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.


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
style = ttk.Style()

# Define a function to implement choice function
def choice(option):
   if option == "yes":
      label.config(text="Hello, How are You?")
      label.config(text="You have selected No")
def click_fun():
   global pop
   pop = Toplevel(win)
   # Create a Label Text
   label = Label(pop, text="Would You like to Proceed?",
   font=('Aerial', 12))
   # Add a Frame
   frame = Frame(pop, bg="gray71")
   # 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))

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



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.