2012-01-06 22 views
6
(versión Python: 3.1.1)

Python tkinter VarCadena() error en init

Estoy teniendo un problema extraño con VarCadena en tkinter. Al intentar mantener continuamente un widget de mensaje actualizado en un proyecto, seguí recibiendo un error al intentar crear la variable. Salté a un shell de python interactivo para investigar y esto es lo que obtuve:

>>> 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' 
>>> 

¿Alguna idea? Todos los ejemplos que he visto en programas de uso Tkinter inicializar la variable sin nada enviado al constructor, así que estoy en una pérdida si estoy perdiendo algo ...

Respuesta

10

VarCadena necesita un maestro:

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

o más comúnmente:

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

Al crear una instancia Tk se crea un nuevo intérprete. Antes que nada funciona:

>>> 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> 

El problema con los ejemplos que encontramos es que, probablemente, en la literatura que muestran solo fragmentos parciales que se supone que están dentro de una clase o en un programa más largo de modo que las importaciones y otros códigos son no indicado explícitamente

Cuestiones relacionadas