如何在Tkinter中處理按鈕點選事件?


有時,在Tkinter應用程式中處理事件可能會成為一項艱鉅的任務。我們必須管理應用程式執行時需要執行的動作和事件。按鈕部件對於處理此類事件非常有用。我們可以使用Button部件透過在命令中傳遞迴調來執行特定任務或事件。

在向Button部件發出命令時,我們可以使用可選的lambda或匿名函式來解釋忽略程式中的任何錯誤。它們就像普通的函式一樣,但沒有函式體。

示例

在此示例中,我們將建立一個按鈕,並將函式傳遞給它,以便在視窗上顯示一個彈出訊息。

# Import the required libraries
from tkinter import *
from tkinter import messagebox
from tkinter import ttk

# Create an instance of tkinter frame
win= Tk()

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

# Define a function to show the popup message
def show_msg():
   messagebox.showinfo("Message","Hey There! I hope you are doing well.")

# Add an optional Label widget
Label(win, text= "Welcome Folks!", font= ('Aerial 17 bold italic')).pack(pady= 30)

# Create a Button to display the message
ttk.Button(win, text= "Click Here", command=show_msg).pack(pady= 20)
win.mainloop()

輸出

執行以上程式碼將顯示一個帶有Button部件的視窗。當我們點選按鈕時,它將觸發一個事件。

現在,點選按鈕檢視在螢幕上顯示彈出訊息的事件。

更新於:2023年9月14日

36K+瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告