简体   繁体   中英

Python Kivy updating text of a children widget in a KV file

I have a Problem changing the Text of a Labelwidget, which is a child of my Rootwidget. I am trying to build a clock and I have a working example of a Clock but that example doesn't use a .kv file. I'm trying the following code:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock

class myRootWidget(BoxLayout):
    def update(self, *args):
        self.ids.timeDisplay.text = "THE TIME!"

class ll(App):
    def build(self):
        crudeclock = myRootWidget()
        Clock.schedule_interval(crudeclock.update, 1)
        return myRootWidget()
    
foo = ll()
foo.run()

this is my kv file:

<myRootWidget>:
    orientation: "vertical"
    
    Label:
        id : timeDisplay
        text : "blank"
    Label:
        text: "foo!"
    Button:
        id: myBtn
        text: "press me"    

The Code executes with no errors, but although the update() is run every second, the label shows "blank" instead of "THE TIME!", which would be necessary in order to update the time. Why is there no error? It seems like self.ids.timeDisplay. is actually accessing the label but the text won't change.

The problem is that you create two instances of the class myRootWidget One that you assign to the crudeclock variable, and another one that the builder returns and creates the application.

You assign the first one to the clock and its working OK, but you can't see it.

You are looking at the second one.

A solution is to use one instance, like this:

class ll(App):
    def build(self):
        crudeclock = myRootWidget()
        Clock.schedule_interval(crudeclock.update, 1)
        return crudeclock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM