Python messagebox error

Python offers multiple options for developing GUI Graphical User Interface . Out of all the GUI methods tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

    Note: For more information, refer to Python GUI – tkinter

    MessageBox Widget

    Python Tkinter – MessageBox Widget is used to display the message boxes in the python applications. This module is used to display a message using provides a number of functions.

    Syntax:

    messagebox.Function_Name(title, message [, options]) 

    Parameters:
    There are various parameters :

    • Function_Name: This parameter is used to represents an appropriate message box function.
    • title: This parameter is a string which is shown as a title of a message box.
    • message: This parameter is the string to be displayed as a message on the message box.
    • options: There are two options that can be used are:
      1. default: This option is used to specify the default button like ABORT, RETRY, or IGNORE in the message box.
      2. parent: This option is used to specify the window on top of which the message box is to be displayed.

    Function_Name:
    There are functions or methods available in the messagebox widget.

    1. showinfo(): Show some relevant information to the user.
    2. showwarning(): Display the warning to the user.
    3. showerror(): Display the error message to the user.
    4. askquestion(): Ask question and user has to answered in yes or no.
    5. askokcancel(): Confirm the user’s action regarding some application activity.
    6. askyesno(): User can answer in yes or no for some action.
    7. askretrycancel(): Ask the user about doing a particular task again or not.

    Example:

    from tkinter import * 

    from tkinter import messagebox

    root = Tk()

    root.geometry("300x200")

    w = Label(root, text ='GeeksForGeeks', font = "50"

    w.pack()

    messagebox.showinfo("showinfo", "Information")

    messagebox.showwarning("showwarning", "Warning")

    messagebox.showerror("showerror", "Error")

    messagebox.askquestion("askquestion", "Are you sure?")

    messagebox.askokcancel("askokcancel", "Want to continue?")

    messagebox.askyesno("askyesno", "Find the value?")

    messagebox.askretrycancel("askretrycancel", "Try again?")  

    root.mainloop() 

    Output:






    Модуль Tkinter messagebox в Python используется для отображения окон сообщений в приложениях Python. Существуют различные функции, которые используются для отображения соответствующих сообщений в зависимости от требований приложения.

    Синтаксис для использования окна сообщений приведен ниже.

    Синтаксис:

     
    messagebox.function_name(title, message [, options]) 
    

    Параметры

    • function_name: представляет соответствующую функцию окна сообщения.
    • title: это строка, которая отображается как заголовок окна сообщения.
    • message: это строка, которая будет отображаться как непосредственное сообщение в окне сообщения.
    • options: различные параметры, которые можно использовать для настройки диалогового окна сообщения.

    Можно использовать два параметра: default и parent.

    1. default.

    Параметр по умолчанию используется для упоминания типов кнопки по умолчанию, то есть ABORT, RETRY или IGNORE в окне сообщения.

    2. parent.

    Опция parent указывает родительское окно, поверх которого должно отображаться окно сообщения.

    Для отображения соответствующих окон сообщений используются следующие функции. Все функции используются с одинаковым синтаксисом, но имеют определенные значения.

    1. showinfo()

    Окно сообщений showinfo() используется там, где нам нужно показать пользователю некоторую релевантную информацию.

    Пример:

     
    # !/usr/bin/python3 
     
    from tkinter import * 
     
    from tkinter import messagebox 
     
    top = Tk() 
     
    top.geometry("100x100")     
     
    messagebox.showinfo("information","Information") 
     
    top.mainloop() 
    

    Вывод:

    showinfo()

    2. showwarning()

    Этот метод используется для отображения предупреждения пользователю. Рассмотрим следующий пример.

    Пример:

     
    # !/usr/bin/python3 
    from tkinter import * 
     
    from tkinter import messagebox 
     
    top = Tk() 
    top.geometry("100x100") 
    messagebox.showwarning("warning","Warning") 
     
    top.mainloop() 
    

    Вывод:

    showwarning()

    3. showerror()

    Этот метод используется для отображения сообщения об ошибке пользователю. Рассмотрим следующий пример.

    Пример:

     
    # !/usr/bin/python3 
    from tkinter import * 
    from tkinter import messagebox 
     
    top = Tk() 
    top.geometry("100x100") 
    messagebox.showerror("error","Error") 
    top.mainloop() 
    

    Вывод:

    showerror()

    4. askquestion()

    Этот метод используется, чтобы задать пользователю вопрос, на который можно ответить утвердительно или нет. Рассмотрим следующий пример.

    Пример:

     
    # !/usr/bin/python3 
    from tkinter import * 
    from tkinter import messagebox 
     
    top = Tk() 
    top.geometry("100x100") 
    messagebox.askquestion("Confirm","Are you sure?") 
    top.mainloop() 
    

    Вывод:

    askquestion()

    5. askokcancel()

    Этот метод используется для подтверждения действий пользователя в отношении некоторых действий приложения. Рассмотрим следующий пример.

    Пример:

     
    # !/usr/bin/python3 
    from tkinter import * 
    from tkinter import messagebox 
     
    top = Tk() 
    top.geometry("100x100") 
    messagebox.askokcancel("Redirect","Redirecting you to www.javatpoint.com") 
    top.mainloop() 
    

    Вывод:

    askokcancel()

    6. askyesno()

    Этот метод используется, чтобы спросить пользователя о каком-либо действии, на которое пользователь может ответить утвердительно или нет. Рассмотрим следующий пример.

    Пример:

     
    # !/usr/bin/python3 
    from tkinter import * 
    from tkinter import messagebox 
     
    top = Tk() 
    top.geometry("100x100") 
    messagebox.askyesno("Application","Got It?") 
    top.mainloop() 
    

    Вывод:

    askyesno()

    7. askretrycancel()

    Этот метод используется, чтобы спросить пользователя, нужно ли снова выполнять определенную задачу. Рассмотрим следующий пример.

    Пример:

     
    # !/usr/bin/python3 
    from tkinter import * 
    from tkinter import messagebox 
     
    top = Tk() 
    top.geometry("100x100") 
    messagebox.askretrycancel("Application","try again?") 
     
    top.mainloop() 
    

    Вывод:

    askretrycancel()

    Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.

    Последнее обновление: 24.09.2022

    Окна сообщений

    Tkinter имеет ряд встроенных окон для разных ситуаций, в частности, окна сообщений, функционал которых заключен в модуле tkinter.messagebox.
    Для отображения сообщений этот модуль предоставляет следующие функции:

    • showinfo(): предназначена для отображения некоторой информации

    • showerror(): предназначена для отображения ошибок

    • showwarrning(): предназначена для отображения предупреждений

    Все эти функции принимают три параметра:

    showinfo(title, message, **options)
    showerror(title, message, **options)
    showwarrning(title, message, **options)
    
    • title: заголовок окна

    • message: отображаемое сообщение

    • options: настройки окна

    В реальности различие между этими типами сообщений заключается лишь в изображении, которое отображается рядом с текстом сообщения:

    from tkinter import *
    from tkinter import ttk
    from tkinter.messagebox import showerror, showwarning, showinfo
    
    root = Tk()
    root.title("METANIT.COM")
    root.geometry("250x200")
    
    def open_info(): 
        showinfo(title="Информация", message="Информационное сообщение")
    
    def open_warning(): 
        showwarning(title="Предупреждение", message="Сообщение о предупреждении")
    
    def open_error(): 
        showerror(title="Ошибка", message="Сообщение об ошибке")
    
    info_button = ttk.Button(text="Информация", command=open_info)
    info_button.pack(anchor="center", expand=1)
    
    warning_button = ttk.Button(text="Предупреждение", command=open_warning)
    warning_button.pack(anchor="center", expand=1)
    
    error_button = ttk.Button(text="Ошибка", command=open_error)
    error_button.pack(anchor="center", expand=1)
    
    root.mainloop()
    

    Здесь по нажатию на каждую из трех кнопок отображается соответствующее сообщение:

    Окна с сообщениями messagebox в Tkinter и Python

    Окна подтверждения операции

    Модуль tkinter.messagebox также предоставляет ряд функций для подтверждения операции, где пользователю предлагается
    нажать на одну из двух кнопок:

    • askyesno()

    • askokcancel()

    • askretrycancel()

    Все эти функции принимают те же три параметра title, message и options. Отличие между ними только в том, что кнопки имеют разный текст. В случае нажатия на кнопку подтверждения, функция возвращает значение True, иначе возвращается False

    from tkinter import *
    from tkinter import ttk
    from tkinter.messagebox import showinfo, askyesno
    
    root = Tk()
    root.title("METANIT.COM")
    root.geometry("250x200")
    
    def click(): 
        result = askyesno(title="Подтвержение операции", message="Подтвердить операцию?")
        if result: showinfo("Результат", "Операция подтверждена")
        else: showinfo("Результат", "Операция отменена")
    
    ttk.Button(text="Click", command=click).pack(anchor="center", expand=1)
    
    root.mainloop()
    

    В данном случае по нажатию на кнопку вызывается функция askyesno(), которая отображает диалоговое окно с двумя кнопками «Да» и «Нет».
    В зависимости от того, на какую кнопку нажмет пользователь, функция возвратит True или False. Получив результат функции, мы можем проверить его и выполнить те или иные действия.

    Диалоговые окна в Tkinter и Python

    Особняком стоит функция askquestion — она также отображает две кнопки для подтверждения или отмены действия (кнопки «Yes»(Да) и «No»(Нет)),
    но в зависимости от нажатой кнопки возвращает строку: «yes» или «no».

    Также отдельно стоит функция askyesnocancel() — она отображает три кнопки: Yes (возвращает True), No (возвращает False) и Cancel
    (возвращает None):

    from tkinter import *
    from tkinter import ttk
    from tkinter.messagebox import showinfo, askyesnocancel
    
    root = Tk()
    root.title("METANIT.COM")
    root.geometry("250x200")
    
    def click(): 
        result =  askyesnocancel(title="Подтвержение операции", message="Подтвердить операцию?")
        if result==None: showinfo("Результат", "Операция приостановлена")
        elif result: showinfo("Результат", "Операция подтверждена")
        else : showinfo("Результат", "Операция отменена")
    
    ttk.Button(text="Click", command=click).pack(anchor="center", expand=1)
    
    root.mainloop()
    

    В этом случае диалоговое окно предоставит выбор из трех альтернатив

    Диалоговые окна подтверждения операции в Tkinter и Python

    Настройка окон

    Дополнительно все вышерассмотренные функции принимают ряд параметров, которые могут применяться для настройки окон. Некоторые из них:

    • detail: дополнительный текст, который отображается под основным сообщением

    • icon: иконка, которая отображается рядом с сообщением. Должна представлять одно из втроенных изображений: info, error, question или warning

    • default: кнопка по умолчанию. Должна представлять одно из встроенных значений: abort, retry, ignore, ok, cancel, no, yes

    from tkinter import *
    from tkinter import ttk
    from tkinter.messagebox import OK, INFO, showinfo 
    
    root = Tk()
    root.title("METANIT.COM")
    root.geometry("250x200")
    
    def click(): 
        showinfo(title="METANIT.COM", message="Добро пожаловать на сайт METANIT.COM", 
                detail="Hello World!", icon=INFO, default=OK)
    
    ttk.Button(text="Click", command=click).pack(anchor="center", expand=1)
    
    root.mainloop()
    

    При нажатии на кнопку отобразится следующее окно:

    конфигурация окна сообщения в tkinter и python

    Tkinter Messagebox

    What is Tkinter Messagebox?

    Tkinter Messagebox is a module in python which provides a different set of dialogues that are used to display message boxes, showing errors or warnings, widgets to select files or change colors which is a pop-up box with a relevant message being displayed along with a title based on the requirement in python applications with an icon and interrupts the user flow to take input from the user is called Tkinter Messagebox and has different functions that are used to display the relevant messages based on the application requirements like info message, warning message, error message, or taking input from the user.

    Syntax:

    import  tkinter
    from tkinter import messagebox
    messagebox.functionname(title, message [,options])

    Explanation: In the above syntax, we have imported the Tkinter library, and from that, we imported the messagebox module using which we can call different functions and display the relevant messages along with title based on the application requirement.

    Attributes of Tkinter Messagebox

    In the previous section, we have discussed the syntax of the Tkinter messagebox. Now we will discuss in detail the parameters or attributes being used in the syntax. There are four attributes in the syntax: function name, title, message, and options.

    • Function name: The function name represents the proper name for the message box function.
    • Title: Title is a message which will be displayed in the dialogue box of the message in the title bar.
    • Message: Messages is a text used to display a message to the appropriate function name.
    • Options: Options are like a choice by which we can customize the message box, which is standard. Some of the options are default and parent. The default option is used to mention default operations or message boxes buttons such as ABORT, IGNORE or RETRY in the message box. Parent option is used to mention a parental window on top of which message box will be displayed.

    Methods of Tkinter Messagebox

    Let’s have a look at different functions available with Tkinter messagebox such as showinfo(), showwarning(), showerror(), askquestion(), askokcancel(), askyesno(), and, askretrycancel(). The above functions used to show appropriate message boxes, and all the functions have the same kind of syntax but with different functionalities. All the functions which we are going to discuss are with python3 and above.

    1. showinfo()

    We use this messagebox function when we want to show some related or relevant information to the user. Let us try to create an information message box with an example below.

    Code:

    import tkinter
    from tkinter import messagebox
    top =  tkinter.Tk()
    top.geometry("150x150")
    messagebox.showinfo("Information","Information for user")
    top.mainloop()

    Explanation: In the above example, we created a Tkinter object top using tkinter.Tk() and used messagebox with showinfo() function to display the information message.

    Output:

    Tkinter Messagebox -1

    2. showwarning()

    We use this messagebox function when we want to display a warning message to the user. Let us create a warning message to the user by using an example as below:

    Code:

    import tkinter
    from tkinter import messagebox
    top =  tkinter.Tk()
    top.geometry("150x150")
    messagebox.showwarning("Warning","Warning message for user")
    top.mainloop()

    Explanation: In the above example, we created a Tkinter object top using tkinter.Tk() and used a messagebox with a showwarning() function to display the user’s warning message.

    Output:

    showwarning()

    3. showerror()

    We use this messagebox function when we want to display an error message to the user. Let us create an error message to the user by using an example as below:

    Code:

    import tkinter
    from tkinter import messagebox
    top =  tkinter.Tk()
    top.geometry("150x150")
    messagebox.showerror("Error","Error message for user")
    top.mainloop()

    Explanation: In the above example, we created a Tkinter object top using tkinter.Tk() and used a messagebox with showerror() function to display the user’s warning message.

    Output:

    showerror()

    4. askquestion()

    We use this messagebox function when we want to ask the user some questions, which can be answered by using yes or no. Let us create a program to ask the user a question whether the user wants to confirm it or not by using an example as below:

    Code:

    import tkinter
    from tkinter import messagebox
    top =  tkinter.Tk()
    top.geometry("150x150")
    messagebox.askquestion("Confirm","Are you sure?")
    top.mainloop()

    Explanation: In the above example, we created a Tkinter object top using tkinter.Tk() and used messagebox with askquestion() function to ask the user a question Confirm with a message Are you sure?

    Output:

    askquestion()

    5. askokcancel()

    We use this messagebox function when we want to confirm the user’s responses regarding the application behavior or activity. Let us create a program to confirm users response regarding an application by using an example as below:

    Code:

    import tkinter
    from tkinter import messagebox
    top =  tkinter.Tk()
    top.geometry("150x150")
    messagebox.askokcancel("Redirect","Redirecting you to www.google.co.in")
    top.mainloop()

    Explanation: In the above example, we created a Tkinter object top using Tkinter.Tk() and used a messagebox with the askokcancel() function to get the user’s response regarding the application activity.

    Output:

    askokcancel()

    6. askyesno()

    We use this messagebox function when we want to ask the user regarding some question that can be answered by using yes or no. Let us create a program to ask user regarding some question, and the user will answer by saying yes or no by using an example as below:

    Code:

    import tkinter
    from tkinter import messagebox
    top =  tkinter.Tk()
    top.geometry("150x150")
    messagebox.askyesno("Application","Got it?")
    top.mainloop()

    Explanation: In the above example, we created a Tkinter object top using tkinter.Tk() and used messagebox with askyesno() function to ask the user regarding some question with a message Got it?

    Output:

    askyesno()

    Examples to Implement Tkinter Messagebox

    Let us create an application using labels, grid, and Entry class to take input from it and apply the action after a button click as the below example.

    Code:

    import tkinter
    from tkinter import *
    top = tkinter.Tk()
    top.title("Welcome to innovate app")
    top.geometry("350x200")
    labl = Label(top, text=”Hello World!”)
    labl.grid(column=0, row=0)
    txt = Entry(top, width=10)
    txt.grid(column=1, row=0)
    def click():
    	labl.configure(text="Click me Button was clicked ! !")
    btn = Button(top, text ="Click Me", command=click)
    btn.grid(column=2, row=0)
    top.mainloop()

    Explanation: In the above example, we have created a Tkinter object top using tkinter.Tk() and the function click() where we are configuring the label with the text “Click me Button was clicked!!” and we have created a title to the Tkinter object, created a grid to display the output as below:

    Output:

    Tkinter Messagebox -7

    Tkinter Messagebox -8

    Conclusion

    Finally, it’s an overview of the Tkinter messagebox module in python. So far, we have discussed what messagebox, its syntax, its attributes, and functions supported in the module, describing functions in detail, and finally explaining with an example using showinfo() function using the pack() method. I hope after reading this article, you will have a good understanding of the Tkinter messagebox module, its functions, and how to use them based on the application requirement.

    Recommended Articles

    This is a guide to Tkinter Messagebox. Here we discuss Syntax, the attributes, different methods and examples to implement with appropriate syntax and sample code. You can also go through our other related articles to learn more –

    1. Tkinter Scrollbar
    2. Python Tkinter Label
    3. Tkinter Listbox
    4. Tkinter Menubutton

    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.

    • 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.

    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

    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

    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

    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

    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:

    • Python Tkinter Frame
    • Python Tkinter Menu bar – How to Use
    • Python Tkinter Checkbutton – How to use
    • Python Tkinter radiobutton – How to use
    • Python Tkinter Button – How to use
    • Python Tkinter Entry – How to use
    • Python tkinter label – How to use
    • Python Tkinter Stopwatch

    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

    Bijay Kumar MVP

    Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

    Summary: in this tutorial, you’ll learn how to show various message boxes using the tkinter.messagebox module.

    Introduction to tkinter.messagebox module

    When developing a Tkinter application, you often want to notify users about the events that occurred.

    For example, when users click the save button, you want to notify them that the record has been saved successfully.

    If an error occurred, for example, the database server is not reachable, you can notify users of the error.

    When the update has been completed but the record already exists, you may want to show a warning.

    To cover all of these scenarios, you can use various functions from the tkinter.messagebox module:

    • showinfo() – notify that an operation completed successfully.
    • showerror() – notify that an operation hasn’t completed due to an error.
    • showwarrning() – notify that an operation completed but something didn’t behave as expected.

    All of these functions accept two arguments:

    showinfo(title, message) showerror(title, message) showwarrning(title, message)

    Code language: Python (python)
    • The title is displayed on the title bar of the dialog.
    • The message is shown on the dialog.

    To span the message multiple lines, you can add the new line character 'n'.

    Tkinter messagebox examples

    The following program consists of three buttons. When you click a button, the corresponding message box will display.

    import tkinter as tk from tkinter import ttk from tkinter.messagebox import showerror, showwarning, showinfo # create the root window root = tk.Tk() root.title('Tkinter MessageBox') root.resizable(False, False) root.geometry('300x150') # options = {'fill': 'both', 'padx': 10, 'pady': 10, 'ipadx': 5} ttk.Button( root, text='Show an error message', command=lambda: showerror( title='Error', message='This is an error message.') ).pack(**options) ttk.Button( root, text='Show an information message', command=lambda: showinfo( title='Information', message='This is an information message.') ).pack(**options) ttk.Button( root, text='Show an warning message', command=lambda: showwarning( title='Warning', message='This is a warning message.') ).pack(**options) # run the app root.mainloop()

    Code language: Python (python)

    How it works.

    First, import the tkinter, tkinter.ttk, and tkinter.messagebox modules:

    import tkinter as tk from tkinter import ttk from tkinter.messagebox import showerror, showwarning, showinfo

    Code language: Python (python)

    Second, create the root window and initialize its properties:

    # create the root window root = tk.Tk() root.title('Tkinter MessageBox') root.resizable(False, False) root.geometry('300x150')

    Code language: Python (python)

    Third, create three buttons and assign a lambda expression to the command option of each button. Each lambda expression shows a corresponding message box.

    ttk.Button( root, text='Show an error message', command=lambda: showerror( title='Error', message='This is an error message.') ).pack(**options) ttk.Button( root, text='Show an information message', command=lambda: showinfo( title='Information', message='This is an information message.') ).pack(**options) ttk.Button( root, text='Show an warning message', command=lambda: showwarning( title='Warning', message='This is a warning message.') ).pack(**options)

    Code language: Python (python)

    Finally, display the root window.

    root.mainloop()

    Code language: Python (python)

    Summary

    • Use showinfo(), showerror(), showwarrning() functions from the tkinter.messagebox module to show an information, error, and warning message.

    Did you find this tutorial helpful ?

    Понравилась статья? Поделить с друзьями:
  • Python memory error out of memory
  • Python math domain error sqrt
  • Python make error
  • Python logic error
  • Python logging level error