如何在 Tkinter 事件中获取小部件名称?
Tkinter 是一个用于创建和开发基于 GUI 的实用应用程序的 Python 库。Tkinter 提供了一些小部件,可用来构建应用程序的可视化及功能性表示。
假设我们在应用程序中定义了一些小部件。如果我们希望在某个事件中获取小部件的名称,那么可以使用函数内部的 event.widget["text"] 关键字来实现。我们可以使用 print() 函数将其打印出来。
示例
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the tkinter window
win.geometry("700x300")
# Define a function to delete the shape
def on_click():
print (win.winfo_children())
# Create a canvas widget
canvas=Canvas(win, width=500, height=300)
canvas.pack()
# Create a button to delete the button
Button(win, text="Click", command=on_click).pack()
win.mainloop()输出
如果我们运行上面的代码,将会显示一个带有按钮的窗口。

如果我们单击按钮,输出将在屏幕上显示小部件的名称。
[<tkinter.Canvas object .!canvas>, <tkinter.Button object .!button>]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP