TheRoyale27
TheRoyale27

Reputation: 21

Having trouble with variables in tkinter Python

I've been running into some problems with variables in Tkinter and I am hoping that some of you may be able to help me with this. I have the following code...

counter = 0

from tkinter import *

root = Tk()

class HomeClass(object):
    def __init__(self, master):
        self.master = master
        self.frame = Frame(master)

        self.CounterTextLabel = Label(root, text=str(counter),
                                      bg="Black", fg="White")
        self.CounterTextLabel.pack(fill=X)

        self.ActionButton = Button(root, text="ADD", bg="green", fg="White",
                          command=self.CounterCommand)
        self.ActionButton.pack(fill=X)

    def CounterCommand(self):
        counter = counter + 1


k = HomeClass(root)
root.mainloop()

The intended effect is that when the green button is pressed, the number updates, going up by one each time. However, when I do press the button, I get the following error.

"UnboundLocalError: local variable 'counter' referenced before assignment"

How would I go about rectifying this? I hope somebody out there can help me out here. :)

TIA

Upvotes: 0

Views: 45

Answers (1)

user3354059
user3354059

Reputation: 402

You are defining counter outside of the scope of the class so when the method is run it is as if it doesn't exist. You should change your counter usage by removing its initial declaration at the top and then in the init function, you should put

self.counter = 0

Then in the counter command function you can use

self.counter = self.counter + 1

You will then be able to access the variable outside of the class by referencing it from what you assign to k, like this:

k = HomeClass(root)
print(k.counter)

Upvotes: 1

Related Questions