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

3
  • 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. Commented Feb 14, 2018 at 19:21
  • I didn't find what I was looking for. Could you help me please? Do you know how to solve this? Commented Feb 14, 2018 at 19:24
  • 1
    Possible duplicate of Using global variables in a function other than the one that created them Commented Feb 15, 2018 at 16:58

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.