Python tkinter script on a one second loop

Question:

I just wrote one of my first tkinter scripts. I started out with a simple calculator. I got it to a point where I can input two numbers (can be either float or int) and after pressing the button a script is started and the result is presented. This all works as it should.

I’m now just looking for a way to put the add function on a loop so that the user would not need to press a button, but the calculation would be performed once every second -> practically the user would get a result as soon as he enters the numbers without the need to press the calculate button.

Here is my code up to this point:

    from tkinter import *
        
    def add():
        first= float(firstnum.get())
        second= float(secondnum.get())
        sum = round(first+second,4)
        result.config(text=f"{sum}")
    
    window = Tk()
    window.title("Addition")
    window.config(padx=20, pady=20)
    
    
    title = Label(text="Adding", font=("Arial", 24,"bold"))
    title.grid(column=1,row=0)
    
    firstnum = Entry(width=7, font=("Arial", 24,"bold"),justify = CENTER)
    firstnum.grid(column=0,row=1)
    firstnum.insert(0,0)
    
    plus_sign = Label(text="+", font=("Arial", 24,"bold"))
    plus_sign.grid(column=1,row=1)
    
    secondnum = Entry(width=7, font=("Arial", 24,"bold"),justify = CENTER)
    secondnum.grid(column=2,row=1)
    secondnum.insert(0,0)
    
    calculate =Button(text="Calculate", command=add, font=("Arial", 14,"bold"), bg="gray")
    calculate.grid(column=0,row=2)
    
    result = Label(text="0", font=("Arial", 24,"bold"))
    result.grid(column=2,row=2)
          
    window.mainloop()

I did try to add an after command, but that function just delays everything for that period, without a repeat. What could I do to get the add function to loop once every second?

Asked By: Demions

||

Answers:

from tkinter import *

def add():
    first= float(firstnum.get())
    second= float(secondnum.get())
    sum = round(first+second,4)
    result.config(text=f"{sum}")
    # Schedule this function to be called again after 1000ms (1 second)
    window.after(1000, add)

window = Tk()
window.title("Addition")
window.config(padx=20, pady=20)

title = Label(text="Adding", font=("Arial", 24,"bold"))
title.grid(column=1,row=0)

firstnum = Entry(width=7, font=("Arial", 24,"bold"),justify = CENTER)
firstnum.grid(column=0,row=1)
firstnum.insert(0,0)

plus_sign = Label(text="+", font=("Arial", 24,"bold"))
plus_sign.grid(column=1,row=1)

secondnum = Entry(width=7, font=("Arial", 24,"bold"),justify = CENTER)
secondnum.grid(column=2,row=1)
secondnum.insert(0,0)

# Call the add function once to start the loop
window.after(1000, add)

result = Label(text="0", font=("Arial", 24,"bold"))
result.grid(column=2,row=2)

window.mainloop()
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.