0

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

  • 1
    Have you done any research on the "local variable referenced before assignment" error? I know there are lots of questions on this site related to that. – Bryan Oakley Feb 14 '18 at 19:21
  • I didn't find what I was looking for. Could you help me please? Do you know how to solve this? – TheRoyale27 Feb 14 '18 at 19:24
  • 1
    Possible duplicate of [Using global variables in a function other than the one that created them](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – Nae Feb 15 '18 at 16:58

1 Answers1

1

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)
user3354059
  • 392
  • 1
  • 12