如何將引數傳遞給 Tkinter 按鈕的回撥命令?
Tkinter 按鈕用於處理應用程式中的某些操作。為了處理此類事件,我們通常將定義的函式名作為回撥命令中的值傳遞。對於特定事件,我們還可以在按鈕的命令中將引數傳遞給函式。
有兩種方法可以將引數傳遞到 tkinter 按鈕命令中 −
- 使用 Lambda 或匿名函式
- 使用 Partials
示例
在此示例中,我們將建立一個簡單的應用程式,其中將包含一個文字標籤和一個按鈕來更改標籤文字的值。我們將使用 lambda 函式將標籤作為引數傳遞到按鈕命令中。
#Import necessary Library from tkinter import * from tkinter import ttk #Create an instance of tkinter window win= Tk() #Set the geometry of tkinter window win.geometry("750x250") #Define the function to change the value in label widget def change_text(label): label.configure(text= "Hey, I am Label-2", background="gray91") #Create a Label label = Label(win, text= "Hey, I am Label-1", font= ('Helvetica 15 underline'), background="gray76") label.pack(pady=20) #Create a button btn= ttk.Button(win, text= "Change", command= lambda:change_text(label)) btn.pack(pady=10) win.mainloop()
輸出
執行以上程式碼將顯示一個視窗,其中包含一個文字標籤和一個按鈕以更改標籤的值。
現在單擊“更改”按鈕以更改標籤控制元件的值。
廣告