Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I update a label with information that changes based on a button click

import tkinter
top = tkinter.Tk()

class Person:
    def __init__ (self):

        self.health = 100

    def sword(self): 
        self.health = self.health - 10
        print(self.health)

n = Person()

sh = tkinter.Label(top, text=str(n.health)).place(x = .5,
                                          y = .5)

button = tkinter.Button(top, text="sword", command=n.sword)
button.place(relx=0.015, rely=0.5, relheight=0.3, relwidth=0.3)
                        

top.mainloop()

I am trying to make a mini app that whenever I click the "sword" button it takes away 10 health and displays how much you have left on the screen.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try this code it should correctly display the updated health value after clicking the "sword" button:
import tkinter

top = tkinter.Tk()

class Person:
    def __init__ (self):
        self.health = 100

    def sword(self): 
        self.health = self.health - 10
        sh.config(text=str(self.health))

n = Person()

sh = tkinter.Label(top, text=str(n.health))
sh.place(x=0.5, y=0.5)

button = tkinter.Button(top, text="sword", command=n.sword)
button.place(relx=0.015, rely=0.5, relheight=0.3, relwidth=0.3)

top.mainloop()

we store a reference to the Label widget in a variable named sh, so that you can later use sh.config(text=…) to update its text. The command argument for the Button widget is set to n.sword, so that clicking the button will call the sword method on the Person object n.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading