How can I use the same callback function to trace multiple variables?

被刻印的时光 ゝ 提交于 2019-12-31 05:18:06

问题


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()


来源:https://stackoverflow.com/questions/27369546/how-can-i-use-the-same-callback-function-to-trace-multiple-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!