如何在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP