Tkinter variable trace problem

C

C Martin

What am I doing wrong in this code? The callback doesn't work from the Entry widget.

##start code
import Tkinter

tk = Tkinter.Tk()
var = Tkinter.StringVar()
print var._name

def cb(name, index, mode):
print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode)
varValue = tk.getvar(name)
print " and variable value = %r" % varValue

var.trace('w', cb)

var.set('test')
entry = Tkinter.Entry(tk, textvariable=var)
entry.pack()

tk.mainloop()
##end code

It produces the following output. The first three lines appear right away, and the exception occurs when you type in the entry widget:
PY_VAR0
callback called with name='PY_VAR0', index='', mode='w'
and variable value = 'test'
callback called with name='PY_VAR0', index='', mode='w'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "D:\APCC\Projects\Utilities\VisualData\test.py", line 9, in cb
varValue = tk.getvar(name)
File "C:\Python25\lib\lib-tk\Tkinter.py", line 421, in getvar
return self.tk.getvar(name)
TclError: can't read "PY_VAR0": no such variable
 
P

Peter Otten

C said:
What am I doing wrong in this code? The callback doesn't work from the Entry widget.

##start code
import Tkinter

tk = Tkinter.Tk()
var = Tkinter.StringVar()
print var._name

def cb(name, index, mode):
print "callback called with name=%r, index=%r, mode=%r" % (name, index, mode)
varValue = tk.getvar(name)
print " and variable value = %r" % varValue

var.trace('w', cb)

var.set('test')
entry = Tkinter.Entry(tk, textvariable=var)
entry.pack()

tk.mainloop()
##end code

It produces the following output. The first three lines appear right away, and the exception occurs when you type in the entry widget:

PY_VAR0
callback called with name='PY_VAR0', index='', mode='w'
and variable value = 'test'
callback called with name='PY_VAR0', index='', mode='w'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "D:\APCC\Projects\Utilities\VisualData\test.py", line 9, in cb
varValue = tk.getvar(name)
File "C:\Python25\lib\lib-tk\Tkinter.py", line 421, in getvar
return self.tk.getvar(name)
TclError: can't read "PY_VAR0": no such variable

A quick look in the Tkinter source reveals that you need
tk.globalgetvar(), not tk.getvar().

I would actually recommend var.get(), so that you don't have to mess with
these internals at all.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top