如何向 Tkinter 按鈕命令中傳遞引數

Jinku Hu 2023年1月30日 2018年2月20日
  1. 通過 partials 向 Tkinter 按鈕命令傳遞引數
  2. 通過 lambda 函式向 Tkinter 按鈕命令傳遞引數
如何向 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))
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

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

相關文章 - Tkinter Button