下面的python代码有一个TKinter gui,可以更新计算函数中的内容(最后用self.after()调用自身.GUI还有一些滑块,用户将在能够调整参数。计算中有一个睡眠延迟,这就是问题:代码运行良好,除了time.sleep(1)不仅阻塞了1秒的计算,还阻止了GUI本身:它&# 39; s只能每秒移动滑块然后一切都被阻塞一秒钟。我能做什么time.sleep(1)只能使计算功能休眠,而不是GUI本身?我需要运行吗?计算函数在一个单独的线程中?
import Tkinter as tk
import ttk
import time
class GUI(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.i=0
self.var1 = tk.StringVar()
self.var2 = tk.StringVar()
self.var3 = tk.StringVar()
self.var4 = tk.StringVar()
self.var5 = tk.StringVar()
self.var6 = tk.StringVar()
self.var7 = tk.StringVar()
tk.Label(self, textvariable=self.var1,justify='left').pack()
tk.Label(self, textvariable=self.var2).pack()
tk.Label(self, textvariable=self.var3).pack()
tk.Label(self, textvariable=self.var4).pack()
tk.Label(self, textvariable=self.var5).pack()
tk.Label(self, textvariable=self.var6).pack()
tk.Label(self, textvariable=self.var7).pack()
p1 = tk.Scale(master, from_=1, to=20, orient=tk.HORIZONTAL).pack()
p2 = tk.Scale(master, from_=1, to=20, orient=tk.HORIZONTAL).pack()
p3 = tk.Scale(master, from_=1, to=20, orient=tk.HORIZONTAL).pack()
p4 = tk.Scale(master, from_=1, to=20, orient=tk.HORIZONTAL).pack()
p5 = tk.Scale(master, from_=1, to=20, orient=tk.HORIZONTAL).pack()
self.progress = ttk.Progressbar(self, orient="horizontal",length=100, mode="determinate")
self.progress.pack()
def calculation(self):
# complex calculations that last 30 minutes in total
self.i += 1
time.sleep(1)
max=1000
self.var1.set("Value1: "+str(self.i))
self.var2.set("Value2: "+str(self.i+100))
self.var3.set("Value3: "+str(self.i+100))
self.var4.set("Value4: "+str(self.i+100))
self.var5.set("Value5: "+str(self.i+100))
self.var6.set("Value6: "+str(self.i+100))
self.var7.set("Value7: "+str(self.i+100))
self.progress["value"] = int(round(self.i*100/max))
#self.update() # no need, will be automatic as mainloop() runs
self.after(1, self.calculation)
app=GUI()
app.calculation() # start calculations
app.mainloop() # run gui
答案 0 :(得分:0)
如果你绝对必须使用睡眠,那么是的,计算应该在另一个线程或另一个进程中完成。