Home > OS >  Show a random number every second in Kivy
Show a random number every second in Kivy

Time:11-03

I'm trying to create a button, when pressed it shows a random integer in a range from 1-10 each second continuously for 10 seconds.I'm completely new to kivy, but I've searched related questions on the internet, so please be gentle.

Currently the the label text only shows the last number. Kivy waits for the for loop to finish and display the final number generated. While the for loop is taking place, kivy gui will die out. Any form of help will be greatly apppriciated!

The following is my code and kv file.

class WidgetExample(GridLayout):

    my_text = StringProperty('Press Click me')
    def on_button_click(self):
        for i in range(1,10):
            i=random.randint(1,10)
            time.sleep(1)
            print(i)
            self.my_text = str(i)


class TheLabApp(App):
    pass

TheLabApp().run()
WidgetExample:

<WidgetExample>:
    cols: 3
    Button:
        text: 'Click me'
        on_press: root.on_button_click()
    Label:
        text: root.my_text

CodePudding user response:

While the for loop is taking place, kivy gui will die out...

Apparently that's not true. Your callback do_button_click runs on the same thread as the GUI but sequentially. That's why once the execution of the callback finished, it then renders the final result in the GUI. To execute that separately you can use another thread without affecting the main thread.

    def on_button_click(self):
        # Start a new thread. Be aware of creating new thread every time you press the button.
        # In which case you need to keep a reference or track the created thread.
        threading.Thread(target = self.do_button_click).start()

    def do_button_click(self):
        for i in range(1,10):
            i=random.randint(1,10)
            time.sleep(1)
            print(i)
            self.my_text = str(i)

Alternatively you can use module Clock.

  • Related