Search code examples
pythontkinter

Stopping a Tkinter window without closing it


I have written a python script that shows an animation of the evolution of a path-finding algorithm and i am wondering how to stop the main loop once it has reached a certain condition.

my basic idea (without any of my actual code) is:

import Tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=800, background="black")
canvas.pack()

def initialise():
    <some code to initialise everything on the canvas>

def move():
    <some code for move()>

root.after(1000,move)
root.mainloop()

i would like to be able to test a condition in the function move() that allows me to stop the Tkinter main loop but still leave the window open so you can see it, and then be able to do other things after (not with the window tho, it doesnt matter if that is unchangeable, just so long as it is visible until the user closes the window)

so basically similar to this:

while true:   # this represents the Tkinter mainloop
    <do something>
    if <final condition>:
        break

<some other operations on data>  # this happens after mainloop stops

Solution

  • You can't stop mainloop without destroying the window. That's the fundamental nature of Tkinter.

    What you can do instead is simply stop the animation. You can do that exactly like you propose: add a flag or final condition in your move method.

    def move():
        if some_condition:
            return
        ...
        root.after(1000, move)