Home > Net >  Python main thread is blocking another thread
Python main thread is blocking another thread

Time:05-03

I am trying to make a timer to remind programmers of coffee breaks, but I still can't find a way to let the main thread not block the timer thread. I don't know what's wrong with my code.

I am not pasting the code here since my code needs some icons to work.

Here is the GitHub repo: https://github.com/cycool29/CoffeeTime, and the code is at /src/coffeetime.py.

Any suggestion would be much appreciated, thanks!

CodePudding user response:

If you are not posting the code here, how can someone here help you with it. Telling us to go off-site to Github doesn't seem like a proper way to ask.

Solution

There is a built in universal method that come with tkinter to achieve this.

w.after(delay_ms, callback=None, *args)

Requests Tkinter to call function callback with arguments args after a delay of at least delay_ms milliseconds. There is no upper limit to how long it will actually take, but your callback won't be called sooner than you request, and it will be called only once.

Example

import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="")
label.pack()

def timer(n, c=0):
    if n == c:
        label.config(text="Done!")
        return

    label.config(text=n)
    label.after(1000, lambda: timer(n - 1, c))

timer(10)

root.mainloop()
  • Related