Python+tkinter——常用的提示框代码

当程序运行结束时,我们经常会用到提示框,用来提醒用户一些信息,如:错误,警告,成功等信息

今天我们来一起看一下python中tkinter的常用提示框

视频展示:

大家可以根据自己的代码中的需求,自行复制相关提示框代码,用于提示消息

下面时完整版代码(自行提取需要的):

import tkinter as tk
from tkinter import messagebox

# 创建主窗口
root = tk.Tk()
root.title("提示框示例")

# 显示一般信息提示框
def show_info():
    messagebox.showinfo(title="提示", message="这是一条普通消息!")

# 显示警告信息提示框
def show_warning():
    messagebox.showwarning(title="警告", message="这是一条警告消息!")

# 显示错误信息提示框
def show_error():
    messagebox.showerror(title="错误", message="这是一条错误消息!")

# 询问一个是/否问题
def ask_question():
    res = messagebox.askquestion(title="确认", message="你确定要执行该操作吗?")
    if res == yes:
        messagebox.showinfo(title="结果", message="你选择了确认!")
    else:
        messagebox.showinfo(title="结果", message="你选择了取消!")

# 询问一个Yes/No问题
def ask_yesno():
    res = messagebox.askyesno(title="确认", message="你确定要退出吗?")
    if res == True:
        messagebox.showinfo(title="结果", message="你选择了Yes!")
    else:
        messagebox.showinfo(title="结果", message="你选择了No!")

# 询问一个Ok/Cancel问题
def ask_okcancel():
    res = messagebox.askokcancel(title="确认", message="你确定要关闭窗口吗?")
    if res == True:
        root.destroy()

# 创建按钮并设置中心对齐
tk.Button(root, text="显示一般消息", command=show_info).pack(pady=10)
tk.Button(root, text="显示警告消息", command=show_warning).pack(pady=10)
tk.Button(root, text="显示错误消息", command=show_error).pack(pady=10)
tk.Button(root, text="是/否问题", command=ask_question).pack(pady=10)
tk.Button(root, text="Yes/No问题", command=ask_yesno).pack(pady=10)
tk.Button(root, text="Ok/Cancel问题", command=ask_okcancel).pack(pady=10)

root.mainloop()

希望对大家有帮助

致力于办公自动化的小小程序员一枚#

经验分享 程序员 微信小程序 职场和发展