Home > front end >  running a while loop in the background of a tkinter application
running a while loop in the background of a tkinter application

Time:11-26

I am trying to run a loop that checks to see if a card has been scanned and if one has been scanned and is valid then switch to another screen. however, if I run a while loop the program crashes and if i use .after then i get a recursion error. i tried to limit how often the .after runs but it still crashes. Can anyone help me? Thanks

Here is my code:

from tkinter import *
import PIL
import serial

def MainScreen():
    global mainscreen
    mainscreen = Tk()
    mainscreen.title('Main Screen')
    mainscreen.geometry('400x400')

    backgroundImage = PhotoImage(file="waves2.png")
    backgroundLabel = Label(mainscreen, image=backgroundImage)

    backgroundLabel.pack()
    mainscreen.after(10000, Scan())
    mainscreen.mainloop()

def Scan():
    x = ""
    if ser.in_waiting > 0:
        line = ser.readline().decode('utf-8').rstrip()
        x = line.strip()
        print(x)
        if x != '':
            print("card accepted")
        else:
            print('scan card')
     mainscreen.update()
     mainscreen.after(10000, Scan())

 if __name__ == '__main__':
        ser = serial.Serial('COM3', 9600, timeout=1)
        ser.flush()

MainScreen()

CodePudding user response:

(This is my first time answering questions here on StackOverFlow)

Running loop in different thread might be the answer

from tkinter import *
import threading
root = Tk()
root.geometry("500x700)
run = False

def Scan():
   run = True
   while run:
       you code here

function = threading.Thread(target=Scan)
function.start()

root.mainloop()
run = False

CodePudding user response:

The main option that came into my head is multi-threading. This is the process running things on a completely different thread to the main program and is very commonly used. With this you could run a while loop checking for the scan without effecting your tkinter application. The module for it is just called threading. Here is a great tutorial:

https://www.geeksforgeeks.org/multithreading-python-set-1/

If you don't want to go that far you could also look into asyncio:

https://realpython.com/async-io-python/

  • Related