3

I have simple code like this:

from tkinter import *



def _show_value(*pargs):
    print(*pargs)



root = Tk()

entry_var1 = StringVar()
entry_var1.trace('w', _show_value)

entry_var2 = StringVar()
entry_var2.trace('w', _show_value)


e1 = Entry(root, textvariable=entry_var1)
e1.pack()

e2 = Entry(root, textvariable=entry_var2)
e2.pack()      


root.mainloop()

I want to print content of e1 and e2 on the fly, each time they are written. But instead of text, I get:

PY_VAR0  w
PY_VAR0  w
PY_VAR1  w
PY_VAR1  w

How to get text from e1 based on PY_VAR0, and when text from e2 when PY_VAR1 appears? Is this some internal names of entry_var1 and entry_var2? How do I reference entry_var1 and entry_var2 using PY_VAR0 and PY_VAR1?

user3654650
  • 5,283
  • 10
  • 27
  • 28
  • Use .get() method [Take a look at this answer](https://stackoverflow.com/questions/24768455/tkinter-intvar-returning-py-var0-instead-of-value/24768467#24768467) –  Jan 19 '18 at 06:30
  • Use .get() method [Take a look at this answer](https://stackoverflow.com/questions/24768455/tkinter-intvar-returning-py-var0-instead-of-value/24768467#24768467) –  Jan 19 '18 at 06:31

1 Answers1

3

You can do it in two ways.

First, use globalgetvar method of your root window.

def _show_value(*pargs):
    print(*pargs)
    print(root.globalgetvar(pargs[0]))

This, should give you text of respective entry.

Second, and probably more recommended is to pass StringVar references into _show_value, using lambdas for instance, rather then using global variables of Tk:

from tkinter import *



def _show_value(v, *pargs):
    print(*pargs)
    print(v.get())



root = Tk()

entry_var1 = StringVar()
entry_var1.trace('w', lambda *pargs: _show_value(entry_var1, *pargs))

entry_var2 = StringVar()
entry_var2.trace('w', lambda *pargs: _show_value(entry_var2, *pargs))


e1 = Entry(root, textvariable=entry_var1)
e1.pack()

e2 = Entry(root, textvariable=entry_var2)
e2.pack()      


root.mainloop()
Marcin
  • 215,873
  • 14
  • 235
  • 294