python - Tkinter:按下按钮时调用函数

标签 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)

我得到的错误是加载和保存缺少位置参数:事件。我了解错误,但不知道如何解决。

最佳答案

这是一个可运行的答案。除了更改 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()

关于python - Tkinter:按下按钮时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41447065/

相关文章:

python - 不显示删除的 Sprite ,Pygame

python - Tkinter 中的程序窗口锁定

python - Tkinter ttk.treeview iid 会溢出吗?

python - 忽略前面没有定界符的可选后缀

Python解析空字符串

python - 如何使用 winsound 阻止声音相互叠加? (Python 和 tkinter)

python - 如何在 tkinter 中显式调整帧大小?

python - 在 Python (Tkinter) 中的同一窗口内混合两个布局管理器

python - 过滤数据框并根据给定条件添加新列

python - 如何确定 numba 的 prange 是否真的正常工作?