[英]Issue with 'StringVar' in Python Program
I am trying to write a VERY simple UI in Python using Tkinter.我正在尝试使用 Tkinter 在 Python 中编写一个非常简单的 UI。 I have run into a small problem with the
StringVar
class.我在
StringVar
类中遇到了一个小问题。 The thing is, when I run the python script, I get an error on the line that initializes the StringVar
variable.问题是,当我运行 python 脚本时,在初始化
StringVar
变量的行上出现错误。 I have written a sample program with this issue that I would like to get working:我已经写了一个关于这个问题的示例程序,我想开始工作:
from Tkinter import *
var = StringVar()
var.set('test');
When I run it through python I see this error:当我通过 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
I have a feeling that this is an issue with my Python installation, but it may be that I am doing something wrong?我有一种感觉,这是我的 Python 安装问题,但可能是我做错了什么? I am using python version 2.6.5 on Ubuntu Linux if that makes a difference.
如果这有所不同,我将在 Ubuntu Linux 上使用 python 版本 2.6.5。
I think you might need to call Tk() explicitly before invoking StringVar.我认为您可能需要在调用 StringVar 之前显式调用 Tk()。
Just do this:只需这样做:
from Tkinter import *
Tk() # Add this
var = StringVar()
var.set('test');
I've never done anything with Tkinter myself, but here it looks like this StringVar class inherits from a base Variable class, as you can see in the traceback with the call to Variable.__init__()
.我自己从来没有用 Tkinter 做过任何事情,但在这里看起来这个 StringVar 类继承自一个基本的 Variable 类,正如你在回溯中看到的那样,调用
Variable.__init__()
。 The exception was raised with the statement "self.tk = master.tk".异常是由语句“self.tk = master.tk”引发的。 The following error message indicates that this "master" parameter is NoneType, and thus would have no such tk attribute.
以下错误消息表明此“主”参数是 NoneType,因此将没有此类 tk 属性。 Looking at the Tkinter documentation for StringVar here: http://epydoc.sourceforge.net/stdlib/Tkinter.StringVar-class.html
在此处查看 StringVar 的 Tkinter 文档: http : //epydoc.sourceforge.net/stdlib/Tkinter.StringVar-class.html
the master parameter is set to default to None.主参数设置为默认为无。 It looks like master should be supplied as a widget that might contain this StringVar (ie would it make sense to have a StringVar not associated with a widget?).
看起来 master 应该作为可能包含此 StringVar 的小部件提供(即,让 StringVar 不与小部件关联是否有意义?)。 I would have to say that you most definitely need to associate a StringVar object with a widget for it to have a 'tk' attribute.
我不得不说,您绝对需要将 StringVar 对象与小部件相关联,以便它具有“tk”属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.