please take a look at my code, it's really simple I need to take the value from the entry box and use it in my program and when pressing the add button I print it ,it keeps giving me this value PY_VAR1?!! wondering what I'm doing wrong!
here's the link for t runnable code for my question My code returns an empty value for the entry box
from Tkinter import *root = Tk()content = StringVar()text = StringVar()class addcase:def mains(self):master = Tk()master.wm_title("Add")bz = Button(master,text="add",command=self.add)bz.pack()l = Label(master,text="ok")l.pack()e = Entry(master,textvariable=content)e.pack()e.focus_set()content.set("default value")text = content.get()master.mainloop()def add(me):print content.get()print text
Since you haven't actually given us a runnable example, this is really no more than a guess, but…
When you fix the code so it actually runs, then click the button, it prints this:
default value
PY_VAR1
If you look at the code, it does this:
def add(me):print content.get()print text
The first line calls get
on a StringVar
that you've initialized with contents.set('default value')
, and never modified again, so of course it prints out default value
. As far as I can tell, you aren't surprised by this.
This second line doesn't call anything on the StringVar
named text
. Just print
ing a StringVar
, instead of calling get()
on it and printing the result, causes it to print the Tk name of the variable. The fact that you've also defined a local variable of the same name within addcase
is irrelevant. As far as I can tell, this is what you're surprised by. But you shouldn't be. The add
function can't see any local variables you've created in a completely unrelated function.
If you want a value to be shared between different methods of the same instance of a class, store them in an instance attribute, rather than a local variable.
But, more simply, if you just avoided reusing the same name for completely different variables in completely independent scopes, you would probably avoid confusing yourself, and it would be obvious what was going on.