本篇 ShengYu 介紹 Python tkinter messagebox 用法與範例,在 Python GUI 程式設計中常常需要提出一個提示對話框告訴使用者一些訊息,例如:有錯誤發生或者離開程式前的確認對話框,所以這篇會列出幾種 messagebox 用法與範例如下,
- tkinter messagebox.showinfo() 顯示訊息對話框
 - tkinter messagebox.showwarning() 警告訊息對話框
 - tkinter messagebox.showerror() 錯誤訊息對話框
 - tkinter messagebox.askokcancel() 確定取消對話框
 - tkinter messagebox.askquestion() 是否問題對話框
 
那就開始吧!
tkinter messagebox.showinfo() 顯示訊息對話框
Python tkinter 要顯示訊息對話框可以使用 messagebox 的 messagebox.showinfo() ,messagebox.showinfo() 可用來顯示一般資訊,用法如下,1
2
3
4
5
6
7
8#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
messagebox.showinfo('my messagebox', 'hello world')
結果圖如下,
  
tkinter messagebox.showwarning() 警告訊息對話框
tkinter 要顯示警告訊息對話框的話用 messagebox.showwarning(),用法如下,1
2
3
4
5
6
7
8#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
messagebox.showwarning('my messagebox', 'hello world')
結果圖如下,
  
tkinter messagebox.showerror() 錯誤訊息對話框
tkinter 要顯示錯誤訊息對話框的話用 messagebox.showerror(),用法如下,1
2
3
4
5
6
7
8#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
messagebox.showerror('my messagebox', 'hello world')
結果圖如下,
  
tkinter messagebox.askokcancel() 確定取消對話框
tkinter 要顯示確定取消訊息對話框的話用 messagebox.askokcancel(),用法如下,1
2
3
4
5
6
7
8#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
messagebox.askokcancel('my messagebox', 'hello world')
結果圖如下,
  
tkinter messagebox.askquestion() 是否問題對話框
tkinter 要顯示是否問題對話框的話用 messagebox.askquestion(),例如要問使用者是否要離開程式,用法如下,1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title('my window')
root.geometry('200x150')
def button_event():
    MsgBox = tk.messagebox.askquestion('my messagebox','Exit?')
    if MsgBox == 'yes':
       root.destroy()
        
tk.Button(root, text='Exit', command=button_event).pack()
  
root.mainloop()
結果圖如下,
  
以上就是 Python tkinter messagebox 用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!  
其它參考
tkinter.messagebox — Tkinter message prompts — Python 3 documentation
https://docs.python.org/3/library/tkinter.messagebox.html  
其它相關文章推薦
Python tkinter 選擇資料夾對話框
Python 新手入門教學懶人包
Python tkinter 新手入門教學