We can also display alert messages in Tkinter, for that we just have to make use of the MessageBox widget. To show a message box using Tkinter, you can use the messagebox library like this:
from tkinter import messagebox
messagebox.showinfo ('The message title', 'message content')
See this example where we will show a message box when the user clicks a button.
from tkinter import *
from tkinter import messagebox
window = Tk()
window.title("hello world")
window.geometry('200x200')
def hello():
messagebox.showinfo('The message title', 'message content ')
btn = Button (window, text =' Click here ', bg='green', fg='white', command = hello)
btn.grid(column = 0, row = 0, pady=10, padx=10)
window.mainloop()
When you click the button, an informational message box will be displayed.
Python Tkinter - Show warning and error messages
You can show a warning or error message in the same way. The only thing that needs to be changed is the message function.
from tkinter import *
from tkinter import messagebox
window = Tk()
window.title("hello world")
window.geometry('200x200')
def hello():
messagebox.showwarning('Message title', 'Message content') # shows warning message
messagebox.showerror ('Message title', 'Message content') # shows the error message
btn = Button (window, text =' Click here ', bg='green', fg='white', command = hello)
btn.grid(column = 0, row = 0, pady=10, padx=10)
window.mainloop()
Python Tkinter - Show askquestion dialogs
To show a yes or no message box to the user, you can use one of the following message box functions:
from tkinter import *
from tkinter import messagebox
window = Tk()
window.title("hello world")
window.geometry('200x200')
def hello():
res = messagebox.askquestion ('Message title', 'Content of the message ')
res = messagebox.askyesno (' Message title ',' Message content ')
res = messagebox.askyesnocancel (' Message title ',' Message content ')
res = messagebox.askokcancel (' Message title ',' Message content ')
res = messagebox.askretrycancel (' Message title ',' Message content ')
btn = Button (window, text =' Click here ', bg='green', fg='white', command = hello)
btn.grid(column = 0, row = 0, pady=10, padx=10)
window.mainloop()
You can choose the appropriate message style according to your needs. Just replace the showinfo function line from the previous line and run it.
Post a Comment
0Comments