Python Tkinter messagebox + 19 Examples

Keep reading to know more about the Python Tkinter messagebox, we will discuss the messagebox in Python Tkinter with examples.

  • Python Tkinter messagebox
  • Python Tkinter messagebox options
  • Python tkinter messagebox size
  • Python tkinter messagebox askquestion
  • Python tkinter messagebox askyesno
  • Python tkinter messagebox position
  • Python tkinter messagebox documentation
  • Python tkinter yes no dialog box
  • Python tkinter yes no message box
  • Python Tkinter dialog window
  • Python Tkinter dialog yes no
  • Python Tkinter open path using the dialog window
  • Python Tkinter dialog return value
  • Python Tkinter dialog modal
  • Python Tkinter dialog focus
  • Python Tkinter popup message
  • python Tkinter popup input box
  • python Tkinter popup dialog
  • python Tkinter popup menu
  • python Tkinter close popup window

If you are new to Python Tkinter or Python GUI programming, check out Python GUI Programming.

Python tkinter messagebox

  • Messagebox is used to display pop-up messages.
  • To get started with message box import a library messagebox in Python.
  • Messagebox provides mainly 6 types of message prompts like showinfo(), showerror(), showwarning(), askquestion(), askokcancel(), askyesno(), askretyrcancel().
showinfo()used when any confirmation/information needs to display. like login successful, message sent, etc.
showerror()used to display error prompt with sound. The ideal time for its appearance is when the user makes any mistakes or skips the necessary step.
showwarning()Shows warning prompt with exclamation sign. It warns the user about the upcoming errors.
askquestion()It asks the user for Yes or No. also it returns ‘Yes‘ or ‘No
askokcancel()It prompts for ‘Ok’ or ‘Cancel‘, returns ‘True‘ or ‘False
askyesno()It prompts for ‘Yes’ or ‘No’. Returns True for ‘Yes’ and False for ‘No’
askyesnocancel()It prompts for ‘Yes’, ‘No’, or ‘Cancel’. Yes returns True, No returns False, and Cancel returns None
askretrycancel()It prompts with Retry and Cancel options. Retry returns True and Cancel returns False.

Check out, How to Generate Payslip using Python Tkinter

Python tkinter messagebox options

  • Python Messagebox options are already mentioned in the above point
  • So here we will look at it with an example, we will see examples for showinfo(), showwarning(), askquestion(), askokcancel(), askyesno(), askretrycancel().

Syntax:

from tkinter import messagebox
messagebox.option('title', 'message_to_be_displayed')
python tkinter messagebox syntax
python tkinter messagebox

Code:

Here is the code to represent all kinds of message boxes.

from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('Python Guides')
ws.geometry('300x200')
ws.config(bg='#5FB691')

def msg1():
    messagebox.showinfo('information', 'Hi! You got a prompt.')
    messagebox.showerror('error', 'Something went wrong!')
    messagebox.showwarning('warning', 'accept T&C')
    messagebox.askquestion('Ask Question', 'Do you want to continue?')
    messagebox.askokcancel('Ok Cancel', 'Are You sure?')
    messagebox.askyesno('Yes|No', 'Do you want to proceed?')
    messagebox.askretrycancel('retry', 'Failed! want to try again?')

Button(ws, text='Click Me', command=msg1).pack(pady=50)

ws.mainloop()

Output:

Here are the options displayed when Click Me button is clicked.

python tkinter messagebox options
python tkinter messagebox examples

You may like Python Tkinter to Display Data in Textboxes and How to Set Background to be an Image in Python Tkinter.

Python tkinter messagebox size

  • There is no way to change the size of the messagebox.
  • Only more text can stretch the size of messagebox.
  • In this example, I will change the text content to stretch the message box size.

Code:

from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')

def clicked():
    messagebox.showinfo('sample 1', 'this is a message')
    messagebox.showinfo('sample 2', 'this is a message to change the size of box')
    messagebox.showinfo('sample 3', ' this is the message that is larger than previous message.')

Button(ws, text='Click here', padx=10, pady=5, command=clicked).pack(pady=20)

ws.mainloop()

Output:

python tkinter messagebox size
Python tkinter messagebox size

Read How to convert Python file to exe using Pyinstaller

