Search code examples
pythontkintertkinter-entry

Python - I want two entry widgets Sum without using button


I do not understand how to do this. I need to sum of two entries and then put the sum into another entry widget without any Buttons.

Example one

from tkinter import *
def sum():
a=float(t1.get())
b=float(t2.get())
c=a+b
t3.insert(0,c)
win=Tk()
win.geometry('850x450')

l1=Label(win,text="First Number")
l1.grid(row=0,column=0)
t1=Entry(win)
t1.grid(row=0,column=1)

l2=Label(win,text="Second Number")
l2.grid(row=1,column=0)
t2=Entry(win)
t2.grid(row=1,column=1)

l3=Label(win,text="Result")
l3.grid(row=2,column=0)
t3=Entry(win)
t3.grid(row=2,column=1)

b1=Button(win,text="Click For SUM",command=sum)
b1.grid(row=3,column=1)

win.mainloop()

I hope anyone can handle this..

Thanks in advance..


Solution

  • You can run a function that regularly every one second resets the third entry's value to the sum of the first and the second like so-:

    try :
        import tkinter as tk # Python 3
    except :
        import Tkinter as tk # Python 2
    
    def update_sum() :
        # Sets the sum of values of e1 and e2 as val of e3
        try :
            sum_tk.set((int(e1_tk.get().replace(' ', '')) + int(e2_tk.get().replace(' ', ''))))
        except :
            pass
        
        root.after(1000, update_sum) # reschedule the event
        return
    
    root = tk.Tk()
    
    e1_tk = tk.StringVar(root) # Initializes a text variable of tk to use to get e1's val.
    e2_tk = tk.StringVar(root) # Initializes a text variable of tk to use to get e2's val.
    sum_tk = tk.StringVar(root) # Initializes a text variable of tk to use to set e3's val.
    
    # Entries
    e1 = tk.Entry(root, textvariable = e1_tk)
    e2 = tk.Entry(root, textvariable = e2_tk)
    e3 = tk.Entry(root, textvariable = sum_tk)
    
    e1.pack()
    e2.pack()
    e3.pack()
    
    # Will update the sum every second 1000 ms = 1 second it takes ms as arg.
    root.after(1000, update_sum)
    root.mainloop()
    

    You can adjust the delay between updates as you wish.