简体   繁体   English

如何将参数传递给StringVar的回调?

[英]How do I pass arguments to a callback for a StringVar?

I have set up an Entry widget using tkinter and am using a StringVar in order to trace any changes to it. 我已经使用tkinter设置了Entry小部件,并且正在使用StringVar来跟踪对其的任何更改。 However, when I try to use the callback function, I find that I am unable to pass any arguments to it. 但是,当我尝试使用回调函数时,发现无法将任何参数传递给它。

Here is what I have tried: 这是我尝试过的:

hpstring = StringVar()
hpstring.trace("w", hptrace)
hpstring.set("0")
hpbox = tk.Entry(frame, textvariable=hpstring)
hpbox.pack()

def hptrace(*args):
    print(hpstring)

This fails because hpstring is not defined. 由于未定义hpstring,因此失败。

hpstring = StringVar()
hpstring.trace("w", hptrace(hpstring))
hpstring.set("0")
hpbox = tk.Entry(frame, textvariable=hpstring)
hpbox.pack()

def hptrace(*args):
    print(hpstring)

This also somehow fails. 这也以某种方式失败了。

hpstring = StringVar()
hpstring.trace("w", lambda hpstring: hptrace(hpstring))
hpstring.set("0")
hpbox = tk.Entry(frame, textvariable=hpstring)
hpbox.pack()

def hptrace(*args):
    print(hpstring)

This time, it fails because "() takes 1 positional argument but 3 were given". 这次,它失败了,因为“()接受了1个位置参数,但给出了3个”。

Is there any way to have my callback function (hptrace) take hpstring as an argument? 有什么办法让我的回调函数(hptrace)以hpstring作为参数?

Is there any way to have my callback function (hptrace) take hpstring as an argument? 有什么办法让我的回调函数(hptrace)以hpstring作为参数?

You can use lambda or functools.partial . 您可以使用lambdafunctools.partial The important thing to remember is that the function called by the trace is called with three arguments , so whatever command you give to trace needs to accept those three arguments. 要记住的重要一点是, 跟踪调用的函数是用三个参数调用的 ,因此,您给trace发出的任何命令都必须接受这三个参数。

Using lambda , your code should look something like this if you want to send only hpstring to hptrace : 如果您只想将hpstring发送到hptrace ,则使用lambda ,您的代码应如下hptrace

hpstring.trace("w", lambda var_name, var_index, operation: hptrace(hpstring))

Note: you need to define hptrace before you attempt to use it, which the code in your question fails to do. 注意:在尝试使用hptrace之前,需要先定义它,问题中的代码无法执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM