How do I update a label with information that changes based on a button click
Question:
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.
Answers:
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.
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.
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.