Python While Loop Within Mainloop Causing Lag
When I run the code with the while True: loop included within the root.mainloop() it is making my GUI lag heavily and the code does not run as smoothly as I would like. I am wonder
Solution 1:
Simply use the after
method of TK
object. This will not impact redrawing and will not require calling any manual update functions, as it defers the execution of that code until the gui thread is not busy.
Split the code to be executed independently into a separate function and pass it to root.after
along with a time delay. The first time I used a delay of 0 so it executes immediately. Then at the end of the function call it again, this time passing the value 1000 (milliseconds) as a delay. It will execute repeatedly until you end the tkinter app.
# ... other code here
def gpiotask():
global temp
print(temp)
if(temp <= desiredtemp):
GPIO.output(17, GPIO.LOW)
GPIO.output(22, GPIO.HIGH)
temp += 5 # <- did you mean 0.5 here ?
crtmpstr.set("%s" % temp)
else:
GPIO.output(17, GPIO.HIGH)
GPIO.output(22, GPIO.LOW)
temp -= 0.5
crtmpstr.set("%s" % temp)
root.after(1000, gpiotask)
root.after(0, gpiotask)
root.mainloop()
Post a Comment for "Python While Loop Within Mainloop Causing Lag"