更新录制时间

时间:2014-05-07 11:35:11

标签: python tkinter

我使用tkinter进行简单的python GUI进行屏幕录制。基本上,我在后端使用ffmpeg命令,tkinter作为前端触发ffmpeg命令。有些东西我坚持。我不知道为什么我的如果我以这种方式编程,时间就无法触发。

下面的代码基本上就是录制方法。您会注意到我实际上是在尝试在while循环中更新我的tkinter GUI。这个方法实际上是在我的类名为Gui_Rec()中,其中包含我需要的其他方法用于我的屏幕录音节目。

def rec(self):
    global videoFile
    mydate = datetime.datetime.now()
    videoFile = mydate.strftime("\%d%b_%Hh%Mm.avi")

    self.l['text']=os.path.expanduser('~')+"\Videos"
    self.l1['text']=videoFile
    self.b.config(state=DISABLED)
    self.b1.config(state=ACTIVE)

    t = Thread(target=self.rec_thread)#trigger another method using thread which will run ffmpeg commands here
    t.start()


    while True:
        if self.count_flag == False:
            break

        self.label['text'] = str("%02dm:%02ds" % (self.mins,self.secs))

        if self.secs == 0:
            time.sleep(0)
        else:
            time.sleep(1)

        if(self.mins==0 and self.secs==1):
            self.b1.config(fg="white")
            self.b1.config(bg="red")
            self.b.config(fg="white")
            self.b.config(bg="white")

        if self.secs==60:
            self.secs=0
            self.mins+=1
            self.label['text'] = str("%02dm:%02ds" % (self.mins,self.secs))

        main.gui.update()               
        self.secs = self.secs+1

类Gui_Rec()中的其他方法,然后在下面

def main():
   gui = Gui_Rec()
   gui.minsize(300,155)
   gui.maxsize(390,195)
   gui.title("Desktop REC")
   gui.attributes("-topmost", 1)
   gui.mainloop() #start mainloop of program


if __name__ == '__main__':
       main()

奇怪的是,如果我没有将上面的代码部分放在def main()中,那么当按下rec按钮时,GUI会随着时间的推移而更新。我不会真的知道如何去解决这个问题。把它放在另一个线程中然而它也不起作用。感谢大家的帮助。

1 个答案:

答案 0 :(得分:1)

while循环与Tkinter的mainloop产生冲突。线程或多处理是解决方案,但我建议查看Tkinter的after()方法。以下是如何使用after后处理计时器的简化示例:

from Tkinter import *

class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.mins = 0
        self.secs = 0

        # make a stringvar instance to hold the time
        self.timer = StringVar()
        self.timer.set('%d:%d' % (self.mins, self.secs))

        Label(self, textvariable=self.timer).pack()
        Button(self, text='Start', command=self._start_timer).pack()
        Button(self, text='Stop', command=self._stop_timer).pack()

    def _start_timer(self):
        self.secs += 1      # increment seconds
        if self.secs == 60: # at every minute,
            self.secs = 0   # reset seconds
            self.mins += 1  # and increment minutes

        self.timer.set('%d:%d' % (self.mins, self.secs))

        # set up the after method to repeat this method
        # every 1000 ms (1 second)
        self.repeater = self.after(1000, self._start_timer)

    def _stop_timer(self):
        self.after_cancel(self.repeater)

root = Tk()
App(root).pack()
mainloop()