本文介绍了如何使用同一个回调函数来跟踪多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想显示几个 StringVar()的值,并在标签上加上一些格式。

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?

推荐答案

您可以发送密钥和函数的输入。这是一个截短的版本,与您的代码有点不同,但是确实满足我的要求。

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

这篇关于如何使用同一个回调函数来跟踪多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:22