Change label text after object attribute change

9 views
Skip to first unread message

Ricardo Couto

unread,
Jun 14, 2019, 10:47:49 AM6/14/19
to Kivy users support
Hello all!

Suppose I have the following code:


class Person(object):
   
def __init__(self, name):
       
self.name = name


   
def change_name(self, *args, **kwargs):
       
self.name = "Jill"


class MyApp(App):
   
def build(self):
        p
= Person("Jack")
       
return Button(text=p.name, on_press=p.change_name)


if __name__ == '__main__':
   
MyApp().run()


How can I make it so that when I press the button the person name changes and the button text changes too?

Thanks!

Rick Kreifeldt

unread,
Jun 14, 2019, 11:01:05 AM6/14/19
to Kivy users support
First I'd make name a String Property in Person

Then it were me I'd either:
1) Make Person a Subclass of button so it can change it's name and set the button
2) Subclass Button, add a reference to Person, have the button change the person name when it's text changes (I use this technique the most)
3) Add a function in MyApp that changes the name, something like this:

class Person(object):
    name = StringProperty()
    
def __init__(self, name='Jack'):

        
self.name = name


    
def change_name(self, *args, **kwargs):
        if self.name == 'Jack'
            
self.name = "Jill"
        else:
            self.name = Jack

class MyApp(App):
    
def build(self):
        self.p 
= Person("Jack")
        self.button = Button(text=p.name, on_press=self.p.change_name)
        self.p.bind(name=self.change_button_text)
        
return self.button
    def change_button_text(self, n):
        self.button.text = n

You can do this is a more sophisticated way with less code all within .kv language, but this is easy to follow as you get started.  

Elliot Garbus

unread,
Jun 14, 2019, 12:53:33 PM6/14/19
to kivy-...@googlegroups.com
Change name to a kivy property 

class Person(object):
      name=StringProperty(‘’)

    def __init__(self, name):
        self.name = name





Sent from my iPad
--
You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To post to this group, send email to kivy-...@googlegroups.com.
Visit this group at https://groups.google.com/group/kivy-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/45038728-985c-4f22-94bd-0d0514da0276%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages