Tkinter:按下按钮时调用函数 [英] Tkinter: Calling function when button is pressed

查看:84
本文介绍了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 和 save 缺少位置参数:event.我理解错误,但不知道如何解决.

I get the error that load and save are missing a position argument: event. I understand the error, but don't understand how to resolve it.

推荐答案

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

这篇关于Tkinter:按下按钮时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