Frage

I have an external script that calls the drawWorld() function of this class. I want the drawing to be shown for 1-2 seconds and then to close and the control to return to the main script. I can manage to let the window disappear with the line

root.after(1000, lambda: root.destroy())

but I cannot return the flow to the main script. I tried

root.after(1000, lambda: root.quit())

but it doesn't work.

This is my code for the Tkinter class:

from Tkinter import Tk, Canvas, Frame, BOTH

class World(Frame):

def __init__(self, parent):
    Frame.__init__(self, parent)   
    self.parent = parent              
    self.parent.title("CliffWorld")        
    self.pack(fill=BOTH, expand=1)

    canvas = Canvas(self)        

    canvas.create_rectangle(4, 4, 31, 31, 
        outline="#f11", fill="#1f1", width=1)
    canvas.pack(fill=BOTH, expand=1)


def drawWorld():
    root = Tk()
    ex = World(root)
    root.geometry("330x220+300+300")
    root.after(1000, lambda: root.destroy())
    root.after(1000, lambda: root.quit())
    root.mainloop() 
War es hilfreich?

Lösung

In a comment to your question you wrote that your main program is just this:

import tkWorld
tkWorld.drawWorld()
print "end"

When I use that in a program, and use your example code (after fixing the indentation), it works fine. I see the window appear for one second, it goes away, and I send "end" printed on the console.

It works no matter whether the lambda calls root.quit() or root.destroy().

from Tkinter import Tk, Canvas, Frame, BOTH

class World(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent              
        self.parent.title("CliffWorld")        
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)        

        canvas.create_rectangle(4, 4, 31, 31, 
            outline="#f11", fill="#1f1", width=1)
        canvas.pack(fill=BOTH, expand=1)


def drawWorld():
    root = Tk()
    ex = World(root)
    root.geometry("330x220+300+300")
    root.after(1000, lambda: root.destroy())
    root.after(1000, lambda: root.quit())
    root.mainloop() 

if __name__ == "__main__":
    import tkWorld
    tkWorld.drawWorld()
    print "end"
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top