Python tkinter messagebox askquestion

  • askquestion prompt is used to ask questions from the user.
  • The response can be collected in the ‘Yes‘ or ‘No‘ form.
  • This function returns the ‘yes‘ or ‘no‘.
  • These return types can be controlled using an if-else statement.
  • We will see this in the below example.

Code:

In this Python code, we have implemented the askquestion messagebox. We stored the value of messagebox in a variable ‘res’. Then we have compared the variable with the return type i.e ‘yes’ or ‘no’.

from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('Python Guides')
ws.geometry('300x100')

def askMe():
    res = messagebox.askquestion('askquestion', 'Do you like cats?')
    if res == 'yes':
        messagebox.showinfo('Response', 'You like Cats')
    elif res == 'no':
        messagebox.showinfo('Response', 'You must be a dog fan.')
    else:
        messagebox.showwarning('error', 'Something went wrong!')


Button(ws, text='Click here', padx=10, pady=5, command=askMe).pack(pady=20)

ws.mainloop()

Output:

In this output, there is a button which when clicked will prompt with the question. The user will reply in ‘yes’ or ‘no’. accordingly another messagebox will prompt.

python tkinter messagebox askquestion
Python tkinter messagebox askquestion

Read: Python Tkinter Mainloop

Python tkinter messagebox askyesno

  • askyesno is used to prompt users with ‘yes’ or ‘no’ options.
  • the response can be collected in the ‘yes’ or ‘no’ format.
  • askyesno function returns boolean values i.e. ‘True’ or ‘False’.
  • To control the yes or no use if-else statement.

Code:

from tkinter import *
from tkinter import messagebox
import time

ws = Tk()
ws.title('Python Guides')
ws.geometry('400x200')
ws.config(bg='#345')

def quitWin():
    res = messagebox.askyesno('prompt', 'Do you want to kill this window?') 
    if res == True:
        messagebox.showinfo('countdown', 'killing window in 5 seconds')
        time.sleep(5)
        ws.quit()

    elif res == False:
        pass
    else:
        messagebox.showerror('error', 'something went wrong!')

Button(ws, text='Kill the Window', padx=10, pady=5, command=quitWin).pack(pady=50)

ws.mainloop()

Output:

In this output, the user will see a window with the ‘Kill the Window’ button. Once the user will click on this button.

Python tkinter messagebox askyesno
Python tkinter messagebox askyesno

Read Create Word Document in Python Tkinter

Python tkinter messagebox position

  • In this section, we will talk about the messagebox position
  • This can be achieved using a Toplevel widget.
  • any other widget can be placed on a Toplevel widget.
  • It is similar to python frames but is specially created for creating customized prompts.
  • In the below example we have placed image, label & 2 buttons.
  • It will look like a prompt but we can position things as per our requirement.
  • for image we have couple of options listed below.
    • ::tk::icons::error
    • ::tk::icons::information
    • ::tk::icons::warning
    • ::tk::icons::question

Code:

Here is a code in Python to create messagebox with customized position of widgets in it. We have placed an icon or image of the question over here. But you can replace it with ‘error’, ‘warning’, ‘question’ or ‘information’

from tkinter import *

def killWin():
	toplevel = Toplevel(ws)

	toplevel.title("Kill window")
	toplevel.geometry("230x100")


	l1=Label(toplevel, image="::tk::icons::question")
	l1.grid(row=0, column=0)
	l2=Label(toplevel,text="Are you sure you want to Quit")
	l2.grid(row=0, column=1, columnspan=3)

	b1=Button(toplevel,text="Yes",command=ws.destroy, width=10)
	b1.grid(row=1, column=1)
	b2=Button(toplevel,text="No",command=toplevel.destroy, width=10)
	b2.grid(row=1, column=2)


ws = Tk()
ws.geometry("300x200")
ws.title('Python Guides')
ws.config(bg='#345')
Button(ws,text="Kill the window",command=killWin).pack(pady=80)

ws.mainloop()

Output:

In this output, the main window has a button which when clicked will prompt a user whether he wants to quit this page or not. If a user says ‘Yes’ this page will disappear’. Since it is a question you can notice a small icon of a question mark on the left side of the prompt.

python tkinter messagebox position
Python tkinter messagebox position

Read Python Number Guessing Game

Python tkinter messagebox documentation

Information message box

To display information showinfo function is used.

Warning message box

To display warning or error message showwarning and showerror is used.

Question message box

