[Python] Tkinter GUI buttons running loops

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to learn how to use TKinter to make GUI for Python apps. I'm trying to create a Pomodoro timer, however I've encountered a couple of issues.

    1. I run while loop in another function to update label with time left
    2. While in loop GUI unresponsive (that's OK)
    3. I've googled a little bit, went through some StackOverflow questions and I've found that this function running loop could be run in a separate thread.

    This solved the first issue, but there is another

    1. Cancel button works, but I don't see the click animation.
    2. Timer does not stop immediately.

    Can you kindly explain why this is happening and what I can do to increase the responsiveness of my GUI?

    import time
    import tkinter
    import winsound
    from tkinter.ttk import Combobox
    import threading


    def run_thread():
    global stop
    stop = False
    start_timer_btn.grab_release()
    threading.Thread(target=countdown()).start()


    def stop_timer():
    global stop
    stop = True


    def countdown():
    option = combo.get()
    if option == "25":
    seconds = 1500
    elif option == "15":
    seconds = 900
    # elif option == "2":
    # countdown(300)
    # elif option == "3":
    # countdown(1200)
    global stop
    while seconds and not stop:
    seconds -= 1
    print("minutes", seconds // 60, "seconds", seconds % 60)
    timer_label.configure(text=str(seconds // 60) + ":" + str(seconds % 60))
    window.update()
    time.sleep(1)
    winsound.PlaySound("SystemExit", winsound.SND_ALIAS)


    stop = False
    window = tkinter.Tk()
    window.title("POMODORO Timer")
    window.geometry("300x250")

    combo = tkinter.ttk.Combobox(window)
    combo["values"] = [25, 15]
    combo.current(1)

    timer_label = tkinter.Label(window, text="00:00")
    start_timer_btn = tkinter.Button(window, text="Start timer", bg="green", fg="white", command=run_thread)
    stop_timer_btn = tkinter.Button(window, text="Stop timer", bg="red", fg="white", command=stop_timer)

    combo.grid(row=1, column=0)
    start_timer_btn.grid(row=1, column=1)
    stop_timer_btn.grid(row=1, column=2)
    timer_label.grid(row=0, column=2, columnspan=3)

    window.mainloop()

    Continue reading...

Compartilhe esta Página