Python Kivy:更新标签 [英] Python Kivy: Update Label
问题描述
我是Kivy主题的新手,我有一个简单的问题(我认为).
i am new in the Kivy Topic and i have got a simple question (i think).
使用函数"zufall",我创建一个随机数. 标签中的此数字应每2秒更新一次.
With the function "zufall" i create a random number. This number should update every 2 seconds in the label.
但是当我运行代码时,发生错误"Label.text仅接受str". 但是我认为我将"random_number"设置为字符串.还是我的想法还有另一个问题?
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?
推荐答案
首先,您必须从zufall
函数中return
您的随机数,然后从您的__init__
中调用该函数,如下所示:
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()))
这篇关于Python Kivy:更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!