在 Python TKinter 中建立彈出視窗時停用底層視窗


我們熟悉彈出視窗,並在許多應用程式中使用它。可以在 Tkinter 應用程式中透過建立 Toplevel(root) 視窗的例項來建立彈出視窗。對於特定應用程式,我們可以在按鈕物件上觸發彈出視窗。

讓我們建立一個 Python 指令碼,在顯示彈出視窗後關閉底層或主視窗。可以使用 withdraw() 方法在彈出視窗中駐留時關閉主視窗。

示例

透過此示例,我們將建立一個彈出對話方塊,該對話方塊可以在單擊按鈕後觸發。彈出視窗開啟後,父視窗將自動關閉。

#Import the required library
from tkinter import*
#Create an instance of tkinter frame
win= Tk()
#Define geometry of the window
win.geometry("750x250")
#Define a function to close the popup window
def close_win(top):
   top.destroy()
   win.destroy()
#Define a function to open the Popup Dialogue
def popupwin():
   #withdraw the main window
   win.withdraw()
   #Create a Toplevel window
   top= Toplevel(win)
   top.geometry("750x250")
   #Create an Entry Widget in the Toplevel window
   entry= Entry(top, width= 25)
   entry.insert(INSERT, "Enter Your Email ID")
   entry.pack()
   #Create a Button Widget in the Toplevel Window
   button= Button(top, text="Ok", command=lambda:close_win(top))
   button.pack(pady=5, side= TOP)
#Create a Label
label= Label(win, text="Click the Button to Open the Popup Dialogue", font= ('Helvetica 15 bold'))
label.pack(pady=20)
#Create a Button
button= Button(win, text= "Click Me!", command= popupwin, font= ('Helvetica 14 bold'))
button.pack(pady=20)
win.mainloop()

輸出

當我們執行上述程式碼段時,將顯示一個視窗。

現在單擊“Click Me”按鈕。它將開啟一個彈出視窗並關閉父視窗。

更新於: 15-4-2021

2K+ 瀏覽量

開啟你的職業道路

透過完成課程獲得認證

開始
廣告