如何在 Tkinter 子級 widget 上捕獲事件?
假設我們正在建立一個應用,該應用會與使用者點選應用中可見的按鈕進行互動。為了瞭解事件是如何工作的,我們必須建立一個回撥函式以及一個觸發事件的觸發器。每當使用者點選按鈕時,事件就會發生,並且需要將其捕獲到螢幕上。
示例
在這個示例中,我們將建立一個 Listbox widget,其中會有一份專案清單。當我們選擇一個專案時,它會捕獲使用者點選的內容。為了找出被捕獲事件,我們可以使用print() 函式在螢幕上列印。
# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") # Create a Listbox widget lb=Listbox(win) lb.pack(expand=True, fill=BOTH) # Define a function to edit the listbox ite def save(): for item in lb.curselection(): print("You have selected "+ str(item+1)) # Add items in the Listbox lb.insert("end","item1","item2","item3","item4","item5") # Add a Button To Edit and Delete the Listbox Item ttk.Button(win, text="Save", command=save).pack() win.mainloop()
輸出
執行上述程式碼將顯示一個視窗,其中列出了一個專案清單。如果我們點選“儲存”按鈕,它會告訴我們捕獲了什麼事件。
現在,從列表中選擇一個專案並點選“儲存”按鈕。它會在控制檯中打印出你選擇的專案。
You have selected 3
廣告