How to create a modal dialog in tkinter?


Dialog Boxes are a very essential component of any application. It is generally used to interact with the user and the application interface. We can create dialog boxes for any tkinter application using the Toplevel window and other widgets. The toplevel window pops up the stuff above all the other windows. Thus, we can add more stuff on the toplevel window for building dialog boxes.

Example

In this example, we have created a modal dialog which has two parts,

  • Initialization of the Toplevel window.
  • Function Definition for Popup Dialog Event.
  • Adding widgets in the Toplevel window.
  • Function Definition for Dialog options.
# 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()

Output

When we run the above code, it will display a window with a Button to open the modal dialog box.

Clicking the Button will open the Modal Dialog Box.

Updated on: 08-Jun-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements