0

I have set up an Entry widget using tkinter and am using a StringVar in order to trace any changes to it. 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 = 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".

Is there any way to have my callback function (hptrace) take hpstring as an argument?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    You can't pass `hptrace` as an argument to `hpstring.trace` before you define it. – chepner Dec 23 '18 at 19:04
  • basically what chepner is trying to say is put `def hptrace(*args): print(hpstring)` before instead of after in the code in the 1st part and try it – Aditya Shankar Dec 23 '18 at 19:07
  • This doesn't have any effect with any one of the options I have tried. I still get the same errors if I put the second part of my code before the first. – BTD6_maker Dec 23 '18 at 19:12

1 Answers1

1

Is there any way to have my callback function (hptrace) take hpstring as an argument?

You can use lambda or functools.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.

Using lambda, your code should look something like this if you want to send only hpstring to 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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685