在猕猴桃标签上生成随机数

时间:2019-08-15 08:49:56

标签: python html python-3.x kivy

我想在一个类似于倒计时动画的奇异果标签上显示随机生成的数字。

prototype.py(Python文件):

    from kivy.app import App
    from kivy.uix.label import Label
    from kivy.uix.boxlayout import BoxLayout
    import random
    import time


    class RootWidget(BoxLayout):
        def do(self):
            a = 0
            total = 5
            user = self.ids.name
            while a <= 10:
                randnum = random.randrange(total)
                user.text = str(randnum)

                a+=1


    class prototypeApp(App):
        def build(self):
            return RootWidget()

    if __name__ == "__main__":
        no=prototypeApp()
        no.run()

prototype.kv(kv文件):

    <RootWidget>:
        orientation:'vertical'
        Label:
            id: name
            text:''
            font_size:70
            height:70
        Button:
            text:'click me'
            on_release:app.root.do()
            size_hint_y:.1

没有错误,但标签上仅显示最后一个数字 随机生成的数字。 但是我希望循环中的数字在标签上顺畅流动,而不会只显示循环中的最后一个数字。

1 个答案:

答案 0 :(得分:0)

您在do()方法中的循环在主线程上运行,该主线程与更新GUI的线程相同。由于它是单线程,因此在您的do()方法完成之前,无法更新GUI,这意味着只有最后一个随机数才会显示在GUI中。

要解决此问题,请在单独的线程中运行该循环(请参见threading)。并且您将需要在主线程上重新执行self.ids.name.text = str(randnum)(考虑使用Clock来完成)。

您可能希望在循环中添加一个sleep,否则它可能发生得太快而看不到中间数字。