To ask question there are multiple options:

  • askquestion
  • askokcancel
  • askretrycancel
  • askyesno
  • askyesnocancel

Python tkinter yes no dialog box

Let us see, how to generate Yes or No Popups in Python Tkinter or Python tkinter yes no message box. Python Tkinter provides a messagebox module that allows generating Yes and No prompts.

  • Yes or No Popups are used to ask for confirmation before performing a task. It is mainly used to make sure that the user has not accidentally triggered a task.
  • Yes or No prompts can be seen while the user is about to exit the program or while he is about to initiate any sensitive task. for example, while transferring money you see a prompt “Do you want to Proceed”.
  • There are two functions inside the messagbox module that are used to generate Yes or No Prompts:
    • messagebox.askquestion()
    • messagebox.askyesno()
  • messagebox.askquestion() function is used to ask a question from the user and the user has to reply in yes or no. The function returns True when the user clicks on the Yes button and Flase when the user clicks on the No button.
  • messagebox.askyesno() function also does the same thing that it asks the user to reply in yes or no. The function returns True for yes and False for no.
  • We have a complete section on Python Tkinter messagebox with an example. In this, we have covered all the available options for message box.

Syntax:

  • Here is the syntax of the messagebox in Python Tkinter. In the first line, we have imported the messagebox module from the Tkinter library.
  • In the second line, the option is the function that will generate a prompt. There are seven options to generate the prompt but in this tutorial, we’ll discuss only two of them:
    • messagebox.askquestion()
    • messagebox.askyesno()
from tkinter import messagebox

messagebox.option('title', 'message_to_be_displayed')

Example of Yes No popups in Python Tkinter

  • This application shows two options to the user. One is to donate & another one is to Exit the application.
  • If the user clicks on the transfer button, askquestion() function is triggered & it requests the user for confirmation.
  • if the user clicks on the Exit button, askyesno() function is triggered and it asks the user if he is sure to exit the application.
from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#4a7a8c')

def askQuestion():
    reply = messagebox.askyesno('confirmation', 'Are you sure you want to donate $10000 ?')
    if reply == True:
        messagebox.showinfo('successful','You are the Best!')
    else:
        messagebox.showinfo('', 'Maybe next time!')
       

def askYesNo():
    reply = messagebox.askyesno('confirmation', 'Do you want to quit this application?')
    if reply == True:
        messagebox.showinfo('exiting..', 'exiting application')
        ws.destroy()
    else:
        messagebox.showinfo('', 'Thanks for Staying')
       

btn1 = Button(
    ws,
    text='Transfer',
    command=askQuestion,
    padx=15,
    pady=5
)
btn1.pack(expand=True, side=LEFT)

btn2 = Button(
    ws,
    text='Exit',
    command=askYesNo,
    padx=20,
    pady=5
)
btn2.pack(expand=True, side=RIGHT)

ws.mainloop()

Output of the above code

Here is the output of the above code, In this code user wants to exit the application. He sees Yes No popup after clicking on the exit button.

Python tkinter yes no dialog box
Yes No Popups in Python Tkinter

This is how to generate Yes No Popup in Python Tkinter or Python Tkinter yes no dialog box.

Read Python Tkinter Filter Function()

Python Tkinter dialog window

In this section, we will learn how to create a dialog window in Python Tkinter.

A dialog window is used to communicate between the user and the software program or we can also say that it is simply used to display the message and require acknowledgment from the user.

Code:

In the following code, we import the library Simpledialog which is used for creating a dialog window to get the value from the user.

  • simpledialog.askinteger() is used to get an integer from the user.
  • simpledialog.askstring() is used to get a string value from the user.
  • simpledialog.askfloat() is used to get a float value from the user.
from tkinter import *
from tkinter import simpledialog

ws = Tk()
ws.title("Python Guides")

answer1 = simpledialog.askstring("Input", "What is your first name?",
                                parent=ws)
if answer1 is not None:
    print("Your first name is ", answer1)
else:
    print("You don't have a first name?")

answer1 = simpledialog.askinteger("Input", "What is your age?",
                                 parent=ws,
                                 minvalue=0, maxvalue=100)
if answer1 is not None:
    print("Your age is ", answer1)
else:
    print("You don't have an age?")

answer1 = simpledialog.askfloat("Input", "What is your salary?",
                               parent=ws,
                               minvalue=0.0, maxvalue=100000.0)
