开发者

Issue with 'StringVar' in Python Program

I am trying to write a VERY simple UI in Python using Tkinter. I have run into a small problem with the StringVar class. The thing is, when I run the python script, I get an error on the line that initializes the StringVar variable. 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 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? I am using python version 2.6.5 on Ubuntu Linux if that makes a difference.


I think you might need to call Tk() explicitly before invoking StringVar.

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__(). The exception was raised with the statement "self.tk = master.tk". The following error message indicates that this "master" parameter is NoneType, and thus would have no such tk attribute. Looking at the Tkinter documentation for StringVar here: 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 (i.e. would it make sense to have a StringVar not associated with a widget?). 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