What is the correct way to implement a custom popup Tkinter dialog box?

TkinterPythonGUI-Programming

Tkinter has many inbuilt functions and modules which are already implemented in Python. The MessageBox module in Tkinter is one of them that can be used in any application, just by using its associated function. The only limitation with these packages is that we cannot modify or change the MessageBox template. Hence, to implement a Custom Popup MessageBox, we can follow these steps,

  • Create a Button and add a command to define a function to it.
  • Define a function to create a Toplevel window and add other widgets to it.
  • Add Buttons and confirmation Label Text in the Toplevel window.
  • Add the Button commands to display some message in the main window interactively.

Example

# Import required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()
# Set the window size
win.geometry("700x250")

# 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")
def click_fun():
   global pop
   pop = Toplevel(win)
   pop.title("Confirmation")
   pop.geometry("700x250")
   pop.config(bg="green3")
   # Create a Label Text
   label = Label(pop, text="Would You like to Proceed?", bg="green3", fg="white", font=('Aerial', 12))
   label.pack(pady=20)
# Add a Frame
frame = Frame(pop, bg="green3")
frame.pack(pady=10)
# Add Button for making selection
button1 = Button(frame, text="Yes",
command=lambda: choice("yes"), bg="green")
button1.grid(row=0, column=1)
button2 = Button(frame, text="No",
command=lambda: choice("no"), bg="green")
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

Executing the above code will show the window with a button.

When we click the button, it will show a Custom Popup Messagebox

raja
Published on 07-Jun-2021 11:32:17
Advertisements