How can I use the same callback function to trace

2020-05-01 02:14发布

问题:

I would like to display the value of several StringVar() with some formatting on Labels.

import tkinter as tk

keys = range(2) # 2 for simplicity

root = tk.Tk()
myVars = {key: tk.StringVar() for key in range(5)}
myStrVars = {key: tk.StringVar() for key in range(5)}

def callback0(*args):
    blah = '{0:.3f}'.format(float(myVars[0].get()))
    myStrVars[0].set(blah)

def callback1(*args):
    blah = '{0:.3f}'.format(float(myVars[1].get()))
    myStrVars[1].set(blah)
#etc...

myCallbacks = {0: callback0,
               1: callback1}
               #etc...

for key in keys:
    myVars[key].trace('w', myCallbacks[key])
    tk.Entry(root, textvariable=myVars[key]).pack()
    label = tk.Label(root, textvariable=myStrVars[key]).pack()

root.mainloop()

Is there a way of writing a callback function so that I don't have to write one for each variable that I want to trace?

回答1:

You can send the key and the input to the function. This is a truncated version and a little different than your code but does what I think you want.

import tkinter as tk
from functools import partial

def callback(key, var, *args):
    print "callback var =", key, var.get()
    ##myStrVars[key].set(var[-1])

root = tk.Tk()

for key in range(5):
    var = tk.StringVar()
    var.trace('w', partial(callback, key, var))
    tk.Entry(root, textvariable=var).pack()

root.mainloop()