如何向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))