9.12 对话框
Tkinter支持几种不同的弹出框类型,以便在应用程序中显示警告、错误或提示消息。
常见的弹出框包括:
- tkMessageBox :用于显示信息或请求输入。
- tkFileDialog :用于选择文件或文件夹。
- tkColorChooser :用于选择颜色。
- tkFont :用于选择字体。
下面是一个messageBox的例子:
import tkinter as tkfrom tkinter import messageboxroot = tk.Tk()def on_button_click(): messagebox.showwarning("警告", "您需要备份文件!")button = tk.Button(root, text="点击我", command=on_button_click)button.pack()root.mainloop()
这里showwarning是一种显示警告的对话框,还有其他的类型:
import tkinter as tkfrom tkinter import messageboxroot = tk.Tk()def on_button_info_click(): messagebox.showinfo("信息", "这是一条信息")def on_button_error_click(): messagebox.showerror("错误", "发生了错误")def on_button_question_click(): t=messagebox.askquestion("询问", "你确定要这样做吗?") print(t)def on_button_yesno_click(): messagebox.askyesno("询问", "你确定吗?")def on_button_okcancel_click(): messagebox.askokcancel("确认", "请确认操作")
button_info = tk.Button(root, text="显示信息", command=on_button_info_click)button_info.pack()button_error = tk.Button(root, text="显示错误", command=on_button_error_click)button_error.pack()button_question = tk.Button(root, text="显示询问", command=on_button_question_click)button_question.pack()button_yesno = tk.Button(root, text="显示Yes/No", command=on_button_yesno_click)button_yesno.pack()button_okcancel = tk.Button(root, text="显示确认/取消", command=on_button_okcancel_click)button_okcancel.pack()root.mainloop()
请注意,showinfo()、showerror()和askquestion()函数都会在对话框的标题栏上显示一个i、x和?符号,以表示它们的类型。