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.