if answer1 is not None:
    print("Your salary is ", answer1)
else:
    print("You don't have a salary?")
ws.mainloop()

Output:

After running the above code we get the following output in which we see a dialog window in which users enter their names. After entering the name click on ok.

Python Tkinter dialog box window
Python Tkinter dialog box window Output

After clicking on ok next dialog window will open in which the user can enter their name. After entering their age click on OK.

Python tkinter dialog box window1
Python Tkinter dialog box window1 Output

After clicking on ok next dialog window will open where the user can enter their salary and finally click on ok.

Python Tkinter dialog box window2
Python Tkinter dialog box window2 Output

After clicking on ok the overall data will show on the command prompt.

Python Tkinter dialog box window3
Python Tkinter dialog box window3 Output

Read Python Tkinter add function with examples

Python Tkinter dialog yes no

In this section, we will learn how to create a yes or no dialog box in Python Tkinter.

This is an alert dialog box in which users can choose they want to continue or quit. if the user wants to quit click on the Yes if they don’t want to quit click on No.

Output:

In the following code, we import tkinter.messagebox library for giving the alert message yes and no. We also create a window and giving the title “Python Guides” to the window on which a yes or no pop-up message will show.

askyesno()function to show a dialog that asks for user confirmation.

from tkinter import *
from tkinter.messagebox import askyesno

# create the root window
ws = Tk()
ws.title('Python Guides')
ws.geometry('200x200')

# click event handler
def confirm():
    answer = askyesno(title='confirmation',
                    message='Are you sure that you want to quit?')
    if answer:
        ws.destroy()


Button(
    ws,
    text='Ask Yes/No',
    command=confirm).pack(expand=True)


# start the app
ws.mainloop()

Output:

In the following output, we see the window on which a yes or no pop-up message will show.

Python tkinter dialog yes or no
Python Tkinter dialog yes or no Output

After clicking on Ask yes/No the confirmation message will show “Are you sure that you want to quit?” with the yes and No buttons. On clicking on yes all the programs will quit otherwise they stay on the first window.

Python tkinter Dialog yes no confirmation
Python Tkinter Dialog Confirmation Yes or No

Read Python Tkinter panel

Python Tkinter open path using the dialog window

In this section, we will learn how to create an open path using the dialog box in Python Tkinter.

The open dialog allows the user to specify the drive, directory, and the name of the file to open.

Code:

In the following code, we import library filedialog as fd and also create window ws= Tk() with the title “Python Guides”.

  • fd.askopenfilename() function return the file name we selected and also support other function that displayed by dialog.
  • error_msg = It show the error msg when file is not supported.
  • Button() can display the text or images.
from tkinter import *
from tkinter import filedialog as fd 
ws = Tk()
ws.title("Python Guides")
ws.geometry("100x100")
def callback():
    name= fd.askopenfilename() 
    print(name)
    
error_msg = 'Error!'
Button(text='File Open', 
       command=callback).pack(fill=X)
ws.mainloop()

Output:

In the following output we see a window inside the window we add a button with the name“File Open”.

Python tkinter open path using dialog window
Python Tkinter open path using dialog window Output

After clicking the button a dialog box is open. Select the file name after selecting click on the open button.

Python Tkinter open path using dialog window 1
Python Tkinter open path using dialog window 1 Output

After clicking on the open button the file path and location is shown on the command prompt as shown in this image.

Python Tkinter open path using dialog window2
Python Tkinter open path using dialog window2 Output

Read Python Tkinter after method

Python Tkinter dialog return value

In this section, we will learn how to create a dialog return value in python Tkinter.

The return value is something when the user enters the number in a dialog. And the number entered by the user is displayed on the main window as a return value.

Code:

In the following code, we create a window ws = TK() inside the window we add a button with the text “Get Input”. We also create labels and entries for taking the input from the user.

  • Label() function is used as a display box where the user can place text.
  • Button() is used for submitting the text.
  • customdialog() is used to get the pop-up message on the main window.
from tkinter import *


class customdialog(Toplevel):
    def __init__(self, parent, prompt):
        Toplevel.__init__(self, parent)

        self.var = StringVar()

        self.label = Label(self, text=prompt)
        self.entry = Entry(self, textvariable=self.var)
        self.ok_button = Button(self, text="OK", command=self.on_Ok)

        self.label.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x")
        self.ok_button.pack(side="right")

        self.entry.bind("<Return>", self.on_Ok)

    def on_Ok(self, event=None):
        self.destroy()

    def show(self):
        self.wm_deiconify()
        self.entry.focus_force()
        self.wait_window()
        return self.var.get()

