如何在 tkinter 中建立一個模態對話方塊?


對話方塊是任何應用程式中非常重要的元件。它通常用於使用者和應用程式介面互動。我們可以使用頂級視窗和其他小部件為任何 tkinter 應用程式建立對話方塊。頂級視窗會彈出高於所有其他視窗的內容。因此,我們可以在頂級視窗中新增更多內容來構建對話方塊。

示例

在此示例中,我們建立了一個模態對話方塊,它包含兩部分,

  • 頂級視窗的初始化。
  • 彈出對話方塊事件的函式定義。
  • 在頂級視窗中新增小部件。
  • 對話方塊選項的函式定義。
# Import required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the window size
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')

# Define a function to implement choice function
def choice(option):
   pop.destroy()
   if option == "yes":
      label.config(text="Hello, How are You?")
   else:
      label.config(text="You have selected No")
      win.destroy()
def click_fun():
   global pop
   pop = Toplevel(win)
   pop.title("Confirmation")
   pop.geometry("300x150")
   pop.config(bg="white")
   # Create a Label Text
   label = Label(pop, text="Would You like to Proceed?",
   font=('Aerial', 12))
   label.pack(pady=20)
   # Add a Frame
   frame = Frame(pop, bg="gray71")
   frame.pack(pady=10)
   # Add Button for making selection
   button1 = Button(frame, text="Yes", command=lambda: choice("yes"), bg="blue", fg="white")
   button1.grid(row=0, column=1)
   button2 = Button(frame, text="No", command=lambda: choice("no"), bg="blue", fg="white")
   button2.grid(row=0, column=2)
# Create a Label widget
label = Label(win, text="", font=('Aerial', 14))
label.pack(pady=40)

# Create a Tkinter button
ttk.Button(win, text="Click Here", command=click_fun).pack()

win.mainloop()

輸出

當我們執行以上程式碼時,它將顯示一個帶按鈕的視窗,用於開啟模態對話方塊。

單擊按鈕將開啟模態對話方塊。

上次更新時間: 08-Jun-2021

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.