Getting double callback from Stringvar change when entry widget selection changed

22 Views Asked by At

I am trying to write a simple program which involves tracing text from the Entry widget and being passed to function for processing as a float.

The problem I have is if I select the contents of the entry widget or like it does automatically when the entry widget gains focus and then type a new value it updates Stringvar twice, the first time Sringvar being empty ('') which is causing me issues later on as I want to convert to a float but cannot as it is empty.

So what am I doing wrong or how can I fix it.

I know I could use 'try except' to get past this and carry on with the program but I want to know why it is doing this and correct it if possible

This is a sample code that replicates the issue:

import tkinter as tk

root = tk.Tk()

txt1 = tk.StringVar()
txt1.set("0")


def check(*args):
    print(f'*{type(txt1.get())} - {txt1.get()}*')


entr1 = tk.Entry(root, textvariable=txt1)
entr1.place(x=20,y=20)

txt1.trace_add("write", check)

root.mainloop()

and this is the output from the 2 callbacks

*<class 'str'> - *
*<class 'str'> - 6*
0

There are 0 best solutions below