class example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.button = Button(self, text="Get Input", command=self.on_Button)
        self.label = Label(self, text="", width=20)
        self.button.pack(padx=8, pady=8)
        self.label.pack(side="bottom", fill="both", expand=True)

    def on_Button(self):
        string = customdialog(self, "Enter something:").show()
        self.label.configure(text="You entered:\n" + string)


if __name__ == "__main__":
    ws = Tk()
    ws.title("Python Guides")
    ws.geometry("200x200")
    example(ws).pack(fill="both", expand=True)
    ws.mainloop()

Output:

After running the above code we get the following output in this we create a window inside the window we add a button with the title “Get Input”.

Python tkinter dialog return value
Python Tkinter dialog return value Output

After clicking on the “Get Input” button we get a dialog box. Inside the dialog box user can enter anything. After entering input click on the OK button.

Python Tkinter dialog return value1
Python Tkinter dialog return value1 Output

After clicking on the ok button we get the return value on the main window.

Python Tkinter dialog return value2
Python Tkinter dialog return value2 Output

Read Python Tkinter save text to file

Python Tkinter dialog modal

In this section, we will learn how to create a dialog modal in Python Tkinter.

The modal window creates a way that damages the main window but makes it visible with the modal window. We can use the modal window as the main window. This is design for computer applications.

Code:

In the following code, we import .ttk import Style library for giving the style to the window. Here we create a window inside the window we add some labels and buttons.

  • Label()function is used as a display box where the user can place text.
  • Button()function is used when the user is pressed a button by a mouse click some action is started.
  • Pop.destroy() is used for destroying the window after use.
from tkinter import *
from tkinter.ttk import Style

ws = Tk()
ws.title("Python Guides")

ws.geometry("200x250")
style = Style()
style.theme_use('clam')

def choice1(option):
   pop1.destroy()
   if option == "yes":
      label1.config(text="Hello, How are You?")
   else:
      label1.config(text="You have selected No")
      ws.destroy()
def click_fun1():
   global pop1
   pop1 = Toplevel(ws)
   pop1.title("Confirmation")
   pop1.geometry("300x150")
   pop1.config(bg="white")

   label1 = Label(pop1, text="Would You like to Proceed?",
   font=('Aerial', 12))
   label1.pack(pady=20)

   frame1 = Frame(pop1, bg="gray71")
   frame1.pack(pady=10)
   
   button_1 = Button(frame1, text="Yes", command=lambda: choice1("yes"), bg="blue", fg="black")
   button_1.grid(row=0, column=1)
   button_2 = Button(frame1, text="No", command=lambda: choice1("no"), bg="blue", fg="black")
   button_2.grid(row=0, column=2)

label1 = Label(ws, text="", font=('Aerial', 14))
label1.pack(pady=40)

Button(ws, text="Click Here", command=click_fun1).pack()

ws.mainloop()

Output:

In the following output, we see a window inside the window a button is placed. By clicking on the “Click Here” button some action is started and move to the next command.

Python Tkinter dialog modal
Python Tkinter dialog modal Output

After click on the “Click Here” button, the confirmation window is open with the text “Would You Like to Proceed” if yes click on yes if no click on.

Python Tkinter dialog modal1
Python Tkinter dialog modal1 Output

After click on the yes button, we see some text is showing o the main window.

Python Tkinter dialog modal2
Python Tkinter dialog modal2 Output

Python Tkinter dialog focus

In this section, we will learn how to create a dialog focus in Python Tkinter.

Before moving forward we should have a piece of knowledge about focus. Focus is that to giving attention to a particular thing or we can say that a center point of all the activity.

Dialog focus is when the user enters some input into a dialog box and wants to move forward then they click on the button so there completely focus on the button.

Code:

In the following code, we create a window inside the window we create an entry widget and buttons. Button widget which complete has the focus.

  • Entry()is used for giving input from the user.
  • Button() function is used when the user is pressed a button by a mouse click some action is started.

from tkinter import *
from tkinter.ttk import *

ws = Tk()
ws.title("Python Guides")

entry1 = Entry(ws)
entry1.pack(expand = 1, fill = BOTH)

