2013-03-07 51 views
2

我正在編寫一個語音錄製應用程序,並且我想在用戶在Tkinter中按下按鈕時開始錄製,並在用戶釋放按鈕時停止錄製。使用Tkinter在while循環中錄製語音

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

如何實現「if按鈕被釋放」?我需要使用線程嗎?

回答

4

如果您不想在錄製時凍結GUI,我建議您使用多線程。點擊和釋放按鈕可以通過事件<Button-1> and <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()