Tkinter - StringVar()无法正常工作

时间:2014-03-11 03:30:52

标签: python tkinter pythonxy

尝试使用TkInter初始化StringVar()时,我收到了这个巨大的错误。所以错误如下:

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

不完全确定这里出了什么问题。我正在使用A

Windows 7系统,

Python(x,y)版本2.7.5.2

Python 2.7.5

在Tkinter.py文件中:

__version__ = "$Revision: 81008 $" 

TkVersion = 8.5

如果有人知道发生了什么,那么我们将非常感激......

1 个答案:

答案 0 :(得分:4)

在创建Tkinter.StringVar之一之前,您需要创建Tkinter.Tk的实例:

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

以下是演示:

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