最近有一个要求,用python的tkinter制作一个messagebox,传入3个参数: title text timeout。用户可以点击“确定” 关闭窗口; 或者 等待几秒(timeout) 窗口自动关闭;
一开始 我选择tkinter原生的messagebox,代码如下:
from tkinter import messagebox, Tk
root = Tk() root.withdraw() root.wm_attributes(‘-topmost‘, 1) messagebox.showinfo(title, text)
但原生的messagebox不支持timeout。。。 只能放弃。(如果有谁知道解决办法,请评论~ 多谢。。。)
所以 我自己写了个窗口,代码也很简单。 但还是没实现timeout功能··· (哭泣,求助)
# -*- coding:utf-8 -*-
import tkinter as tk # 导入tkinter模块
import time
import threading
import re
def center_window(root, width, height): # 窗口居中
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
size = ‘%dx%d+%d+%d‘ % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
root.geometry(size)
def msg_box(title="Info", text="text", width=330, height=100):
window = tk.Tk() # 主窗口
window["bg"] = "white"
window.wm_attributes(‘-topmost‘, 1) # 窗口置顶
window.title(title) # 窗口标题
center_window(window, width=width, height=height) # 窗口 置于屏幕中央
#text = re.sub(r"(.{20})", "\\1\n", text)
l = tk.Label(window, text=text, width=40, height=3, font=(‘Arial‘, 12), bg="white", relief="flat")
l.pack()
b = tk.Button(window, text=‘退出‘, command=window.quit, width=5, relief="groove", bg="white")
b.pack(side=‘bottom‘, anchor="s")
def auto_close():
for i in range(30):
time.sleep(1)
print(i)
window.destroy()
t = threading.Thread(target=auto_close, daemon=True)
t.start()
# def fun_timer():
# global timer
# window.destroy()
# timer.cancel()
# timer = threading.Timer(15, fun_timer)
# timer.start()
window.mainloop() # 循环消息,让窗口活跃
if __name__ == ‘__main__‘:
# text = ""
# text = "1"
# text = "12345"
# text = "123456789"
# text = "你好"
# text = "这是五个字"
text = "落霞与孤鹭齐飞,秋水共长天一色"
# text = "123456789abcdefghijklmn"
for i in "abc":
time.sleep(1)
print(i)
msg_box(text=text)
for i in "正在等待最终结果":
time.sleep(1)
print(i)
如果感兴趣,大家可以运行这段代码,就知道存在什么问题了。。。
也希望 如果有对GUI编程懂得人或是了解tkinter的人 可以给出宝贵意见。
多谢~ (欢迎交流)
查看更多关于【求教 探讨】python tkinter的messagebox的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did170487