如何在Python Tkinter中僅關閉頂級視窗?


頂級視窗是一個選項,用於在應用程式中建立子視窗。它類似於預設的主 tkinter 視窗。我們可以配置頂級視窗的大小,自定義其屬性以及新增想要用來構建元件的小部件。

對於特定應用程式,如果我們定義了一個頂級視窗,我們使用destroy()方法來關閉它。

示例

在下面的示例中,我們建立了一個應用程式,包含一個按鈕,用於開啟一個頂級視窗。頂級視窗或子視窗包含一個標籤文字和一個用於關閉相應視窗的按鈕。每當單擊按鈕時,頂級視窗都會被關閉。

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x400")
win.title("Root Window")

# Function to create a toplevel window
def create_top():
   top=Toplevel(win)
   top.geometry("400x250")
   top.title("Toplevel Window")
   Label(top, text="Hello, Welcome to Tutorialspoint", font='Arial 15 bold').pack()

   # Button to close the toplevel window
   button=Button(top, text="Close", command=top.destroy)
   button.pack()

# Create a button to open the toplevel window
button=Button(win, text="Click Here", font='Helvetica 15', command=create_top)
button.pack(pady=30)

win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,其中包含一個用於開啟頂級視窗的按鈕。

一旦開啟頂級視窗,你可以單擊“關閉”按鈕以關閉頂級視窗。

更新時間: 22-Dec-2021

3K+ 次瀏覽

開啟您的 事業

完成課程,取得認證

開始
廣告