Python - Using Threads in Windows for Multiple Events

Asked

Viewed 45 times

-1

After I click the Button the window stops responding until the sound ends, and what I wanted it to continue to answer after clicking the button

import winsound
b=winsound.Beep
class janela:
    def __init__(self, janela):

        self.frame=Frame(janela)
        self.frame.pack()

        janela.resizable(width=True, height=True)
        janela.config(bg='gray')
        janela.title('PIIIIIII')
        Canvas(janela, width=600, height=680, bg='BLACK').pack()


        fonte=('Comic Sans MS','14','bold')
        self.botao=Button(self.frame, text='Pi',
                            command=(self.tocar), font=fonte,
                            fg='red', bg='yellow')
        self.botao.pack(side=LEFT)

        
        self.botao1=Button(self.frame, text='Pi2',
                            command=(self.toca2), font=fonte,
                            fg='red', bg='grey')
        self.botao1.pack(side=LEFT)
    def tocar (self):
        b(1000,1000)

    def toca2 (self):
        b(2000, 1000)


jan1=Tk()
janela(jan1)
jan1.mainloop()```

1 answer

3


From what I’ve researched it’s normal winsound.Beep, in the winsound.PlaySound we have the winsound.SND_ASYNC, which would allow to run without crashing (I believe), but it is for files or operating system sounds (Windows only, as is the library name, winsound):

  • 'Systemasterisk'
  • 'Systemexclamation'
  • 'Systemexit'
  • 'Systemhand'
  • 'Systemquestion'

Or point to an existing sound file.

In such cases it is possible to add the flag SND_ASYNC, only use winsound.SND_ALIAS it will also freeze until the sound ends.

But how probably not to use PlaySound and yes the .Beep you can use threading.Thread:

from winsound import Beep
from threading import Thread
from tkinter import *

...

def tocar(self):
    Thread(target=self.executarBeep, args=[1000, 1000]).start()


def tocar2(self):
    Thread(target=self.executarBeep, args=[2000, 1000]).start()


def executarBeep(self, frequency, duration):
    Beep(frequency, duration)

If you want the sound to touch until the end happens a double click or the user tries to click several times just create a variable to check when begins and ends the Beep, releasing at the end, something like:

class janela:
    executando = False

    ...

    def executarBeep(self, frequency, duration):
        if not self.executando:
            self.executando = True

            Beep(frequency, duration)

            self.executando = False
  • all right, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.