Logan Darby Logan Darby - 3 months ago 18
Python Question

Cant define variable from tkinter Entry box

I am trying to learn tkinter in python 3.5, and for some reason I cannot print the text in an Entry box. Here is my code:

from tkinter import *

text = StringVar

def func():
print(text.get())

root = Tk()
root.geometry('450x450')
root.title('App')

mylabel = Label(text='My Label').grid(row = 0, column=0, sticky='W')

mybutton = Button(text = 'Button',command = func).grid(row=0,column=1,sticky='W')

myentry = Entry(root, textvariable=text).grid(row=1,column=1)

root.mainloop()


However when I press the button, I get an error saying

Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
return self.func(*args)
File "tkapp.py", line 6, in func
print(text.get())
TypeError: get() missing 1 required positional argument: 'self'


Thanks in advance for any help!

Answer

There are 2 errors:

1) as @cdonts said, use StringVar() instead of StringVar

2) StringVar() should be called after calling Tk(), so move text = StringVar() before creating myentry:

text = StringVar()
myentry = Entry(....)