entry2 = Button(ws, text ="Button")

entry2.focus_set()
entry2.pack(pady = 5)

entry3 = Radiobutton(ws, text ="Hello")
entry3.pack(pady = 5)

ws.mainloop()

Output:

Here is a dialog widget in which the user enters the input and future proceeding they click on the button. In this the button widget completely has focus.

Python tkinter dialog focus3

So, in this tutorial, we discussed Python Tkinter Dialog Box Window and we have also covered different examples.

Python Tkinter popup message

In this section, we will learn about how to create a Popup message in Python Tkinter.

Before moving forward we should have a piece of knowledge about Popup. Popup is defined as notification that occurs suddenly and catches the audience’s attention. Popup message occurs on the user window.

Code:

In the following code, we create a window inside the window we also create a button with the text “Click Me”. After clicking on them a Popup window will be open.

import tkinter.messagebox importing this library for showing the message on the Popup screen.

tkinter.messagebox.showinfo() is used for displaying the important information.

from tkinter import *

import tkinter.messagebox

ws = Tk()

ws.title("Python Guides")
ws.geometry("500x300")

def on_Click():
	tkinter.messagebox.showinfo("Python Guides", "Welcome")


but = Button(ws, text="Click Me", command=on_Click)

but.pack(pady=80)
ws.mainloop() 

Output:

In the following output, we see a window inside the window a button is placed.

Python Tkinter Popup message
Python Tkinter Popup message Output

By clicking on this button a Popup window is generated which shows some message.

Create popup message in Python Tkinter
Create popup message in Python Tkinter

Python Tkinter popup input box

In this following section, we will learn how to create a Popup input box in Python Tkinter.

Inputbox is where the user can enter some value, text after entering there is a button to move forward to complete the task. The Popup input box is similar where the user can insert the text when the pop input box window will appear.

Code:

In the following code, we create a window inside the window we add a label and button. We also define a Popup input window as Popup_win inside this window we create an entry where we can insert some text.


from tkinter import*

ws= Tk()
ws.title("Python Guides")

ws.geometry("500x300")

def closewin(tp):
   tp.destroy()
def insert_val(e):
   e.insert(0, "Hello Guides!")

def popup_win():
  
   tp= Toplevel(ws)
   tp.geometry("500x200")
   
   entry1= Entry(tp, width= 20)
   entry1.pack()

   Button(tp,text= "Place text", command= lambda:insert_val(entry1)).pack(pady= 5,side=TOP)
   
   button1= Button(tp, text="ok", command=lambda:closewin(tp))
   button1.pack(pady=5, side= TOP)

label1= Label(ws, text="Press the Button to Open the popup dialogue", font= ('Helvetica 15 bold'))
label1.pack(pady=20)

button1= Button(ws, text= "Press!", command= popup_win, font= ('Helvetica 16 bold'))
button1.pack(pady=20)
ws.mainloop()

Output:

In the following output, we see a label and button present on the window where the label is used to describe the task and the button is used for continuing the task.

Python Tkinter Popup input box
Python Tkinter Popup input box Output

On the clicking, the Press button a Popup input box is shown on the screen where we can insert some text in the input box on clicking on the place text button. After inserting click on the ok button.

Popup input box using Python Tkinter
Popup input box using Python Tkinter

Python Tkinter popup dialog

In the following section, we will learn how to create a Popup dialog in Python Tkinter.

The Popup dialog box is similar to the popup message this is shown on top of the existing window.

Code:

In the following code, we see a window inside the window buttons are placed on clicking on any of these buttons a Popup dialog box appear on the screen.

from tkinter import *

import tkinter.messagebox

ws = Tk()

ws.title("Python Guides")
ws.geometry('500x300')

def Eastside():
	tkinter.messagebox.showinfo("Python Guides", "Right button Clicked")

def Westside():
	tkinter.messagebox.showinfo("Python Guides", "Left button Clicked")

def Northside():
	tkinter.messagebox.showinfo("Python Guides", "Top button Clicked")

def Southside():
	tkinter.messagebox.showinfo("Python Guides", "Bottom button Clicked")

button1 = Button(ws, text="Left", command=Westside, pady=10)
button2 = Button(ws, text="Right", command=Eastside, pady=10)
button3 = Button(ws, text="Top", command=Northside, pady=10)
button4 = Button(ws, text="Bottom", command=Southside, pady=10)

