0

I have a visualization tool written in Tkinter. Typically, I execute it standalone and then manually close the window when I'm finished. However, I'd like to be call it from another Python program, execute the main loop once (and save the canvas as an SVG), and then close the window, allowing the program to continue.
If I could not even bother opening a window, but just re-use my code to draw an SVG, that would work too.

My tk application looks like this:

class MainApplication(tk.Frame):

    def __init__(self, output_path, parent=None):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        # draw visualization, save as svg
        #...
        #



From another part of my code, I call the

kill = True

root = tk.Tk()
root.title("Placement Visualizer")
MainApplication(output_path, root ).pack(side="top", fill="both", expand=True)
    
if kill:
    root.destroy()
root.mainloop()

I get this error: Tcl_AsyncDelete: async handler deleted by the wrong thread Aborted (core dumped) I've tried using root.quit() or removing root.mainloop(), but I don't get the desired result. Thank you

fgjt
  • 43
  • 8
  • Generally you shouldn't be calling `Tk()` more than once in a tkinter application — see [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) — which make your question moot in my opinion. – martineau Nov 06 '20 at 21:22
  • I removed the call from ```if __name__ == "__main__'```. Unmooted – fgjt Nov 06 '20 at 21:24
  • You can't call `root.mainloop()` after destroying it. – martineau Nov 06 '20 at 21:28
  • Have you read the question at all? – fgjt Nov 06 '20 at 21:29
  • Yes. You can't "main loop once". Tkinter doesn't work like that. The `mainloop()` must continue running until the program exits. At that point, execution will resume with any code that might be following the call to `mainloop()`. – martineau Nov 06 '20 at 21:33
  • The answer to the question [Tkinter — executing functions over time](https://stackoverflow.com/questions/9342757/tkinter-executing-functions-over-time) might be helpful. – martineau Nov 06 '20 at 21:35
  • So I execute ```mainloop()```, which draws everything on my canvas. Now you say that I could return to the code following the ```mainloop()``` call, if "the program exits" (I assume you mean the Tk program). How can I make the Tk program exit without hitting the 'close window' button? – fgjt Nov 06 '20 at 21:39
  • Calling `root.quit()` is how to exit `mainloop()` — although I see you say you've tried it. – martineau Nov 06 '20 at 21:41

1 Answers1

0

In "the other part of my code":

if kill:
    root.quit()
else:
    root.mainloop()

To not open a window at all, but to draw everything and save the SVG, just call root.quit(). To open the window normally (and have to close it, killing the process), call root.mainloop().

fgjt
  • 43
  • 8