Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

user interface - Python Tkinter after() Only Executing Once

Something that seems like it should be so simple is giving me quite an issue. I have a Tkinter GUI that I am trying to update at regular intervals. Specifically I am deleting items off a canvas and replacing them. As an example here though I am just trying to print a statement that proves the after function is working correctly. When I place a button and click it, things work great, but I would like to do it automatically using the after() function. I am not having much luck getting it to work though.

class app():
    def __init__(self, frame):
        self.pad = tk.Canvas(frame)
        self.pad.create_window(10, 10, window=tk.Button(self.pad,command=update)
        self.pack(fill="both")

        #More Stuff

        #Neither one worked
        frame.after(1000,update)
        #self.pad.after(1000,update)

    def update(self):
        print "Updating"
        #More Stuff

if __name__=="__main__":
    root = tk.TK()
    app(root)
    root.mainLoop()

Of course this isn't the complete code, but hopefully it makes enough sense to see what I am trying to do. So when I click the button I see the words "Updating" appear. But when I use the after funciton, it appears once at the start and never again. I am also on Python version 2.4.4, don't judge I have no say in it haha. Thanks for any and all help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Place a call to after at the end of update:

def __init__(self, frame):       
    self.frame = frame
    ...
    self.frame.after(1000, self.update)

def update(self): 
    ...
    self.frame.after(1000, self.update)

This is the way after works. It only queues the callback (e.g. self.update) once. Per the docs:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...