原文: https://pythonbasics.org/tkinter_messagebox/

消息框是一个显示消息的小弹出窗口。 有时它伴随着一个图标。 几乎所有时间,它都会中断用户的操作。

下面的示例向您展示如何使用 Tkinter 创建和使用消息框。 此处显示的代码适用于 Python 3.x 和更高版本。 较旧的 Python 导入和使用 Tkinter 的方式有所不同。

消息框

消息框

消息框有很多变体。 您可以有一条信息消息,警告消息或错误消息。 所有这些消息框都有标题和消息。

  1. #!/usr/bin/python3
  2. import tkinter
  3. import tkinter.messagebox
  4. tkinter.messagebox.showinfo('title','message')
  5. tkinter.messagebox.showwarning('title','message')
  6. tkinter.messagebox.showerror('title','message')

Tkinter 消息框 - 图1

点击和消息框

下面的示例仅在单击按钮时显示一个消息框。 这类似于现实世界中出现问题时显示消息框的情况。

  1. import tkinter
  2. import tkinter.messagebox
  3. def buttonClick():
  4. tkinter.messagebox.showinfo('title', 'message')
  5. #tkinter.messagebox.showwarning('title', 'message')
  6. #tkinter.messagebox.showerror('title', 'message')
  7. root=tkinter.Tk()
  8. root.title('GUI')
  9. root.geometry('100x100')
  10. root.resizable(False, False)
  11. tkinter.Button(root, text='hello button',command=buttonClick).pack()
  12. root.mainloop()

Tkinter 消息框 - 图2

下载 Tkinter 示例