import tkinter as tk
def load(event):
file = open(textField.GetValue())
txt.SetValue(file.read())
file.close()
def save(event):
file = open(textField.GetValue(), 'w')
file.write(txt.GetValue())
file.close()
win = tk.Tk()
win.title('Text Editor')
win.geometry('500x500')
# create text field
textField = tk.Entry(win, width = 50)
textField.pack(fill = tk.NONE, side = tk.TOP)
# create button to open file
openBtn = tk.Button(win, text = 'Open', command = load())
openBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)
# create button to save file
saveBtn = tk.Button(win, text = 'Save', command = save())
saveBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)
我收到错误 load and save are missing a position argument: event
。我理解错误,但不明白如何解决它。
原文由 user7091463 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个可运行的答案。除了更改
commmand=
关键字参数使其在创建tk.Button
时不调用函数外,我还从相应的参数中删除了event
自tkinter
以来的函数定义不会将任何参数传递给小部件命令函数(并且您的函数不需要它,无论如何)。您似乎将事件处理程序与小部件命令函数处理程序混淆了。前者 确实 有一个
event
参数在它们被调用时传递给它们,但后者通常没有(除非你做额外的事情来实现它 - 这是需要/想要的相当普遍的事情做并且有时被称为 额外参数技巧)。