當按鈕單擊時,如何在 Tkinter 中建立一個彈窗?


可以在 Tkinter 中定義 Toplevel(win) 視窗來建立彈窗。Toplevel 視窗能建立子視窗和父視窗。它始終開啟在任何應用程式中定義的所有其他視窗之上。我們可以透過初始化 Toplevel(parent) 物件來建立頂級視窗或子視窗。它繼承其父視窗的所有屬性,例如幾何、標題以及寬度或高度。

示例

在此示例中,我們將建立一個按鈕,該按鈕將在所有其他視窗之上開啟一個彈窗。

#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter frame
win.geometry("750x270")

def open_popup():
   top= Toplevel(win)
   top.geometry("750x250")
   top.title("Child Window")
   Label(top, text= "Hello World!", font=('Mistral 18 bold')).place(x=150,y= 80)

Label(win, text=" Click the Below Button to Open the Popup Window", font=('Helvetica 14 bold')).pack(pady=20)
#Create a button in the main Window to open the popup
ttk.Button(win, text= "Open", command= open_popup).pack()
win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,其中有一個按鈕,用於開啟彈窗。

現在,單擊“開啟”按鈕以開啟彈窗。單擊“開啟”按鈕後,螢幕上將出現一個彈窗。

更新時間: 03-May-2021

2K+ 瀏覽

開啟 事業

完成課程拿取證書

開始吧
廣告