Message box in python
- Python | Creating a button in tkinter
- Python | Add style to tkinter button
- Python | Add image on a Tkinter button
- Python Tkinter – Label
- Python Tkinter | Create LabelFrame and add widgets to it
- RadioButton in Tkinter | Python
- Python Tkinter – Checkbutton Widget
- Python Tkinter – Canvas Widget
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Python Tkinter | Moving objects using Canvas.move() method
- Combobox Widget in tkinter | Python
- maxsize() method in Tkinter | Python
- minsize() method in Tkinter | Python
- resizable() method in Tkinter | Python
- Python Tkinter – Entry Widget
- Tkinter – Read only Entry Widget
- Python Tkinter – Text Widget
- Python Tkinter – Message
- Python | Menu widget in Tkinter
- Python Tkinter – Menubutton Widget
- Python Tkinter – SpinBox
- Progressbar widget in Tkinter | Python
- Python-Tkinter Scrollbar
- Python Tkinter – ScrolledText Widget
- Python Tkinter – ListBox Widget
- Scrollable ListBox in Python-tkinter
- Python Tkinter – Frame Widget
- Scrollable Frames in Tkinter
- How to make a proper double scrollbar frame in Tkinter
- Python Tkinter – Scale Widget
- Hierarchical treeview in Python GUI application
- Python-Tkinter Treeview scrollbar
- Python Tkinter – Toplevel Widget
- Python | askopenfile() function in Tkinter
- Python | asksaveasfile() function in Tkinter
- Python – Tkinter askquestion Dialog
- Python Tkinter – MessageBox Widget
- Create a Yes/No Message Box in Python using tkinter
- Change the size of MessageBox – Tkinter
- Different messages in Tkinter | Python
- Change Icon for Tkinter MessageBox
- Python – Tkinter Choose color Dialog
- Popup Menu in Tkinter
- Getting screen’s height and width using Tkinter | Python
- Python | How to dynamically change text of Checkbutton
- Python | focus_set() and focus_get() method
- Search String in Text using Python-Tkinter
- Autocomplete ComboBox in Python-Tkinter
- Autohiding Scrollbars using Python-tkinter
- Python Tkinter – Validating Entry Widget
- Tracing Tkinter variables in Python
- Python | setting and retrieving values of Tkinter variable
- Tkinter | Adding style to the input text using ttk.Entry widget
- Python | after method in Tkinter
- destroy() method in Tkinter | Python
- Text detection using Python
- Python | winfo_ismapped() and winfo_exists() in Tkinter
- Collapsible Pane in Tkinter | Python
- Creating a multiple Selection using Tkinter
- Creating Tabbed Widget With Python-Tkinter
- Open a new Window with a button in Python-Tkinter
- Cryptography GUI using python
- Python | Simple GUI calculator using Tkinter
- Create Table Using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python: Weight Conversion GUI using Tkinter
- Python: Age Calculator using Tkinter
- Python | Create a GUI Marksheet using Tkinter
- Python | Loan calculator using Tkinter
- Python | Create a digital clock using Tkinter
- Make Notepad using Tkinter
- Color game using Tkinter in Python
- Python | Simple FLAMES game using Tkinter
- Simple registration form using Python Tkinter
- How to create a COVID19 Data Representation GUI?
- Python | Creating a button in tkinter
- Python | Add style to tkinter button
- Python | Add image on a Tkinter button
- Python Tkinter – Label
- Python Tkinter | Create LabelFrame and add widgets to it
- RadioButton in Tkinter | Python
- Python Tkinter – Checkbutton Widget
- Python Tkinter – Canvas Widget
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Python Tkinter | Moving objects using Canvas.move() method
- Combobox Widget in tkinter | Python
- maxsize() method in Tkinter | Python
- minsize() method in Tkinter | Python
- resizable() method in Tkinter | Python
- Python Tkinter – Entry Widget
- Tkinter – Read only Entry Widget
- Python Tkinter – Text Widget
- Python Tkinter – Message
- Python | Menu widget in Tkinter
- Python Tkinter – Menubutton Widget
- Python Tkinter – SpinBox
- Progressbar widget in Tkinter | Python
- Python-Tkinter Scrollbar
- Python Tkinter – ScrolledText Widget
- Python Tkinter – ListBox Widget
- Scrollable ListBox in Python-tkinter
- Python Tkinter – Frame Widget
- Scrollable Frames in Tkinter
- How to make a proper double scrollbar frame in Tkinter
- Python Tkinter – Scale Widget
- Hierarchical treeview in Python GUI application
- Python-Tkinter Treeview scrollbar
- Python Tkinter – Toplevel Widget
- Python | askopenfile() function in Tkinter
- Python | asksaveasfile() function in Tkinter
- Python – Tkinter askquestion Dialog
- Python Tkinter – MessageBox Widget
- Create a Yes/No Message Box in Python using tkinter
- Change the size of MessageBox – Tkinter
- Different messages in Tkinter | Python
- Change Icon for Tkinter MessageBox
- Python – Tkinter Choose color Dialog
- Popup Menu in Tkinter
- Getting screen’s height and width using Tkinter | Python
- Python | How to dynamically change text of Checkbutton
- Python | focus_set() and focus_get() method
- Search String in Text using Python-Tkinter
- Autocomplete ComboBox in Python-Tkinter
- Autohiding Scrollbars using Python-tkinter
- Python Tkinter – Validating Entry Widget
- Tracing Tkinter variables in Python
- Python | setting and retrieving values of Tkinter variable
- Tkinter | Adding style to the input text using ttk.Entry widget
- Python | after method in Tkinter
- destroy() method in Tkinter | Python
- Text detection using Python
- Python | winfo_ismapped() and winfo_exists() in Tkinter
- Collapsible Pane in Tkinter | Python
- Creating a multiple Selection using Tkinter
- Creating Tabbed Widget With Python-Tkinter
- Open a new Window with a button in Python-Tkinter
- Cryptography GUI using python
- Python | Simple GUI calculator using Tkinter
- Create Table Using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python: Weight Conversion GUI using Tkinter
- Python: Age Calculator using Tkinter
- Python | Create a GUI Marksheet using Tkinter
- Python | Loan calculator using Tkinter
- Python | Create a digital clock using Tkinter
- Make Notepad using Tkinter
- Color game using Tkinter in Python
- Python | Simple FLAMES game using Tkinter
- Simple registration form using Python Tkinter
- How to create a COVID19 Data Representation GUI?
Message box in python
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()
Здесь по нажатию на каждую из трех кнопок отображается соответствующее сообщение:
Окна подтверждения операции
Модуль tkinter.messagebox также предоставляет ряд функций для подтверждения операции, где пользователю предлагается нажать на одну из двух кнопок:
Все эти функции принимают те же три параметра 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. Получив результат функции, мы можем проверить его и выполнить те или иные действия.
Особняком стоит функция 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()
В этом случае диалоговое окно предоставит выбор из трех альтернатив
Настройка окон
Дополнительно все вышерассмотренные функции принимают ряд параметров, которые могут применяться для настройки окон. Некоторые из них:
- 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 messagebox
The Tkinter tkMessageBox has various methods to display a message box.
There is a slight difference between Tkinter for Python 2.7 and Python 3.
To find your Python version try one of these commands:
python —version
python3 —version
Related courses
Tkinter Message box
TkMessage box To show a minimalistic Tkinter message box, use the function showinfo() where the parameters are the window title and text.
The showinfo() function is in a different module depending on the Python version.
from tkinter import messagebox
messagebox.showinfo(«Title», «a Tk MessageBox»)
import Tkinter
import tkMessageBox
tkMessageBox.showinfo(«Title», «a Tk MessageBox»)
Tkinter showerror, showwarning and showinfo
import tkinter
from tkinter import messagebox
# hide main window
root = tkinter.Tk()
root.withdraw()
# message box display
messagebox.showerror(«Error», «Error message»)
messagebox.showwarning(«Warning»,«Warning message»)
messagebox.showinfo(«Information»,«Informative message»)
import Tkinter
import tkMessageBox
# An error box
tkMessageBox.showerror(«Error»,«No disk space left on device»)
# A warning box
tkMessageBox.showwarning(«Warning»,«Could not start service»)
# An information box
tkMessageBox.showinfo(«Information»,«Created in Python.»)
If you are new to programming Tkinter, I highly recommend this course.