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
。我理解这个错误,但不知道如何解决它。
从两个函数def中删除“event”参数,并从命令中删除方括号。
使用button.bind()方法并在第一个参数中传递“button-1”,在第二个参数中传递函数名 定义函数名(事件): #你的代码
这是一个合理的答案。除了更改
commmand=
关键字参数以使其在创建tk.Button
时不调用函数外,我还从相应的函数定义中删除了event
参数,因为tkinter
不向小部件命令函数传递任何参数(无论如何,您的函数不需要它)。您似乎混淆了事件处理程序和小部件命令函数处理程序。前者在被调用时会有一个
event
参数传递给它们,但后者通常不会(除非您做了额外的事情来实现它,否则需要/想要做的事情相当常见,有时称为The extra arguments trick)。相关问题 更多 >
编程相关推荐