Tkinter:按下按钮时调用功能

2024-05-18 14:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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。我理解这个错误,但不知道如何解决它。


Tags: texteventsavetopcreateloadopenfill
3条回答

从两个函数def中删除“event”参数,并从命令中删除方括号。

使用button.bind()方法并在第一个参数中传递“button-1”,在第二个参数中传递函数名 定义函数名(事件): #你的代码

button = tk.Button(win, text="Login", bg="green")#, command=attempt_log_in)
button.grid(row=5, column=2)
button.bind('<Button-1>', functionname)

这是一个合理的答案。除了更改commmand=关键字参数以使其在创建tk.Button时不调用函数外,我还从相应的函数定义中删除了event参数,因为tkinter不向小部件命令函数传递任何参数(无论如何,您的函数不需要它)。

您似乎混淆了事件处理程序和小部件命令函数处理程序。前者在被调用时会有一个event参数传递给它们,但后者通常不会(除非您做了额外的事情来实现它,否则需要/想要做的事情相当常见,有时称为The 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()

相关问题 更多 >

    热门问题