Tkinter 教程 - 消息框

Jinku Hu 2023年1月30日 2019年12月15日
  1. Tkinter 消息框
  2. Tkinter 消息框示例
  3. GUI 中的 Tkinter 消息框示例
Tkinter 教程 - 消息框

Tkinter 消息框是在屏幕上弹出,给你额外信息或要求用户回答这样的问题 Are you sure to quit? Yes or No?

Tkinter 消息框

import tkinter as tk
from tkinter import messagebox
messagebox.showinfo("Basic Example", "a Basic Tk MessageBox")

Tkinter 消息框_基本示例

from tkinter import messagebox

我们需要从 tkinter 导入 messagebox

messagebox.showinfo("Basic Example", "a Basic Tk MessageBox")

showinfomessagebox 中的显示函数之一。它在消息框中显示信息,其中 Basic Example 是标题,a Basic Tk MessageBox 是所显示的信息。

Tkinter messagebox 中的显示函数是

显示函数 描述
showinfo 普通信息
showwarning 警告信息
showerror 错误信息
askquestion 向用户提问
askokcancel 答案是 okcancel
askyesno 答案是 yesno
askretrycancel 答案是 retrycancel

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?")

Tkinter 消息框_警告示例

Tkinter 消息 Box_Error 示例

Tkinter 消息框_askquestion

Tkinter 消息框_askyesno

Tkinter 消息框_askretrycancel

Tkinter 消息框_askokcancel

GUI 中的 Tkinter 消息框示例

上面的消息框示例给我们展示了 Tkinter 消息框的第一印象。但是通常消息框是在用户单击按钮后才会弹出。


import tkinter as tk
from tkinter import messagebox

root= tk.Tk()

def ExitApp():
    MsgBox = tk.messagebox.askquestion ('Exit App','Really Quit?',icon = 'error')
    if MsgBox == 'yes':
        tk.messagebox.showinfo('Welcome Back','Welcome back to the App')
buttonEg = tk.Button (root, text='Exit App',command=ExitApp)

我们将构造消息框的函数 ExitApp() 绑定到按钮 buttonEg

if MsgBox == 'yes':

askquestion 消息框中,单击的选项的返回值是 yesno


Tkinter 消息框_绑定到一个按钮

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.