0

I'm trying to combine aruino RFID reading capabilities with python tkinter to make a desktop appication. Here, I used a function to create a toplevel which start listening to the serial port. It works perfectly fine when reading values, but if I try to move it, use 'Stop Scan' button it freezes and closes without any errors in terminal.

Toplevel function:

def scanWindow():
    scan_window = Toplevel(root)
    scan_window.attributes('-topmost', 'true')
    scan_window.geometry('300x300')
    scan_window.title('RFID Scanner')
    Label(scan_window, text="Enter user RFID tag to the scanner...", fg = "dark green", font = "Helvetica 10").place(x=150, y=150, anchor="center")
    scan_close = ttk.Button(scan_window, text="Stop Scan", command=lambda: scan_window.destroy()).place(x=150, y=270, anchor="center")
    scan_window.after(100, scan_port, scan_window)

scan_port function:

ser = serial.Serial('COM3', 9600)
ser.flushInput()

def scan_port(cur_window):
    ser_bytes = ser.readline()
    str_rn = ser_bytes.decode()
    str = str_rn.rstrip().strip()
    re_val = re.findall("[A-Z0-9][A-Z0-9] [A-Z0-9][A-Z0-9] [A-Z0-9][A-Z0-9] [A-Z0-9][A-Z0-9]", str)
    if(len(re_val) == 1):
        check_id_details(str)
        cur_window.destroy()

How can I avoid the freezing? I feel like the error is in scan_port function but can't put my finger on it. Any help is really appreciated.

  • 4
    you probably want to do the reading in another thread, put the data in a queue and then use `after` "loop" to update widgets with the data, there are multiple questions about this on this site – Matiiss Nov 15 '21 at 22:11
  • @Matiiss thank you for the reply and can you please link me to a similar solved question to check out the code. If you can it'll be a big help. – Dulan Pabasara Nov 15 '21 at 22:37
  • you can look here: https://stackoverflow.com/questions/69741939/how-to-set-tkinter-textvariable-running-on-separate-thread/69743264 and here: https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop or just use search – Matiiss Nov 15 '21 at 22:56
  • 1
    Also see [Trying to fix tkinter GUI freeze-ups (using threads)](https://stackoverflow.com/questions/53525746/trying-to-fix-tkinter-gui-freeze-ups-using-threads). – martineau Nov 15 '21 at 23:22
  • 1
    Is it because you are using readline that has blocking behavior? Only when there is data in the buffer with the [in_waiting property](https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.in_waiting), you can read it with [read() method](https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.read) and add it to a temporary variable, and if there is carriage return(or line feed) code in that data, you should display the data up to that point. That way, you won't have to add complicated processing such as threads. – kunif Nov 16 '21 at 00:23

0 Answers0