2014-02-10 56 views
0

好吧,我已經在一個非常特殊的方式問這個:https://stackoverflow.com/questions/21667119/tkinter-increment-a-varaible-while-still-running-codeTkinter的背景while循環

但現在來解釋它在許多少言。

我有一個程序運行使用tkinter。當按下按鈕時,它將一個值放入隊列中。

我希望能夠使用while循環來處理隊列中的數據,而代碼仍允許將更多數據添加到隊列中。

所以基本上重複:

Check see if button pressed 
if yes : add to queue 
if no : do nothing 
manipulate queue data. 

檢查的其他問題,如果你需要看到代碼,它都在那裏。

我知道很多其他職位有這個,但我找不到一個答案,很容易解釋它對我來說。

簡單的代碼,我可以罐子到項目,請= d

感謝

回答

1

你的Tkinter程序已經有一個「while」循環運行 - 主循環。在大多數情況下,您不需要在該循環內部使用另一個循環。

使用此循環的模式是創建一個函數,用於執行循環體的所需操作。它應該完成循環的一次迭代。一旦完成,它需要安排自己在未來的某個時間再次使用after。未來有多遠可以定義循環運行的速度。

這裏每秒這麼檢查隊列的示例一次:

import Tkinter as tk 
import Queue as queue 

class Example(tk.Frame): 
    def __init__(self, parent): 
     tk.Frame.__init__(self, parent) 

     self.queue = queue.Queue() 

     buttonFrame = tk.Frame(self) 
     for i in range(10): 
      b = tk.Button(buttonFrame, text=str(i), 
          command=lambda button=i: self.press(button)) 
      b.pack(side="top", fill="x") 
     self.lb = tk.Listbox(self, width=60, height=20) 
     self.vsb = tk.Scrollbar(self, command=self.lb.yview) 
     self.lb.configure(yscrollcommand=self.vsb.set) 

     buttonFrame.pack(side="left", fill="y") 
     self.vsb.pack(side="right", fill="y") 
     self.lb.pack(side="left", fill="both", expand=True) 

     self.manage_queue() 

    def press(self, i): 
     '''Add a button to the queue''' 
     item = "Button %s" % i 
     self.queue.put(item) 
     self.log("push", item) 

    def log(self, action, item): 
     '''Display an action in the listbox''' 
     message = "pushed to queue" if action == "push" else "popped from queue" 
     message += " '%s' (queue size %s)" % (item, self.queue.qsize()) 
     self.lb.insert("end", message) 
     self.lb.see("end") 

    def manage_queue(self): 
     '''pull an item off the queue and act on it''' 
     try: 
      item = self.queue.get_nowait() 
      self.log("pop", item) 
     except queue.Empty: 
      pass 

     # repeat again in 1 second 
     self.after(1000, self.manage_queue) 

if __name__ == "__main__": 
    root = tk.Tk() 
    Example(root).pack(fill="both", expand=True) 
    root.mainloop()