如何向 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))
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn