The below python code has a TKinter gui which updates on what's going on in the calculation function (which calls itself at the end with self.after(). The GUI has also some sliders where the user will be able to adjust parameters. The calculation has a sleep delay in it which is the problem: The code works well, except that the time.sleep(1) is blocking not just the calculation for 1 second, but also the GUI itself: It's only possible to move the sliders every second and then everything is blocked for one second. What can I do that the time.sleep(1) only makes the calculation function sleep, but not the GUI itself? Do I need to run the calculation function in a separate thread?
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
如果绝对必须使用睡眠,那么可以,该计算应在另一个线程或另一个进程中完成。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.