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.
A variable defined using StringVar() holds a string data where we can set text value and can retrieve it. Also, we can pass this variable to textvariable parameter for a widget like Entry. The widget will automatically get updated with the new value whenever the value of the StringVar() variable changes.
A normal variable can be used to set the value for any application whenever it is required. However, we can take the user input by creating an instance of the StringVar() object.
In the case of textvariable , which is mostly used with Entry and Label widgets, it is a variable that will be displayed as text. When the variable changes, the text of the widget changes as well.
Python tkinter DoubleVar() trace Here is an example which uses w ( write ) mode to display the value of the variable when ever it changes. We used one Button and used on Click event to change the value of this variable db1 from 5.1 to 10.34.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With