Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra widget có tồn tại trong Tkinter

Kiểm tra widget tồn tại bằng winfo_exists(). Trả về True(1) nếu tồn tại, False(0) nếu không.

Ví dụ

# Import thư viện
from tkinter import *
from tkinter import ttk

# Tạo khung
win = Tk()
win.geometry("700x250")

# Hàm kiểm tra widget
def check_widget():
    exists = label.winfo_exists()
    if exists == 1:
        print("The widget exists.")
    else:
        print("The widget does not exist.")

# Tạo Label
label = Label(win, text="Hey There! Howdy?", font=('Helvetica 18 bold'))
label.place(relx=.5, rely=.3, anchor=CENTER)

# Nút kiểm tra
button = ttk.Button(win, text="Check", command=check_widget)
button.place(relx=.5, rely=.5, anchor=CENTER)

win.mainloop()

Kết quả

Cửa sổ có Label và nút Check. Click Check in ra console widget có tồn tại.

Kiểm tra widget có tồn tại trong Tkinter

The widget exists.