【发布时间】:2017-09-29 08:35:48
【问题描述】:
我正在寻找一种优雅的方式来在脚本运行时在屏幕上显示日志行。
from time import sleep
from threading import Thread
import tkinter as tk
class WaitGuiPrallel(Thread):
def __init__(self, TXT='Wait!', ttl='Logs'):
self.txt = TXT
Thread.__init__(self)
self.ttl = ttl
self.start() # This is starting the self.run()
def run(self):
self.root = tk.Tk()
self.root.attributes("-topmost", True)
self.root.title(self.ttl)
self.label = tk.Label(self.root, text=self.txt, font=("Helvetica", 20))
self.label.pack()
self.Location()
self.root.mainloop()
def Exit(self):
self.root.quit()
def Location(self):
w = 500 # width for the Tk root
h = 150 # height for the Tk root
ws = self.root.winfo_screenwidth() # width of the screen
self.root.geometry('%dx%d+%d+%d' % (w, h, ws - w - 20, 10))
def Update(self, newText):
self.txt1 = newText
self.label.destroy()
self.label = tk.Label(self.root, text=self.txt1,
font=("Helvetica", 12))
self.label.pack()
self.root.update()
Wait = WaitGuiPrallel(TXT='Wait! Do not touch mouse or keyboard')
sleep(2)
for t in range(5):
sleep(1)
Wait.Update(newText='Log line %s' % t)
Wait.Update(newText='Done!')
sleep(1)
Wait.Exit()
当前脚本有几个问题:
不优雅——一定有更好的办法
从不同线程更新时出现问题
有时无法从 Spyder+IPython 运行两次(IPython 冻结)
【问题讨论】:
-
您的意思是要同时打开 2 个窗口?忘记线程,只需使用
tk.Toplevel来制作第二个窗口。
标签: python python-3.x tkinter spyder