Mark Costello
Mark Costello

Reputation: 155

How do I call upon Tkinter labels defined in a different function?

I am making a simple little clicker game using Python. This is currently what I have:

from tkinter import *

x = [0]
y = [1]

class Game:
    def __init__(self, master):
        master.title('Game')

        Amount = Label(master,text=x[0])
        Amount.pack()

        Butt = Button(master,text='Press!',command=self.click)
        Butt.pack()

    def click(self):
        x[0] = x[0] + y[0]
        Amount.config(root,text=x[0])
        print(x[0])

root = Tk()
root.geometry('200x50')
game = Game(root)
root.mainloop()

When I run this, it tells me that 'Amount' is not defined within the click function. I know this is because it's defined in a different function. I want to know how to make it so the click function recognizes 'Amount'.

Upvotes: 0

Views: 203

Answers (1)

omri_saadon
omri_saadon

Reputation: 10631

You should either define your amount as data member(each instance has his value) or static member(same value withing all classes instances).

I would go with data member.

In order to use it as a data member you should use self.Amount.

So, this is what you need:

from tkinter import *

x = [0]
y = [1]

class Game:
    def __init__(self, master):
        master.title('Game')

        self.Amount = Label(master,text=x[0])
        self.Amount.pack()

        Butt = Button(master,text='Press!',command=self.click)
        Butt.pack()

    def click(self):
        x[0] = x[0] + y[0]
        self.Amount.config(text=x[0])
        print(x[0])

root = Tk()
root.geometry('200x50')
game = Game(root)
root.mainloop()

self is shared among your class methods, so you can access the Amount variable through it.

Upvotes: 1

Related Questions