Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting tkinter StringVar() error on init

(Python version: 3.1.1)

I am having a strange problem with StringVar in tkinter. While attempting to continuously keep a Message widget updated in a project, I kept getting an error while trying to create the variable. I jumped out to an interactive python shell to investigate and this is what I got:

>>> StringVar
<class 'tkinter.StringVar'>
>>> StringVar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python31\lib\tkinter\__init__.py", line 243, in __init__
    Variable.__init__(self, master, value, name)
  File "C:\Python31\lib\tkinter\__init__.py", line 174, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
>>>

Any ideas? Every example I have seen on tkinter usage shows initializing the variable with nothing sent to the constructor so I am at a loss if I am missing something...

like image 485
Arialth Avatar asked Jan 06 '12 18:01

Arialth


1 Answers

StringVar needs a master:

>>> StringVar(Tk())
<Tkinter.StringVar instance at 0x0000000004435208>
>>> 

or more commonly:

>>> root = Tk()
>>> StringVar()
<Tkinter.StringVar instance at 0x0000000004435508>

When you instantiate Tk a new interpreter is created. Before that nothing works:

>>> from Tkinter import *
>>> StringVar()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 251, in __init__
    Variable.__init__(self, master, value, name)
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 182, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
>>> root = Tk()
>>> StringVar()
<Tkinter.StringVar instance at 0x00000000044C4408>

The problem with the examples you found is that probably in the literature they show only partial snippets that are supposed to be inside a class or in a longer program so that imports and other code are not explicitly indicated.

like image 133
joaquin Avatar answered Nov 15 '22 15:11

joaquin