如何在Tkinter中将参数传递给Button命令?

2024-04-20 08:46:14 发布

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

假设我用Python中的Tkinter制作了以下Button

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)

当我按下按钮时,方法action被调用,但是如果我想向方法action传递一些参数怎么办?

我尝试了以下代码:

button = Tk.Button(master=frame, text='press', command=action(someNumber))

这只是立即调用该方法,而按按钮什么也不做。


Tags: 方法textimportmastertkinterasbuttonaction
3条回答

图形用户界面示例:

假设我有图形用户界面:

import tkinter as tk

root = tk.Tk()

btn = tk.Button(root, text="Press")
btn.pack()

root.mainloop()

按下按钮会发生什么

请注意,当按下btn时,它会调用自己的函数,这与以下示例中的button_press_handle非常相似:

def button_press_handle(callback=None):
    if callback:
        callback() # Where exactly the method assigned to btn['command'] is being callled

使用:

button_press_handle(btn['command'])

您可以简单地认为应该将command选项设置为对要调用的方法的引用,类似于button_press_handle中的callback


按下按钮时调用方法(Callback

不带参数

因此,如果我想在按下按钮时print某个东西,我需要设置:

btn['command'] = print # default to print is new line

注意print方法中()缺少,省略的意思是:“这是我希望您在按下时调用的方法的名称,但是不要仅在此时调用它。”但是,我没有为print传递任何参数,因此它在没有参数的情况下打印调用时打印的任何内容。

参数

现在,如果我还想将参数传递给按钮按下时要调用的方法,我可以使用匿名函数,在本例中,匿名函数可以用lambda语句创建,用于print内置方法,如下所示:

btn['command'] = lambda arg1="Hello", arg2=" ", arg3="World!" : print(arg1 + arg2 + arg3)

按下按钮时调用多个方法

不带参数

您也可以使用lambda语句来实现这一点,但这被认为是一种不好的做法,因此我在这里不包括它。好的做法是定义一个单独的方法multiple_methods,该方法调用所需的方法,然后将其设置为对按钮的回调按下:

def multiple_methods():
    print("Vicariously") # the first inner callback
    print("I") # another inner callback

参数

为了将参数传递给调用其他方法的方法,再次使用lambda语句,但首先:

def multiple_methods(*args, **kwargs):
    print(args[0]) # the first inner callback
    print(kwargs['opt1']) # another inner callback

然后设置:

btn['command'] = lambda arg="live", kw="as the" : a_new_method(arg, opt1=kw)

从回调返回对象

还要注意的是callback不能真正地return,因为它只在button_press_handle内部用callback()调用,而不是return callback()。它可以return,但在该函数之外的任何地方都不可以。因此,您应该修改当前作用域中可访问的对象。


带有global对象修改的完整示例

下面的示例将调用一个方法,该方法在每次按下按钮时更改btn的文本:

import tkinter as tk

i = 0
def text_mod():
    global i, btn           # btn can be omitted but not sure if should be
    txt = ("Vicariously", "I", "live", "as", "the", "whole", "world", "dies")
    btn['text'] = txt[i]    # the global object that is modified
    i = (i + 1) % len(txt)  # another global object that gets modified

root = tk.Tk()

btn = tk.Button(root, text="My Button")
btn['command'] = text_mod

btn.pack(fill='both', expand=True)

root.mainloop()

Mirror

这也可以通过使用标准库functools中的partial来完成,如下所示:

from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)

我个人更喜欢在这样的场景中使用lambdas,因为在imo中,它更清晰、更简单,而且如果您不能控制被调用的方法,也不会强迫您编写很多包装器方法,但这肯定是一个品味问题。

这就是使用lambda的方法(注意,在功能模块中还有一些curring的实现,所以您也可以使用它):

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

相关问题 更多 >