Recording voice in a while loop using Tkinter

早过忘川 提交于 2019-12-13 15:21:45

问题


I'm coding a voice recording application and I want to start the recording when the user pushes a Button in Tkinter, and stop the recording when the user releases the Button.

import Tkinter

def record():
    while True
          Recordning runtines...
          if <button is released>
             stop audio steam...
             break


main = Tkinter.Tk()

b = Tkinter.Button(main, text='rec', command=record)
b.place(x="10", y="10")

main.mainloop()

How do I achieve the "if button is released"? Do I need to use Threading?


回答1:


If you don't want to freeze the GUI while recording, I recommend you to use multithreading. The click and release of the button can be accomplished with the events <Button-1> and <ButtonRelease-1>. I have wrapped the code into a class, so it also contains the flag for finishing the working thread.

import Tkinter as tk
import threading

class App():
    def __init__(self, master):
        self.isrecording = False
        self.button = tk.Button(main, text='rec')
        self.button.bind("<Button-1>", self.startrecording)
        self.button.bind("<ButtonRelease-1>", self.stoprecording)
        self.button.pack()

    def startrecording(self, event):
        self.isrecording = True
        t = threading.Thread(target=self._record)
        t.start()

    def stoprecording(self, event):
        self.isrecording = False

    def _record(self):
        while self.isrecording:
            print "Recording"

main = tk.Tk()
app = App(main)
main.mainloop()


来源:https://stackoverflow.com/questions/15268882/recording-voice-in-a-while-loop-using-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!