扫码一下
查看教程更方便
tkinter 消息框是在屏幕上弹出,给你额外信息或要求用户回答这样的问题 are you sure to quit? yes or no?
#!/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 |
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?")
上面的消息框示例给我们展示了 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。
后续的操作可能是关闭应用程序,显示另一个消息框,或者其他已定义的行为。