0

I am new to tkinter. I want to write two numbers in two different entries in GUI and see their updated subtraction result on the display. here is my code:

from tkinter import *  
window = Tk()  

lb1 = Label(window,text="variable 1") 
lb1.pack()

name1=IntVar()  
en1=Entry(window, textvariable=name1)  
en1.pack()

lb2 = Label(window,text="variable 2")  
lb2.pack()

name2=IntVar()  
en2=Entry(window, textvariable=name2)  
en2.pack()

subt=IntVar()  
subt=name1.get()-name2.get()  
label_subt=Label(window, text=subt).pack()

how can I update label_subt?

  • 2
    Have you read any documentation? There is documentation for updating labels, and also for updating variables associated with labels. – Bryan Oakley Sep 05 '18 at 14:38
  • Not a duplicate, but this question should explain what you need to do: https://stackoverflow.com/q/17457178/8201979 – strava Sep 05 '18 at 14:41

2 Answers2

0

You could try calling the config method on the label after every subtraction. You’ll have to use the entry.get() method to get the string of each entry. And don’t forget to use int() to convert it to an integer so you can do your subtraction otherwise you’ll get an error

label_subt.config(text=result)

Gerald Leese
  • 355
  • 4
  • 13
0

You change the subt variable to the result of the subtraction before actually setting it to the label. Don't do that! Also, you set it as the text, not as the textvariable.

subt = IntVar()
Label(window, textvariable=subt).pack()

(Note that the result of pack() is not the Label, but None, so either move it to a separate line, as you did before, or just don't bind it to a variable that you never need anyway.)

Next, you can define a callback function for updating the value of the subt variable using the set method and bind that callback to any key press. You might want to narrow this down a bit, though.

def update(event):
    subt.set(name1.get() - name2.get())
window.bind_all("<Key>", update)
tobias_k
  • 81,265
  • 12
  • 120
  • 179