Python tkinter StringVar() error on init

匿名 (未验证) 提交于 2019-12-03 00:48:01

问题:

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

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!