【问题标题】:Tkinter background while loopTkinter 背景 while 循环
【发布时间】:2014-02-10 01:38:47
【问题描述】:

好的,我已经以非常具体的方式提出了这个问题:https://stackoverflow.com/questions/21667119/tkinter-increment-a-varaible-while-still-running-code

但是现在用更少的语言来解释它。

我有一个使用 tkinter 运行的程序。当按下按钮时,它会将一个值放入队列中。

我想要的只是能够使用 while 循环来操作队列中的数据,同时代码仍然允许将更多数据添加到队列中。

所以基本上重复了:

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

如果您需要查看代码,请查看其他问题,所有代码都在其中。

我知道许多其他帖子都有这个,但我找不到对我来说足够容易解释的答案。

我可以将简单的代码放入项目中=D

谢谢

【问题讨论】:

    标签: python user-interface tkinter queue


    【解决方案1】:

    您的 tkinter 程序已经运行了一个“while”循环——mainloop。在大多数情况下,您不需要该循环内的另一个循环。

    使用这个循环的模式是创建一个函数来为循环体做你想做的事情。它应该只进行一次循环迭代。一旦完成,它需要安排自己在将来的某个时间使用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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多