2012-05-15 93 views
6

我對Python比較陌生,想用Tumblr的倒計時器功能在Tkinter中設置一個標籤。現在它所做的一切就是將標籤設置爲10,一旦達到10,我就不明白爲什麼。另外,即使我將計時器打印到終端,而不是「時間到了!」位從不打印。用Python和Tkinter製作倒數計時器?

import time 
import tkinter as tk 

class App(): 
    def __init__(self): 
     self.root = tk.Tk() 
     self.label = tk.Label(text="null") 
     self.label.pack() 
     self.Pomodoro() 
     self.root.mainloop() 

    ## Define a timer. 
    def Pomodoro(self): 
     p = 10.00 
     t = time.time() 
     n = 0 
     while n - t < p: ## Loop while the number of seconds is less than the integer defined in "p" 
      n = time.time() 
      if n == t + p: 
       self.label.configure(text="Time's up!") 
      else: 
       self.label.configure(text=round(n - t)) 

app=App() 

編輯:前面的回答表明,"Time's up!"從來沒有工作的原因是因爲它是如何不太可能是爲n等於準確t + p由於不精確使用time.time。定時器的最終基於控制檯的版本是:

import time 

## Define a static Pomodoro timer. 
def Countdown(): 
     p = 2.00 
     alarm = time.time() + p 
     while True: ## Loop infinitely 
      n = time.time() 
      if n < alarm: 
       print(round(alarm - n)) 
      else: 
       print("Time's up!") 
       break 

Countdown() 

然而,這不符合Tkinter的的原因,布萊恩·奧克利提到了他的回答和評論工作。

+0

這裏的(https://gist.github.com/zed/1951815) – jfs

回答

8

Tkinter已經有一個無限循環運行(事件循環),並且有一種方法可以計劃一段時間後運行的事情(使用after)。您可以通過編寫一個自動調用一次的函數來更新顯示來利用此功能。您可以使用類變量來跟蹤剩餘時間。

import Tkinter as tk 

class ExampleApp(tk.Tk): 
    def __init__(self): 
     tk.Tk.__init__(self) 
     self.label = tk.Label(self, text="", width=10) 
     self.label.pack() 
     self.remaining = 0 
     self.countdown(10) 

    def countdown(self, remaining = None): 
     if remaining is not None: 
      self.remaining = remaining 

     if self.remaining <= 0: 
      self.label.configure(text="time's up!") 
     else: 
      self.label.configure(text="%d" % self.remaining) 
      self.remaining = self.remaining - 1 
      self.after(1000, self.countdown) 

if __name__ == "__main__": 
    app = ExampleApp() 
    app.mainloop() 
+0

這就解釋了很多,謝謝[使用Tkinter的實施倒計時的代碼示例]一。我想知道爲什麼只有在最後一個項目達到後纔會更新,即使我用幾種不同的方法重寫了它。 –

+0

@RyanHasse:當Tkinter可以響應告訴它更新顯示的事件時,顯示只會更新。這些事件只能由事件循環處理。如果你有自己的循環,它會使事件循環捱餓,防止重繪請求發生。 –