程序员的知识教程库

网站首页 > 教程分享 正文

Python GUI 编程:tkinter 初学者入门指南——消息框、对话框

henian88 2025-03-03 18:43:21 教程分享 5 ℃ 0 评论


在本教程中,将介绍如何使用 tkinter 的 messagebox 模块、filedialog 模块、colorchooser 模块显示各种消息框、对话框。


在使用 Tkinter 开发应用程序时,需要向用户发送提示、警告、错误信息。这些场景,可以使用 messagebox 模块中的以下方法实现:


  • showinfo():提示信息。
  • showerror(): 错误信息。
  • showwarrning():警告信息。



如果需要显示一个要求用户选择、确认、重试的对话框,可以使用 messagebox 模块中的以下方法实现:


  • askyesno():显示 Yes/No 对话框
  • askokcancel():显示 OK/Cancel 对话框
  • askretrycancel():显示 Retry/Cancel 对话框



如果需要显示打开文件的对话框,可以使用 filedialog 模块中的以下方法实现:


  • askopenfilename()



如果需要显示颜色选择对话框,可以使用 colorchooser 模块中的以下方法实现:


  • askcolor()



import tkinter as tk
from tkinter.messagebox import *
from tkinter import filedialog as fd
from tkinter.colorchooser import askcolor
root = tk.Tk()
root.geometry('600x400+200+200')
root.title('MessageBox 消息框、对话框演示')

def show_error():
    showerror(title='错误', message='这是一个错误信息窗口')
def show_info():
    showinfo(title='提示', message='这是一个提示信息窗口')
def show_warning():
    showwarning(title='警告', message='这是一个警告信息窗口')
def confirm_destroy():
    answer = askyesno(title='Yes/No', message='你确定要退出?')
    if answer:
        root.destroy()
def confirm_delete():
    answer = askokcancel(title='Ok/Cancel', message='删除所有数据?')
    if answer:
        showinfo(title='提示', message='所有数据删除成功')
def confirm_retry():
    answer = askretrycancel(title='Retry/Cancel', message='数据发送不成功,尝试重新发送?')
    if answer:
        showinfo(title='提示', message='尝试再次发送数据')
def select_file():
    filetypes = (('text files', '*.txt'), ('All files', '*.*'))
    filename = fd.askopenfilename(title='打开文件', initialdir='/', filetypes=filetypes)
    showinfo(
        title='选择文件', message=filename)
def change_color():
    colors = askcolor(title="选择颜色")
    root.configure(bg=colors[1])
    
tk.Button(
    root, width=20,
    text='显示错误信息',
    command=show_error).pack(padx=10, pady=10)

tk.Button(
    root, width=20,
    text='显示提示信息',
    command=show_info).pack(padx=10, pady=10)

tk.Button(
    root, width=20,
    text='显示警告信息',
    command=show_warning).pack(padx=10, pady=10)

tk.Button(
    root, width=20,
    text='退出',
    command=confirm_destroy).pack(padx=10, pady=10)

tk.Button(
    root, width=20,
    text='删除数据',
    command=confirm_delete).pack(padx=10, pady=10)

tk.Button(
    root, width=20,
    text='发送数据',
    command=confirm_retry).pack(padx=10, pady=10)
tk.Button(
    root, width=20,
    text='打开文件',
    command=select_file).pack(padx=10, pady=10)
tk.Button(
    root, width=20,
    text='选择颜色',
    command=change_color).pack(padx=10, pady=10)
root.mainloop()

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表