如何向Tkinter按钮命令中传递参数

Tkinter按钮中的command选项是当用户按下按钮后触发的命令。有些情况下,你还需要向command中传递参数,但是你却不能像下面例子中这样简单的传递参数,

button = tk.Button(app, text="Press Me", command=action(args))

我们将来介绍两种不同的向command中传递参数的方法,

通过partials向Tkinter按钮命令传递参数

Python Tkinter教程-按钮中演示的那样, 你可以通过使用functools模块中的partial对象来传递参数。

from sys import version_info
if version_info.major == 2:
    import Tkinter as tk
elif version_info.major == 3:
    import tkinter as tk
    
from functools import partial
    

    
app = tk.Tk()
labelExample = tk.Button(app, text="0")

def change_label_number(num):
    counter = int(str(labelExample['text']))
    counter += num
    labelExample.config(text=str(counter))
    
buttonExample = tk.Button(app, text="Increase", width=30,
                          command=partial(change_label_number, 2))

buttonExample.pack()
labelExample.pack()
app.mainloop()
buttonExample = tk.Button(app, text="Increase", width=30,
                          command=partial(change_label_number, 2))

partial(change_label_numer, 2)返回了一个可以来调用的对象,在引用的时候它跟一个函数func很类似。

通过lambda函数向Tkinter按钮命令传递参数

你也可以通过Python的lambda操作符或者函数来创建一个临时的、一次性的简单函数用以按钮被按下时候来调用。

from sys import version_info
if version_info.major == 2:
    import Tkinter as tk
elif version_info.major == 3:
    import tkinter as tk
    

    
app = tk.Tk()
labelExample = tk.Button(app, text="0")

def change_label_number(num):
    counter = int(str(labelExample['text']))
    counter += num
    labelExample.config(text=str(counter))
    
buttonExample = tk.Button(app, text="Increase", width=30,
                          command=lambda: change_label_number(2))

buttonExample.pack()
labelExample.pack()
app.mainloop()

lambda函数的语法如下,

lambda: argument_list: expression

具体的通过lamda函数传递参数的语句是,

buttonExample = tk.Button(app, text="Increase", width=30,
                          command=lambda: change_label_number(2))