如何在 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