2

我正在编写一个录音应用程序,我想在用户按下 Tkinter 中的按钮时开始录音,并在用户释放按钮时停止录音。

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()

如何实现“如果按钮被释放”?我需要使用线程吗?

4

1 回答 1

4

如果您不想在录制时冻结 GUI,我建议您使用多线程。可以通过事件<Button-1><ButtonRelease-1>来完成按钮的单击和释放。我已将代码包装到一个类中,因此它还包含用于完成工作线程的标志。

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()
于 2013-03-07T13:19:37.770 回答