哔哔声间歇性地失踪

时间:2017-02-16 03:35:44

标签: python windows tkinter timer beep

我是Python的新手,并且认为我会使用Tkinter GUI编写一个小的Windows计时器程序。计时器在五秒钟的开始和结束时发出蜂鸣声。通过单击“开始”按钮,按Enter键或按空格键来激活计时器。计时器完成后需要进入待机状态,然后再按命令启动。

计时器时间,并且是准确的(它需要精确到小于0.03秒)。但是,有时(但不可预测)启动蜂鸣声不发出声音或发出蜂鸣声。没有生成RunTimeError。我怎样才能确保每次都发出哔哔声?

from Tkinter import *
from time import time
from winsound import Beep

class Timer(Frame):  
    """ Implements a timer frame widget. """                                                                
    def __init__(self, parent = None, **kw):
        Frame.__init__(self, parent, kw)
        self.timestr = StringVar()                

    def _update(self): 
        """ if 5 seconds is up, then beep, else loopback """
        self._elapsedtime = 5.0 - (time() - self._start)  
        if self._elapsedtime < 0.0:
            Beep(1500, 2000)
        else:
            self._timer = self.after(1, self._update)

    def StartKey(self, event):
        """ If Enter key or Spacekey is pressed """
        self.Start()

    def Start(self):                                                     
        """ Start the timer """
        self._start = time()
        Beep(4000, 200)
        self._update()

root = Tk()
root.geometry('500x300+30+30')
t = Timer(root)
t.pack(side=TOP)

"""" Big Start Button """
b = Button(root, text='Start', fg = 'black', bg = 'green', \
           height=2, width=10, font=('Ubuntu Mono', '40', 'bold'), \
           command=t.Start).pack(side=BOTTOM, pady=30)

"""" Bind Enter key and Spacebar  to starting the timer """
t.bind("<Return>", t.StartKey)
t.bind("<space>", t.StartKey)
t.focus_set()

root.mainloop()

0 个答案:

没有答案