首页 > 解决方案 > while循环在一段时间后不会停止

问题描述

嗨,我在这里有我的代码,它连接在我的 tkinter GUI 中,并且我读到 tkinter 会在其中存在循环时冻结,因为它也是一个循环。所以我在这里要做的是给这个函数一些时间,比如 45 秒,然后在这段时间过去后打破循环。我也尝试过线程,但我知道如何正确实现它,这就是我想出这个解决方案的原因。但是在我尝试了这个之后,循环不会在 45 秒后中断。我究竟做错了什么?这个能用吗?非常感谢您提前。我确实看过很多关于线程和队列的教程,但是对于像我这样的初学者来说非常复杂,所以如果这个可以工作,请帮助我。再一次感谢你!

import serial

port = '/dev/ttyUSB0'
balance = 0
timeout = time.time() + 45


#get Pulse from Arduino
def getPulse():
    try:
        ser = serial.Serial(port, 9600)
        while True:
            read = ser.readline()
            try:
                value = int(read, 10)
                if (value != 0):
                    print(value)
                    break
            except ValueError:
                pass
        finally:
            return value

#Update Balance

def balanceCounter(coins):
    total = 0
    total += coins
    return total


def getCoins():
    pulse = getPulse()
    coinvalue = 0

    if pulse == 1:
        coinvalue = 1
        print("1 Inserted")
    elif pulse == 5:
        coinvalue = 5
        print("5 Inserted")
    elif pulse == 10:
        coinvalue = 10
        print("10 Inserted")

    return coinvalue

def mainCounter(numpages):
    global balance
    #input target Sample Amount
    targetValue = numpages
    tbalance = 0

    try:
        while tbalance <= int(targetValue):
            coins = getCoins()
            balance = balanceCounter(coins)
            tbalance += balance
            print("Total balance : "+str(tbalance))
            if tbalance >= int(targetValue) or time.time() > timeout:
                break
    finally:
                return tbalance

标签: python-3.xmultithreadingtkintertimewhile-loop

解决方案


推荐阅读