如何在 Tkinter 中檢視小部件是否存在?
為了讓特定的 Tkinter 應用程式具備完整的功能和操作性,我們可以使用任意數量的小部件。如果要檢查小部件是否存在,我們可以使用 winfo_exists() 方法。可以使用要檢查的特定小部件呼叫該方法。它返回一個布林值,其中 True(1) 表示小部件存在於應用程式中,False(0) 表示小部件不存在於應用程式中。
示例
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry
win.geometry("700x250")
# Define a function to check if a widget exists or not
def check_widget():
exists = label.winfo_exists()
if exists == 1:
print("The widget exists.")
else:
print("The widget does not exist.")
# Create a Label widget
label = Label(win, text="Hey There! Howdy?", font=('Helvetica 18 bold'))
label.place(relx=.5, rely=.3, anchor=CENTER)
# We will define a button to check if a widget exists or not
button = ttk.Button(win, text="Check", command=check_widget)
button.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()輸出
執行以上程式碼將顯示一個帶有按鈕和標籤小部件的視窗。在應用程式中,我們可以檢查標籤小部件是否存在。
如果你單擊“檢查”按鈕,它將列印標籤小部件是否存在。
The widget exists.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP