Python вывести окно ошибки

What’s the easiest way to generate an error window for a Python script in Windows?
Windows-specific answers are fine; please don’t reply how to generate a custom Tk window.

asked Jul 29, 2010 at 18:10

Scribble Master's user avatar

Scribble MasterScribble Master

1,1003 gold badges11 silver badges17 bronze badges

2

@Constantin is almost correct, but his example will produce garbage text. Make sure that the text is unicode. I.e.,

ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)

…and it’ll work fine.

answered Jul 29, 2010 at 18:25

Chris's user avatar

5

If you need a GUI error message, you could use EasyGui:

>>> import easygui as e
>>> e.msgbox("An error has occured! :(", "Error")

Otherwise a simple print("Error!") should suffice.

answered Jul 29, 2010 at 18:16

John Howard's user avatar

John HowardJohn Howard

60.5k23 gold badges49 silver badges66 bronze badges

1

If i recall correctly (don’t have Windows box at the moment), the ctypes way is:

import ctypes
ctypes.windll.user32.MessageBoxW(None, u"Error", u"Error", 0)

ctypes is a standard module.

Note: For Python 3.x you don’t need the u prefix.

answered Jul 29, 2010 at 18:23

Constantin's user avatar

ConstantinConstantin

27.4k10 gold badges60 silver badges79 bronze badges

0

You can get a one-liner using tkinter.

import tkMessageBox

tkMessageBox.showerror('error title', 'error message')

Here is some documentation for pop-up dialogs.

answered Jul 29, 2010 at 18:32

Gary Kerr's user avatar

Gary KerrGary Kerr

13.6k4 gold badges47 silver badges51 bronze badges

2

Check out the GUI section of the Python Wiki for info on message boxs

answered Jul 29, 2010 at 18:42

asd32's user avatar

asd32asd32

1911 gold badge1 silver badge6 bronze badges

Скачайте код уроков с GitLab: https://gitlab.com/PythonRu/tkinter-uroki

Окна уведомлений

Распространенный сценарий применения диалоговых окон — уведомление пользователей о событиях, которые происходят в приложении: сделана новая запись или произошла ошибка при попытке открыть файл. Рассмотрим базовые функции Tkinter, предназначенные для отображения диалоговых окон.

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

Окна предупреждений

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

Окна предупреждений

Эти диалоговые окна открываются с помощью функций showinfo, showwarning и showerror из модуля tkinter.messagebox:


import tkinter as tk
import tkinter.messagebox as mb class App(tk.Tk):
def __init__(self):
super().__init__()
btn_info = tk.Button(self, text="Информационное окно",
command=self.show_info)
btn_warn = tk.Button(self, text="Окно с предупреждением",
command=self.show_warning)
btn_error = tk.Button(self, text="Окно с ошибкой",
command=self.show_error)

opts = {'padx': 40, 'pady': 5, 'expand': True, 'fill': tk.BOTH}
btn_info.pack(**opts)
btn_warn.pack(**opts)
btn_error.pack(**opts)

def show_info(self):
msg = "Ваши настройки сохранены"
mb.showinfo("Информация", msg)

def show_warning(self):
msg = "Временные файлы удалены не правильно"
mb.showwarning("Предупреждение", msg)

def show_error(self):
msg = "Приложение обнаружило неизвестную ошибку"
mb.showerror("Ошибка", msg) if __name__ == "__main__":
app = App()
app.mainloop()

Как работают окна с уведомлениями

В первую очередь нужно импортировать модуль tkinter.messagebox, задав для него алиас mb. В Python2 этот модуль назывался tkMessageBox, поэтому такой синтаксис позволит изолировать проблемы совместимости.

Каждое окно обычно выбирается в зависимости от информации, которую нужно показать пользователю:

  • showinfo — операция была завершена успешно,
  • showwarning — операция была завершена, но что-то пошло не так, как планировалось,
  • showerror — операция не была завершена из-за ошибки.

Все три функции получают две строки в качестве входящих аргументов: заголовок и сообщение.

Сообщение может быть выведено на нескольких строках с помощью символа новой строки n.

Окна выбора ответа

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

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

В этой программе рассмотрим остальные диалоговые функции из модуля tkinter.messagebox. Каждая кнопка включает метки с описанием типа окна, которое откроется при нажатии:

Окна выбора ответа

У них есть кое-какие отличия, поэтому стоит попробовать каждое из окон, чтобы разобраться в них.

Как и в прошлом примере сначала нужно импортировать tkinter.messagebox с помощью синтаксиса import … as и вызывать каждую из функций вместе с title и message:


import tkinter as tk
import tkinter.messagebox as mb class App(tk.Tk):
def __init__(self):
super().__init__()
self.create_button(mb.askyesno, "Спросить Да/Нет",
"Вернет True или False")
self.create_button(mb.askquestion, "Задать вопрос ",
"Вернет 'yes' или 'no'")
self.create_button(mb.askokcancel, "Спросить Ок/Отмена",
"Вернет True или False")
self.create_button(mb.askretrycancel, "Спросить Повтор/Отмена",
"Вернет True или False")
self.create_button(mb.askyesnocancel, "Спросить Да/Нет/Отмена",
"Вернет True, False или None")

def create_button(self, dialog, title, message):
command = lambda: print(dialog(title, message))
btn = tk.Button(self, text=title, command=command)
btn.pack(padx=40, pady=5, expand=True, fill=tk.BOTH) if __name__ == "__main__":
app = App()
app.mainloop()

Как работают вопросительные окна

Чтобы избежать повторений при создании экземпляра кнопки и функции обратного вызова определим метод create_button, который будет переиспользоваться для каждой кнопки с диалогами. Команды всего лишь выводят результат функции dialog, переданной в качестве параметра, что позволит видеть значение, которое она возвращает в зависимости от нажатой пользователем кнопки.

Выбор файлов и папок

Диалоговые окна для выбора файлов позволяют выбирать один или несколько файлов из файловой системы. В Tkinter эти функции объявлены в модуле tkinter.filedialog, который также включает окна для выбора папок. Он также позволяет настраивать поведение нового окна: например, фильтрация по расширению или выбор папки по умолчанию.

В этом приложении будет две кнопки. Первая, «Выбрать файл», откроет диалоговое окно для выбора файла. По умолчанию в окне будут только файлы с расширением .txt:

Выбор файлов и папок

Вторая — «Выбор папки». Она будет открывать похожее диалоговое окно для выбора папки.

Обе кнопки будут выводить полный путь к выбранным файлу или папке и не делать ничего, если пользователь выберет вариант Отмена.

Первая кнопка будет вызывать функцию askopenfilename, а вторая — askdirectory:


import tkinter as tk
import tkinter.filedialog as fd class App(tk.Tk):
def __init__(self):
super().__init__()
btn_file = tk.Button(self, text="Выбрать файл",
command=self.choose_file)
btn_dir = tk.Button(self, text="Выбрать папку",
command=self.choose_directory)
btn_file.pack(padx=60, pady=10)
btn_dir.pack(padx=60, pady=10)

def choose_file(self):
filetypes = (("Текстовый файл", "*.txt"),
("Изображение", "*.jpg *.gif *.png"),
("Любой", "*"))
filename = fd.askopenfilename(title="Открыть файл", initialdir="/",
filetypes=filetypes)
if filename:
print(filename)

def choose_directory(self):
directory = fd.askdirectory(title="Открыть папку", initialdir="/")
if directory:
print(directory) if __name__ == "__main__":
app = App()
app.mainloop()

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

Как работают окна выбора файлов и папок

Создадим первое диалоговое окно с помощью функции askopenfilename, которая возвращает строку с полным путем к файлу. Она принимает следующие опциональные аргументы:

  • title — название для диалогового окна.
  • initialdir — начальная папка.
  • filetypes — последовательность из двух строк. Первая — метка с типом файла в читаемом формате, а вторая — шаблон для поиска совпадения с названием файла.
  • multiple — булево значение для определения того, может ли пользователь выбирать несколько файлов.
  • defaultextension — расширение, добавляемое к файлу, если оно не было указано явно.

В этом примере задаем корневую папку в качестве начальной, а также название. В кортеже типов файлов есть следующие три варианта: текстовые файлы, сохраненные с расширением .txt, изображения с .jpg, .gif и .png, а также подстановочный знак («*») для всех файлов.

