且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

主循环中的Python While循环导致延迟

更新时间:2021-11-09 03:07:45

只需使用TK对象的after方法.这不会影响重绘,也不需要调用任何手动更新函数,因为它会延迟该代码的执行,直到gui线程不忙为止.

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.

将要独立执行的代码拆分为一个单独的函数,并将其与时间延迟一起传递给root.after.我第一次使用0的延迟,因此它立即执行.然后在函数末尾再次调用它,这一次将值1000(毫秒)作为延迟传递.它将重复执行,直到您结束tkinter应用为止.

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()