Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีซ่อนหรือลบ Tkinter Root Window

บางครั้งขณะทดสอบแอปพลิเคชัน Tkinter เราอาจต้องการซ่อน Tkinter Default Window หรือ Frame มี 2 วิธีทั่วไปที่เราสามารถซ่อนหรือทำลาย Tkinter Window ได้

mainloop() ทำให้ Tkinter Window ทำงานต่อเนื่องจนกว่าจะถูกปิดโดย External Events เพื่อทำลายหน้าต่าง เราสามารถใช้เมธอด destroy() ที่เรียกได้ (Callable)

อย่างไรก็ตาม เพื่อซ่อน Tkinter Window เรามักใช้เมธอด "withdraw" ที่สามารถเรียกใช้บน Root Window หรือ Main Window ได้

ในตัวอย่างนี้ เราสร้าง Text Widget และปุ่ม "Quit" ที่จะปิด Root Window ทันที อย่างไรก็ตาม เราสามารถใช้เมธอด withdraw เพื่อไม่ให้แสดงบนหน้าจอได้

ตัวอย่าง

# Import the library
from tkinter import *

# Create an instance of window
win = Tk()

# Set the geometry of the window
win.geometry("700x400")

def disable_button():
    win.destroy()

# Create a Label
Label(win, text="Type Something", font=('Helvetica bold', 25), fg="green").pack(pady=20)

# Create a Text widget
text = Text(win, height=10, width=40)
text.pack()

# Create a Disable Button
Button(win, text="Quit", command=disable_button, fg="white", bg="black", width=20).pack(pady=20)

# win.withdraw()
win.mainloop()

โค้ด Python ข้างต้นซ่อน Root Window โดยใช้เมธอด withdraw อย่างไรก็ตาม เพื่อทำลายหน้าต่าง เราสามารถใช้เมธอด destroy ได้

ผลลัพธ์

วิธีซ่อนหรือลบ Tkinter Root Window

เมื่อคุณคลิกปุ่ม Quit จะซ่อน Root Window