0

Hi I have my code here that is connected in my tkinter GUI and I've read that tkinter freezes when there's a loop in it since it's also a loop. So what I'm trying to do here is to give this function some time like 45 seconds then break the loop after that time passes. I've also tried threading but I do know how to implement it properly that's why I came up with this solution. But after I tried this one the loop doesn't break after 45 seconds. What am I doing wrong? Will this one work? Thank you very much in advance. I did watch a lot of tutorials about threading and queues but it's very complicated for a beginner like me so if this one is possible to work please help me. Thank you once again!

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
seluj rufo
  • 11
  • 3
  • For doing background work in a tkinter UI, you will want to use [after](https://stackoverflow.com/questions/50160783/background-process-and-tkinter/50161602#50161602) because it is simple, and works fine. – progmatico Nov 15 '18 at 14:39
  • Hi! Yes I'm also using after. But this one is a bit different. Here I'm waiting for a value to be satisfied and putting a time limit on it so that in case that the value is not achieved, GUI won't be left hanging. – seluj rufo Nov 15 '18 at 14:57
  • You should read from the serial from time to time using an `after` registered function. That way you never really block the UI. Blocking it for seconds is not nice for the user. – progmatico Nov 15 '18 at 15:05
  • 1
    That is, replace your while with an `after` callback scheme. – progmatico Nov 15 '18 at 15:07
  • Ok I'll try that. Thank you so much for replying – seluj rufo Nov 16 '18 at 00:20

0 Answers0