更新时间:2023-12-02 23:32:04
这是一个可运行的答案.除了更改 commmand=
关键字参数以便在创建 tk.Button
时它不会调用该函数,我还删除了 event
来自相应函数定义的参数,因为 tkinter
不会将任何参数传递给小部件命令函数(无论如何,您的函数不需要它).
Here's a runnable answer. In addition to changing the commmand=
keyword argument so it doesn't call the function when the tk.Button
s are created, I also removed the event
argument from the corresponding function definitions since tkinter
doesn't pass any arguments to widget command functions (and your function don't need it, anyway).
您似乎将事件处理程序与小部件命令函数处理程序混淆了.前者do 有一个 event
参数在它们被调用时传递给它们,但后者通常没有(除非你做额外的事情来让它发生——这是一个需要/想要做的相当普遍的事情,有时被称为额外参数技巧).
You seem to be confusing event handlers with widget command function handlers. The former do have an event
argument passed to them when they're called, but the latter typically don't (unless you do additional stuff to make it happen—it's a fairly common thing to need/want to do and is sometimes referred to as theThe extra arguments trick).
import tkinter as tk
# added only to define required global variable "txt"
class Txt(object):
def SetValue(data): pass
def GetValue(): pass
txt = Txt()
####
def load():
with open(textField.get()) as file:
txt.SetValue(file.read())
def save():
with open(textField.get(), 'w') as file:
file.write(txt.GetValue())
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)
win.mainloop()