-1

Trying to make a basic GUI where it counts to the number the user inputs.

When I hit the button to count through the while loop it doesnt change the counterlabel text in the way i want it too.

So i want to put 100 in the entry box and watch it count to 100 as "1,2,3,4,5.....etc" but at the moment i press the button and it jumps to 100.

from tkinter import *

def countloop():
    x = 1
    userinput = int(integerinput.get())
    while x <= userinput:
        counterlabel.configure(text=x)
        x += 1

window = Tk()

counttoolabel = Label(window, text="Count To?:", font=("Arial Bold", 50))
counttoolabel.grid(column=0, row=0)

integerinput = Entry(window, font=("Arial Bold", 50))
integerinput.grid(column=1, row=0)

inputbutton = Button(window, text="Count", font=("Arial Bold", 50), command=countloop)
inputbutton.grid(column=0, row=1)

counterlabel = Label(window, text=0, font=("Arial Bold", 50))
counterlabel.grid(column=1, row=1)

window.mainloop()

Metabite
  • 11
  • 2
  • Don't use `while` loops in `tkinter` programs. You will have to utilise `after()` instead. – quamrana Mar 22 '20 at 18:25
  • Read [While Loop Locks Application](https://stackoverflow.com/questions/28639228/python-while-loop-locks-application) and [how to use after method?](https://stackoverflow.com/questions/25753632) – stovfl Mar 22 '20 at 18:42

1 Answers1

-1

Use the after method built in to tkinter.

from tkinter import *

def countloop(x=0):
    userinput = int(integerinput.get())

    x += 1

    counterlabel.configure(text=x)

    if x < userinput:
        window.after(1000, lambda: countloop(x))

window = Tk()

counttoolabel = Label(window, text="Count To?:", font=("Arial Bold", 50))
counttoolabel.grid(column=0, row=0)

integerinput = Entry(window, font=("Arial Bold", 50))
integerinput.grid(column=1, row=0)

inputbutton = Button(window, text="Count", font=("Arial Bold", 50), command=countloop)
inputbutton.grid(column=0, row=1)

counterlabel = Label(window, text=0, font=("Arial Bold", 50))
counterlabel.grid(column=1, row=1)

window.mainloop()