Tkinter — StringVar() not working correctly

随声附和 提交于 2019-12-24 12:00:28

问题


While trying to initialize a StringVar() using TkInter I am getting this huge error back. So the error is as follows:

In [160]: from Tkinter import *

In [161]: p = StringVar()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-161-3e21f17f6e4f> in <module>()
----> 1 p = StringVar()

C:\Python27\lib\lib-tk\Tkinter.pyc in __init__(self, master, value, name)
    285         then the existing value is retained.
    286         """
--> 287         Variable.__init__(self, master, value, name)
    288
    289     def get(self):

C:\Python27\lib\lib-tk\Tkinter.pyc in __init__(self, master, value, name)
    216             master = _default_root
    217         self._master = master
--> 218         self._tk = master.tk
    219         if name:
    220             self._name = name

AttributeError: 'NoneType' object has no attribute 'tk'

In [162]:

Not entirely sure what is going wrong here. I am using A

Windows 7 system,

Python(x,y) version 2.7.5.2

Python 2.7.5

Within the Tkinter.py file:

__version__ = "$Revision: 81008 $" 

TkVersion = 8.5

If anyone has any clue as to what is going on, then it will be greatly appreciated ...


回答1:


You need to create an instance of Tkinter.Tk before you create one of Tkinter.StringVar:

root = Tk()  # You must do this first
p = StringVar()

Below is a demonstration:

>>> from Tkinter import *
>>>
>>> p = StringVar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 287, in __init__
    Variable.__init__(self, master, value, name)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 218, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
>>>
>>> root = Tk()
>>> p = StringVar()
>>>


来源:https://stackoverflow.com/questions/22315899/tkinter-stringvar-not-working-correctly

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