Стоит обратить внимание на то, что эти шаблоны не обязательно соответствуют формату данных в файле, поскольку есть возможность переименовать его с другим расширением:


filetypes = (("Текстовый файл", "*.txt"),
("Изображение", "*.jpg *.gif *.png"),
("Любой", "*"))
filename = fd.askopenfilename(title="Открыть файл", initialdir="/",
filetypes=filetypes)

Функция askdirectory также принимает параметры title и initialdir, а также булев параметр mustexist для определения того, должны ли пользователи выбирать существующую папку:


directory = fd.askdirectory(title="Открыть папку", initialdir="/")

Модуль tkinter.filedialog включает вариации этих функций, которые позволяют прямо получать объекты файлов.

Например, askopenfile возвращает объект файла, который соответствует выбранному вместо того чтобы вызывать open с путем возвращающим askopenfilename. Но при этом все еще придется проверять, не было ли окно отклонено перед вызовом файловых методов:


import tkinter.filedialog as fd

filetypes = (("Текстовый файл", "*.txt"),)
my_file = fd.askopenfile(title="Открыть файл", filetypes=filetypes)
if my_file:
print(my_file.readlines())
my_file.close()

Сохранение данных в файл

Помимо выбора существующих файлов и папок также есть возможность создавать новые, используя диалоговые окна Tkinter. Они позволят сохранять данные, сгенерированные приложением, позволяя пользователям выбирать название и местоположение нового файла.

Будем использовать диалоговое окно «Сохранить файл» для записи содержимого виджета Text в текстовый файл:

Сохранение данных в файл

Для открытия такого диалогового окна используется функция asksavefile из модуля tkinter.filedialog. Она создает объект файла с режимом записи ('w') или None, если окно было закрыто:


import tkinter as tk
import tkinter.filedialog as fd class App(tk.Tk):
def __init__(self):
super().__init__()
self.text = tk.Text(self, height=10, width=50)
self.btn_save = tk.Button(self, text="Сохранить", command=self.save_file)

self.text.pack()
self.btn_save.pack(pady=10, ipadx=5)

def save_file(self):
contents = self.text.get(1.0, tk.END)
new_file = fd.asksaveasfile(title="Сохранить файл", defaultextension=".txt",
filetypes=(("Текстовый файл", "*.txt"),))
if new_file:
new_file.write(contents)
new_file.close() if __name__ == "__main__":
app = App()
app.mainloop()

Как работает сохранение фалов

Функция asksavefile принимает те же опциональные параметры, что и askopenfile, но также позволяет добавить расширение файла по умолчанию с помощью параметра defaultextension.

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

С помощью объекта файла можно записать содержимое виджета Text. Нужно лишь не забывать закрывать файл для освобождения ресурсов, которые использовал объект:


contents = self.text.get(1.0, tk.END)
new_file.write(contents)
new_file.close()

Благодаря последней программе стало понятно, что askopenfile возвращает объект файла, а не его название. Также есть функция asksaveasfilename, которая возвращает путь к выбранному файлу. Ее можно использовать для изменения пути или выполнения валидации перед открытием файла для записи.

Последнее обновление: 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

The Tkinter library has many built-in functions and methods which can be used to implement the functional part of an application. We can use messagebox module in Tkinter to create various popup dialog boxes. The messagebox property has different types of built-in popup windows that the users can use in their applications.

If you need to display the error messagebox in your application, you can use showerror(«Title», «Error Message») method. This method can be invoked with the messagebox itself.

Example

# Import the required libraries
from tkinter import *
from tkinter import messagebox

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function to show the error message
def on_click():
   messagebox.showerror('Python Error', 'Error: This is an Error Message!')

# Create a label widget
label = Label(win, text="Click the button to show the message ",
font=('Calibri 15 bold'))
label.pack(pady=20)


# Create a button to delete the button
b = Button(win, text="Click Me", command=on_click)
b.pack(pady=20)

win.mainloop()

Output

When you run the above code, it will show a button widget and a label in the window. Click the button to show the error message.

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

Fewlines4Biju Bijay

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

  • Pycharm ошибка при установке пакетов
  • Python обработка ошибок valueerror
  • Python try обработка ошибок
  • Pycharm ошибка при установке модуля
  • Python не закрывать консоль при ошибке