Leon Siemon-Wenzel
Leon Siemon-Wenzel

Reputation: 13

How to implement a ever running loop within a PySimpleGUI code?

I couldnt something problem solving anywhere, so I think its time to post this question myself.

Here is my code:

import serial
from serial import Serial
import PySimpleGUI as sg



ser = serial.Serial('COM3', 115200, timeout=1)
read = False

sg.theme('DarkAmber')
layout = [  [sg.InputText(), sg.Button('Empfindlichkeit einstellen')],
            [sg.Button('start'), sg.Button('end')] ]

window = sg.Window('Window Title', layout)



while True:
    event, values = window.read()

    if read == True:
        reading = ser.readline()
        print(reading[0:256])

    if event == "start":
        read = True

    if event == sg.WIN_CLOSED or event == 'end':
        break

window.close()

The GUI shows up just perfectly fine and there are no errors. But the problem is the following part:

    if read == True:
        reading = ser.readline()
        print(reading[0:256])

This part of the code should run continuously when I pressed the button that says "start" once. But it doesnt. This part of the code just get executed one time, whenever I have pressed start once and then any other button. How can I fix this?

Upvotes: 1

Views: 5046

Answers (1)

Jason Yang
Jason Yang

Reputation: 13051

event, values = window.read()

It will stop here to wait event happen. After button 'start' clicked first time,

if event == "start":
    read = True

Variable read set to True after that event, then back to window.read() again to wait another event. There's no more event, so wait there.

To avoid to wait event there, you can use option timeout in method window.read() for how long to wait.

event, values = window.read(timeout=100)    # 100 ms to wait

Option timeout, milliseconds to wait until the Read will return if no other GUI events happen first. Default event or key is __TIMEOUT__.

Upvotes: 4

Related Questions