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

Cách ẩn/hủy cửa sổ gốc (root window) Tkinter?

Khi test Tkinter, có thể cần ẩn hoặc hủy cửa sổ mặc định. 2 phương pháp:

  • destroy(): hủy hoàn toàn cửa sổ.
  • withdraw(): ẩn cửa sổ (vẫn tồn tại, không hiển thị).

mainloop() chạy cho đến khi đóng. Dùng destroy() trong hàm đóng. Dùng withdraw() để ẩn.

Ví dụ

from tkinter import *

win = Tk()
win.geometry("700x400")

def disable_button():
    win.destroy()  # Hoặc win.withdraw() để ẩn

Label(win, text="Type Something", font=('Helvetica bold', 25), fg="green").pack(pady=20)
Text(win, height=10, width=40).pack()
Button(win, text="Quit", command=disable_button, fg="white", bg="black", width=20).pack(pady=20)

# win.withdraw()  # Bỏ comment để ẩn ngay từ đầu

win.mainloop()

Kết quả

Click Quit sẽ hủy (hoặc ẩn) cửa sổ gốc.

Cách ẩn/hủy cửa sổ gốc (root window) Tkinter?