Satish Bitla
Satish Bitla

Reputation: 57

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..

Upvotes: 1

Views: 655

Answers (2)

typedecker
typedecker

Reputation: 1390

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.

Upvotes: 0

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

Without any buttons, you might want to use bind. So try saying this at the end of your code.

t2.bind('<Return>',sum)

and change the function to:

def sum(event):
..... #same code

Now you can remove you button and when you press the Enter key in the second entry widget, itll call the sum() and then insert the output to the third entry widget.

Extra tips:

  • I recommend to change the name of the function from sum to something else, as sum is a built-in python function.
  • You could also add an extra bind like, t1.bind('Return',lambda event:t2.focus_force()) so when the user press enter key in the first entry, they will move to the next entry widget(same as the tab key).

Hope it helped, if any doubts, do let me know.

Cheers

Upvotes: 1

Related Questions