在 Tkinter 中單擊按鈕時執行多條命令


Button 元件提供了一種透過所有現有應用程式功能進行通訊的方法。藉助 Button,我們可以執行某個操作,其中封裝了函式和物件。但是,有時我們可能希望使用單個按鈕執行多個操作。這可以透過定義 lambda 函式來實現,該 lambda 函式針對應用程式中的多個事件或回撥。

示例

在此示例中,我們將向特定 Button 新增多個事件。

#Import the Tkinter Library
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of window
win.geometry("700x350")

#Define functions
def display_msg():
   label.config(text="Top List of Programming Language")

def show_list():
   listbox= Listbox(win, height=10, width= 15, bg= 'grey', activestyle= 'dotbox',font='aerial')
   listbox.insert(1,"Go")
   listbox.insert(1,"Java")
   listbox.insert(1,"Python")
   listbox.insert(1,"C++")
   listbox.insert(1,"Ruby")
   listbox.pack()
   button.destroy()

#Create a Label widget to display the message
label= Label(win, text= "", font= ('aerial 18 bold'))
label.pack(pady= 20)

#Define a Button widget
button= Button(win, text= "Click Here",command= lambda:[display_msg(), show_list()])
button.pack()
win.mainloop()

輸出

執行以上程式碼,將顯示一個包含按鈕的視窗。

當我們單擊 Button 時,它將並行執行兩個任務。其中會包含一個 Label 元件和一個字串列表的視窗。

更新於:2021-5-25

5000+ 次瀏覽

啟動你的 職業生涯

透過完成該課程獲得認證

開始學習
廣告
© . All rights reserved.