Working with Message Boxes, Dialogs, and File Dialogs in Python Tkinter
import tkinter
import tkinter.messagebox
To display an informational message:
tkinter.messagebox.showinfo('Notice', 'Life is short')
For a warning message:
tkinter.messagebox.showwarning('Warning', 'Heavy rain expected tomorrow')
And to show an error:
tkinter.messagebox.showerror('Error', 'An error occurred')
These can be integrated into a GUI application as follows:
import tkinter
import tkinter.messagebox
def trigger_dialog():
tkinter.messagebox.showinfo('Notice', 'Life is short')
window = tkinter.Tk()
window.title('GUI')
window.geometry('800x600')
window.resizable(False, False)
tkinter.Button(window, text='Click Me', command=trigger_dialog).pack()
window.mainloop()
Interactive dialogs return user responses:
import tkinter
import tkinter.messagebox
def confirm_action():
result = tkinter.messagebox.askokcancel('Confirmation', 'Proceed with this action?')
print(result) # True for OK, False for Cancel
root = tkinter.Tk()
root.title('Dialog Demo')
root.geometry('800x600')
root.resizable(False, False)
tkinter.Button(root, text='Confirm', command=confirm_action).pack()
root.mainloop()
Different dialog types yield different return values:
askquestion: returns'yes'or'no'askyesno: returnsTrueorFalseaskretrycancel: returnsTrue(Retry) orFalse(Cancel)askyesnocancel: returnsTrue(Yes),False(No), orNone(Cancel)
Example usage:
response = tkinter.messagebox.askyesnocancel('Save?', 'Do you want to save changes?')
For file selcetion, use the filedialog module:
import tkinter.filedialog
filepath = tkinter.filedialog.askopenfilename()
print(filepath) # e.g., 'E:/1.txt'