Search code examples
python-3.xtkinterwinsound

Clock's clicking does not work in simoultaneous with countdown timer


I am using tkinter and winsound. I want the sound and the countdown timer to work simultaneously. Right now, once the clicking sound is over the timer appears.

I have seen some countdown timers examples which use "after". Ex: self.after(1000, self.countdown). But I need both in simoultaneous.

import tkinter as tk
from tkinter import Tk
from nBackTools.NBackTools import *
from nBackTools.ZBack import *
#To play sounds
import winsound 
from winsound import *
import numpy as np


class NBack:

    def __init__(self, master):
        ##Title of the window
        self.master = master
        master.title("N-Back")


        ##It measures the screen size (width x height + x + y)
        ##The opened window will be based on the screen size
        master.geometry("{0}x{1}-0+0".format(master.winfo_screenwidth(), master.winfo_screenheight()))
        self.canvas = tk.Canvas(master, width=master.winfo_screenwidth(), height=master.winfo_screenheight(), \
                            borderwidth=0, highlightthickness=0, bg="grey")


        self.canvasWidth = master.winfo_screenwidth()
        self.canvasHeight =  master.winfo_screenheight()


        ##If removed, a white screen appears
        self.canvas.grid()


        """

        BREAK TIMER

        """


        self.play()

        self.canvas.create_text(((self.canvasWidth/2), (self.canvasHeight/2)-130), text="LET'S TAKE A BREAK!", font=(None, 90))
        self.display = tk.Label(master, textvariable="")
        self.display.config(foreground="red", background = "grey", font=(None, 70), text= "00:00")
        self.display.grid(row=0, column=0, columnspan=2)


    def play(self):
        return PlaySound('clock_ticking.wav', SND_FILENAME)


root = Tk()
my_gui = NBack(root)
root.mainloop()

Solution

  • Doing 2 things at once is called "asynchronous". To enable that mode in winsound you need the ASYNC flag:

    def play(self):
        PlaySound('clock_ticking.wav', SND_FILENAME | SND_ASYNC)
    

    You will still need to use after to get the countdown to work.