Tkinter 教程 - 消息框
    
    Jinku Hu
    2024年2月15日
    
    Tkinter
    Tkinter Message Box
    
 
Tkinter 消息框是在屏幕上弹出,给你额外信息或要求用户回答这样的问题 Are you sure to quit? Yes or No?
Tkinter 消息框
#!/usr/bin/python3
import tkinter as tk
from tkinter import messagebox
messagebox.showinfo("Basic Example", "a Basic Tk MessageBox")

from tkinter import messagebox
我们需要从 tkinter 导入 messagebox。
messagebox.showinfo("Basic Example", "a Basic Tk MessageBox")
showinfo 是 messagebox 中的显示函数之一。它在消息框中显示信息,其中 Basic Example 是标题,a Basic Tk MessageBox 是所显示的信息。
Tkinter messagebox 中的显示函数是
| 显示函数 | 描述 | 
|---|---|
| showinfo | 普通信息 | 
| showwarning | 警告信息 | 
| showerror | 错误信息 | 
| askquestion | 向用户提问 | 
| askokcancel | 答案是 ok和cancel | 
| askyesno | 答案是 yes和no | 
| askretrycancel | 答案是 retry和cancel | 
Tkinter 消息框示例
import tkinter as tk
from tkinter import messagebox
messagebox.showwarning("Warning Example", "Warning MessageBox")
messagebox.showerror("Error Example", "Error MessageBox")
messagebox.askquestion("Ask Question Example", "Quit?")
messagebox.askyesno("Ask Yes/No Example", "Quit?")
messagebox.askokcancel("Ask OK Cancel Example", "Quit?")
messagebox.askretrycancel("Ask Retry Cancel Example", "Quit?")






GUI 中的 Tkinter 消息框示例
上面的消息框示例给我们展示了 Tkinter 消息框的第一印象。但是通常消息框是在用户单击按钮后才会弹出。
我们将介绍如何将命令同消息框中的不同选项来绑定。
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.geometry("300x200")
def ExitApp():
    MsgBox = tk.messagebox.askquestion("Exit App", "Really Quit?", icon="error")
    if MsgBox == "yes":
        root.destroy()
    else:
        tk.messagebox.showinfo("Welcome Back", "Welcome back to the App")
buttonEg = tk.Button(root, text="Exit App", command=ExitApp)
buttonEg.pack()
root.mainloop()
我们将构造消息框的函数 ExitApp() 绑定到按钮 buttonEg。
if MsgBox == 'yes':
在 askquestion 消息框中,单击的选项的返回值是 yes 或 no。
后续的操作可能是关闭应用程序,显示另一个消息框,或者其他已定义的行为。

        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
