Ali
Ali

Reputation: 193

Tkinter dynamic label that displays the result of an equation?

Apologies if this has been solved somewhere else. I couldn't find any solutions that weren't based on running a function/clicking a button.

I have two columns of entry slots where slot 1 - slot 2 = outcome on column 3, I'd like to display the outcome live. Is this possible?

Displaying textvariable in a label seems dynamic enough but it doesn't seem to work if it's something being changed in the moment (unless I'm changing one variable and displaying that one variable in another label)

Right now, I just have it set which I'm aware only runs on start

preview

t1_in = IntVar(root, value=0)
t1_out = IntVar(root, value=0)

total1 = IntVar(root, value=0)
total1.set(t1_in.get() - t1_out.get())

in1 = Entry(root, width=10,textvariable=t1_in).grid(row=4, column=in_col)
out1 = Entry(root, width=10,textvariable=t1_out).grid(row=4, column=out_col)

t1 = Label(root, textvariable=total1, font=30).grid(row=4, column=t_col)

Is there any way to directly display total1 showing t1_in - t1_out dynamically as the user types in the text field new values?

Upvotes: 1

Views: 227

Answers (1)

Robert Kearns
Robert Kearns

Reputation: 1706

I would do this with tracing, and an intermediate variable that holds the end result. There may be a better way to do this, but something like this works well:

t1_in = IntVar(root, value=0)
t1_out = IntVar(root, value=0)

total1 = IntVar(root, value=0)


in1 = Entry(root, width=10,textvariable=t1_in).grid(row=4, column=in_col)
out1 = Entry(root, width=10,textvariable=t1_out).grid(row=4, column=out_col)

def dynamic_total(var, index, mode):
    total1.set(t1_in.get() - t1_out.get())

t1_in.trace_add('write', dynamic_total)
t1_out.trace_add('write', dynamic_total)

t1 = Label(root, textvariable=total1, font=30).grid(row=4, column=t_col)

Upvotes: 1

Related Questions