Using a while loop in Pycharm and Kivy

how can I use a while loop in this code to read serial every 2 seconds and show it in a shortcut? this application will be hung in run, and I'm new to python to solve this problem.

from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from time import sleep import serial class LoginScreen(GridLayout): def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) self.cols = 2 self.rows = 2 ser = serial.Serial('COM3', 9600, timeout=0) while 1: sleep(2) ser.read() data = ser.read() self.add_widget(Label(text=str(data))) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': MyApp().run() 
+5
source share
1 answer

You cannot start the while loop while what Kivy himself does inside, each iteration checks the input, updates the gui, etc. By doing this on your own, you stop the Kivy cycle from an ever-advancing one. This is not just kiwi, but also how other GUI frameworks work, although not all of them run gui elements in the main thread.

Sleep also does the same - every time you sleep, it does just that, and gui freezes until it ends.

The solution is to connect to the Kivy event system and use the internal while loop. The easiest way is to add a new method to your LoginScreen, as shown below.

in __init__ :

 self.ser = serial.Serial('COM3', 9600, timeout=0) 

and new method:

 def update(self, dt): self.ser.read() # Not sure if you're deliberately or accidentally reading twice data = self.ser.read() self.add_widget(Label(text=str(data))) 

... and then

 from kivy.clock import Clock from functools import partial Clock.schedule_interval(self.update, 2) 

Then the update method will be called every 2 seconds.

+1
source

Source: https://habr.com/ru/post/1237994/


All Articles