Python Kivy: Update Label

六眼飞鱼酱① 提交于 2021-02-11 14:31:08

问题


i am new in the Kivy Topic and i have got a simple question (i think).

With the function "zufall" i create a random number. This number should update every 2 seconds in the label.

But when i am running the code, the error "Label.text accept only str" occurs. But from my opinion i made the "random_number" to a string. Or is there another problem, with my thinking?

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
import random
from kivy.clock import Clock
from kivy.properties import StringProperty


class ConnectPage(GridLayout):
    # runs on initialization
    def zufall(self, *args):

        random_number = random.randrange(10)
        random_number = str(random_number)
        print(random_number)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 2  # used for our grid
        self.add_widget(Label(text='OEE'))
        self.add_widget(Label(text=self.zufall))



class EpicApp(App):
    def build(self):
        t = ConnectPage()
        Clock.schedule_interval(t.zufall, 2)
        return t


if __name__ == "__main__":
    EpicApp().run()   

Can someone of you give me a hint?


回答1:


Firstly you have to return your random number from your zufall function, and call that function from your __init__ like this:

    # runs on initialization
    def zufall(self, *args):
        random_number = random.randrange(10)
        random_number = str(random_number)
        return random_number

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 2  # used for our grid
        self.add_widget(Label(text='OEE'))
        self.add_widget(Label(text=self.zufall()))


来源:https://stackoverflow.com/questions/60851369/python-kivy-update-label

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!