0

I want to initiate a class variable in order to pass it to another class. This variable has to be a StringVar variable as I want to use it for an Entry function of Tkinter. What I have done so far is this:

class ClassA:
    var1 = StringVar()
    def __init__(self,master):
        entry1 = Entry(master, textvariable = var1)

root = Tk()
my_gui = ClassA(root)
root.mainloop()

However, it gives the message:

StringVar instance has no attribute '_tk'.

This can be solved by adding Tk() before the declaration of StringVar but this produces a new window when I start my app. Is there a way to declare it without having to add the Tk() line? I can't figure out why this happens as I initiate Tk() outside the class.

3
  • Why exactly do you need it to be class variable as opposed to an instance variable? Commented Mar 16, 2018 at 10:22
  • "I want to initiate a class variable in order to pass it to another class." - it doesn't have to be a class variable in order for you to do that. Commented Mar 16, 2018 at 13:55
  • How else can I know the value of a StringVar from another class without it being a class variable? Commented Mar 18, 2018 at 18:12

1 Answer 1

3

Non-definition lines under a class declaration are read as soon as they're reached, and at the time at which the var1 = StringVar() there is no Tk instance, hence the error.

You can instead assign var1 class variable inside a method in the class, __init__ perhaps. Replace:

class ClassA:
    var1 = StringVar()
    def __init__(self,master):
        entry1 = Entry(master, textvariable = var1)

with:

class ClassA:
    def __init__(self,master):
        entry1 = Entry(master)
        ClassA.var1 = StringVar()
        entry1['textvariable'] = ClassA.var1

A complete example:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk


class ClassA:
    def __init__(self, master):
        entry1 = tk.Entry(master)
        ClassA.var1 = tk.StringVar()
        entry1['textvariable'] = ClassA.var1
        ClassA.var1.set('"asd"')
        print("[Inside call], it is: {}".format(entry1.get()))


root = tk.Tk()
my_gui = ClassA(root)
print("[Outside call], it is: {}".format(ClassA.var1.get()))
tk.mainloop()
Sign up to request clarification or add additional context in comments.

2 Comments

Using this example, when I want to use the StringVar from another class, it gives me the error: AttributeError: class ClassA has no attribute 'var1'.
@tzoukritzou With the example above, there has to be an instance of ClassA such as my_gui.

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.