问题
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