Tkinter:按下按钮时调用功能

时间:2017-01-03 15:29:49

标签: python tkinter

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的错误。我理解错误,但不明白如何解决它。

4 个答案:

答案 0 :(得分:1)

这是一个可以回答的问题。除了更改commmand=关键字参数以使其在创建tk.Button时不调用该函数,我还从相应的函数定义中删除了event参数,因为{ {1}}没有将任何参数传递给widget命令函数(无论如何,你的函数都不需要它。)

您似乎将事件处理程序与窗口小部件命令函数处理程序混淆。前有一个tkinter参数在他们被调用时传递给他们,但后者通常不会(除非你做其他事情来实现它 - 它&& #39;需要/想做的事情相当普遍,有时被称为The extra arguments trick。)

event

答案 1 :(得分:0)

从两个函数defs中删除'event'参数,并从命令中删除括号。

答案 2 :(得分:0)

使用button.bind()mehtod并传递' Button-1'在第一个参数和第二个参数中的函数名称中 def functionname(event):   #your code

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

答案 3 :(得分:0)

您具有保存加载的函数,该函数带有1个参数:事件,但是在您调用时

# create button to open file
openBtn = tk.Button(win, text = 'Open', command = **load()**) <<<--- no argument in load
                                                       <<<---should be load(someEvent)
openBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)
# create button to save file
saveBtn = tk.Button(win, text = 'Save', command = **save()**)<<< ---- same for the save
saveBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)

但是在您的函数中保存加载参数:事件,您对其不执行任何操作,因此可以删除事件参数,该问题就不会出现。像这样:

def load():
    file = open(textField.GetValue())
    txt.SetValue(file.read())
    file.close()

def save():
    file = open(textField.GetValue(), 'w')
    file.write(txt.GetValue())
    file.close()