Thomas Caio
Thomas Caio

Reputation: 81

Python tkinter label formulas

how can I make a label with a formula and whenever I change the value in entry, does it automatically change the value in the label? As if it were excel cells with formulas. And in case it would have to be invisible (without content) while the entry is empty.

import tkinter as tk

root = tk.Tk()
ent1 = tk.Entry(root)
lab1 = tk.Label(root,text='Price')
ent2 = tk.Entry(root)
lab2 = tk.Label(root,text='Quantity')
lab3 = tk.Label(root,text='') #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack() 
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

Upvotes: 0

Views: 580

Answers (1)

Novel
Novel

Reputation: 13729

Use the trace method to execute a function when a variable changes.

import tkinter as tk

def update(*args):
    try:
        output_var.set(price_var.get() * quantity_var.get())
    except (ValueError, tk.TclError):
        output_var.set('invalid input')

root = tk.Tk()

lab1 = tk.Label(root,text='Price')
price_var = tk.DoubleVar()
price_var.trace('w', update) # call the update() function when the value changes
ent1 = tk.Entry(root, textvariable=price_var)

lab2 = tk.Label(root,text='Quantity')
quantity_var = tk.DoubleVar()
quantity_var.trace('w', update)
ent2 = tk.Entry(root, textvariable=quantity_var)

output_var = tk.StringVar()
lab3 = tk.Label(root, textvariable=output_var) #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack()
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

root.mainloop()

Upvotes: 1

Related Questions