Update label automatically with Tkinter

Asked

Viewed 77 times

-1

I would like to take the value 1 and subtract with the value 2 that the user type and update the result label automatically. This way, as the user is typing the result label is already updating. How could you do this?

    from tkinter import *

    root = Tk()
    root.geometry("200x300")

    valor1_content = DoubleVar()
    resultado_content = DoubleVar()

    valor1_content.set(125.55)

    lb_valor1 = Label(root, text="Valor 1")
    lb_valor1.place(relx=0.1, rely=0.1)
    lb_valor1_content = Label(root, text="", textvariable=valor1_content)
    lb_valor1_content.place(relx=0.1, rely=0.2)

    lb_valor2 = Label(root, text="Insere o valor 2")
    lb_valor2.place(relx=0.1, rely=0.3)
    valor2_entry = Entry(root, textvariable=resultado_content) 
    valor2_entry.place(relx=0.1, rely=0.4)

    lb_resultado = Label(root, text="Resultado")
    lb_resultado.place(relx=0.1, rely=0.5)
    resultado_entry = Label(root, text="", textvariable=resultado_content) 
    resultado_entry.place(relx=0.1, rely=0.6)

    root.mainloop()

1 answer

0

We can call a function in each key pressed to make the calculation.

from tkinter import *

root = Tk()
root.geometry("200x300")

valor1_content = DoubleVar()
resultado_content = DoubleVar()
resultado = DoubleVar()

def subtrair(e):
    resultado.set(valor1_content.get() - resultado_content.get())

valor1_content.set(125.55)

lb_valor1 = Label(root, text="Valor 1")
lb_valor1.place(relx=0.1, rely=0.1)
lb_valor1_content = Label(root, text="", textvariable=valor1_content)
lb_valor1_content.place(relx=0.1, rely=0.2)

lb_valor2 = Label(root, text="Insere o valor 2")
lb_valor2.place(relx=0.1, rely=0.3)
valor2_entry = Entry(root, textvariable=resultado_content) 
valor2_entry.place(relx=0.1, rely=0.4)
valor2_entry.bind("<KeyRelease>", subtrair)

lb_resultado = Label(root, text="Resultado")
lb_resultado.place(relx=0.1, rely=0.5)
resultado_entry = Label(root, text="", textvariable=resultado) 
resultado_entry.place(relx=0.1, rely=0.6)

root.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.