button1.pack(side=LEFT)
button2.pack(side=RIGHT)
button3.pack(side=TOP)
button4.pack(side=BOTTOM)

ws.mainloop()

Output:

After running the above code we get the following output in which we see four buttons Paced at “Top”, “Bottom”, “Left”, “Right” inside the window.

Python Tkinter Popup dialog
Python Tkinter Popup dialog Output

On clicking on the Top button a Popup dialog open with the message“Top button

Create a popup dialog in python Tkinter
Create a popup dialog in Python Tkinter

Python Tkinter popup menu

In this section, we will learn how to create a Popup menu in Python Tkinter.

The Popup menu appears on the main window by right-clicking on the main window. A menu bar is Popup on the screen with limited choices.

Code:

In the following code, we create a window inside the window we add a label with the text “Right-click To Display a Menu”.As the label describes what to do as the menu bar is Popup on the screen.

  • Menu() is used to display the menubar on the screen.
  • pop_up.add_command()is used to add some command in the menubar.
from tkinter import *

ws = Tk()
ws.title("Python Guides")

ws.geometry("500x300")

label1 = Label(ws, text="Right-click To Display a Menu", font= ('Helvetica 16'))
label1.pack(pady= 40)

pop_up = Menu(ws, tearoff=0)

pop_up.add_command(label="New")
pop_up.add_command(label="Edit")
pop_up.add_separator()
pop_up.add_command(label="Save")

def menupopup(event):
   
   try:
      pop_up.tk_popup(event.x_root, event.y_root, 0)
   finally:
      
      pop_up.grab_release()

ws.bind("<Button-3>", menupopup)

button1 = Button(ws, text="Exit", command=ws.destroy,width=6,height=4)
button1.pack()

ws.mainloop()


Output:

In the following output, as we see there is a label and button place inside the window.

Python Tkinter popup menu
Python Tkinter popup menu

When we right-click anywhere on the window menubar is a popup on the window.

Popup menu using Python Tkinter
Popup menu using Python Tkinter

Python Tkinter close popup window

In this section, we will learn how we can create close the popup window in Python Tkinter.

In the close popup window, we want to close the window that is currently Popup on the screen.

Code:

In the following code, we import tkinter.messagebox library for showing the message on the popup window and want to close this window with a show warning message.

  • tkinter.messagebox.askyesno() is used for taking the user response if they want to quit click on yes if no click on no.
  • tkinter.messagebox.showwarning() is used for showing the warning for verifying the user response.
  • tkinter.messagebox.showinfo() is used for showing the information that the POPup window is closed.
from tkinter import *
import tkinter.messagebox 

ws=Tk()
ws.title("Python Guides")
ws.geometry("300x200")


def callfun():
    if tkinter.messagebox.askyesno('Python Guides', 'Really quit'):
        tkinter.messagebox.showwarning('Python Guides','Close this window')
    else:
        tkinter.messagebox.showinfo('Python Guides', 'Quit has been cancelled')

Button(text='Close', command=callfun).pack(fill=X)

ws.mainloop()

Output:

In the following output er see a window inside a window a button is placed on clicking on them we get askyesno message.

Python Tkinter close popup window
Python Tkinter close popup window Output

As shown in this picture we choose the option yes or no if we want to close the popup window then click on yes.

Python Tkinter close popup window
Close popup window Tkinter

After clicking on yes we see this popup window come on the screen by click on the ok button they close the popup window.

How to close Python Tkinter popup window
Python Tkinter close popup window

You may like the following Python tutorials:

In this tutorial, we have learned about Python tkinter messagebox. We have also covered these topics.

  • Python tkinter messagebox
  • python tkinter messagebox options
  • python tkinter messagebox size
  • python tkinter messagebox askquestion
  • python tkinter messagebox askyesno
  • python tkinter messagebox position
  • python tkinter messagebox documentation
  • Python tkinter yes no message box
  • Python tkinter yes no dialog box
  • Python Tkinter dialog window
  • Python Tkinter dialog yes no
  • Python Tkinter open path using the dialog window
  • Python Tkinter dialog return value
  • Python Tkinter dialog modal
  • Python Tkinter dialog focus
  • Python Tkinter popup message
  • python Tkinter popup input box
  • python Tkinter popup dialog
  • python Tkinter popup menu
  • python Tkinter close popup window