如何在 Tkinter 中向事件處理程式傳遞引數?


在大多數情況下,回撥函式可以稱為例項方法。例項方法訪問其所有成員並在不指定任何引數的情況下對它們執行操作。

讓我們考慮一個定義了多個元件並且我們希望使用這些元件處理某些事件的情況。為了執行多個事件,我們更傾向於在事件處理程式中傳遞多個引數。

示例

在此示例中,我們在框架中建立了多個按鈕小部件,我們將透過將小部件的名稱作為引數來處理各種事件。一旦單擊某個按鈕,它將更新標籤小部件,依此類推。

#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
#Define Event handlers for different Operations
def event_low(button1):
   label.config(text="This is Lower Value")
def event_mid(button2):
   label.config(text="This is Medium Value")
def event_high(button3):
   label.config(text="This is Highest value")
#Create a Label
label= Label(win, text="",font=('Helvetica 15 underline'))
label.pack()
#Create a frame
frame= Frame(win)
#Create Buttons in the frame
button1= ttk.Button(frame, text="Low", command=lambda:event_low(button1))
button1.pack(pady=10)
button2= ttk.Button(frame, text="Medium",command= lambda:event_mid(button2))
button2.pack(pady=10)
button3= ttk.Button(frame, text="High",command= lambda:event_high(button3))
button3.pack(pady=10)
frame.pack()
win.mainloop()

輸出

執行以上程式碼將顯示一個包含“低”、“中”和“高”按鈕的視窗。當我們單擊一個按鈕時,它將在視窗上顯示一些標籤文字。

更新於: 2021年4月22日

1K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告