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