问题
Okay I have asked this in a very specific way : https://stackoverflow.com/questions/21667119/tkinter-increment-a-varaible-while-still-running-code
But now to explain it in many less words.
I have a program running using tkinter. When a button is pressed it puts a value into a queue.
All I want is to be able to use a while loop to manipulate the data in the queue while the code still allows for more data to be added to the queue.
So basically repeated :
Check see if button pressed
if yes : add to queue
if no : do nothing
manipulate queue data.
Check the other question if you need to see code, its all in there.
I know many other posts have this but I cannot find an answer that explains it easily enough for me.
Simple code I can jar into a project please =D
thanks
回答1:
Your tkinter program already has a "while" loop running -- mainloop. In most cases you don't need another loop inside that loop.
The pattern for using this loop is to create a function that does what you want for the body of the loop. It should do exactly one iteration of the loop. Once it is done, it needs to arrange for itself to be called again some time in the future using after. How far in the future defines how fast your loop runs.
Here's an example that checks the queue once per second:
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()
来源:https://stackoverflow.com/questions/21667713/tkinter-background-while-loop