Python程序中的'StringVar'问题

Ale*_*hol 6 python string user-interface tkinter widget

我正在尝试使用Tkinter在Python中编写一个非常简单的UI.我在StringVar班上遇到了一个小问题.问题是,当我运行python脚本时,我在初始化StringVar变量的行上得到一个错误.我已经编写了一个示例程序来解决这个问题,我想让它工作:

from Tkinter import *

var = StringVar()
var.set('test');
Run Code Online (Sandbox Code Playgroud)

当我通过python运行它时,我看到这个错误:

$ python test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    var = StringVar()
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 254, in __init__
    Variable.__init__(self, master, value, name)
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 185, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
Exception AttributeError: "StringVar instance has no attribute '_tk'" in <bound method StringVar.__del__ of <Tkinter.StringVar instance at 0xb73cc80c>> ignored
Run Code Online (Sandbox Code Playgroud)

我觉得这是我的Python安装的一个问题,但可能是我做错了什么?我在Ubuntu Linux上使用python版本2.6.5,如果这有所作为.

Nul*_*ter 11

我想你可能需要在调用StringVar之前显式调用Tk().

这样做:

from Tkinter import *
Tk() # Add this
var = StringVar()
var.set('test');
Run Code Online (Sandbox Code Playgroud)

  • 为什么在创建`StringVar`对象之前必须显式调用`Tk()`? (7认同)