1

I'm coding a program in Python 3.7 that draws flowers where the user clicks on the screen, but I can't figure out how to detect if the user presses the X button while the functions are still being executed, and then stop all processes and close the window.

I looked for solutions and tried using this answer about using winfo_toplevel but I couldn't make that work either.

My code looks like this:

import turtle, random
from sys import exit

window = turtle.Screen()
window.setup(1000,500)

#my functions to draw go here, but aren't included since the question is about closing the program  

def stop():
    turtle.bye()
    root.destroy()
    exit()

window.onclick(chooseFlower)
window.listen()

canvas = window.getcanvas()
root = canvas.winfo_toplevel()
root.protocol("WM_DELETE_WINDOW", stop)
while not root.protocol("WM_DELETE_WINDOW"):
    turtle.mainloop()

I get this bunch of errors:

tkinter.TclError: can't invoke "destroy" command: application has been destroyed

and then

raise Terminator
turtle.Terminator

and then

_tkinter.TclError: invalid command name ".!canvas"

What else can I try?

martineau
  • 119,623
  • 25
  • 170
  • 301
Zubia
  • 11
  • 1
  • 1

1 Answers1

0

Your code is destroying the window before you click on the X button. The while loop condition is wrong. I think your code should run without that. Also, turtle.bye() will close the window for you without any error. you do not require the destroy function to do so. Try changing code as per below. It should work.

       def stop():
           turtle.bye()

and comment out while

          root.protocol("WM_DELETE_WINDOW", stop)
          # while root.protocol("WM_DELETE_WINDOW"):
          turtle.mainloop()
Yugesha Sapte
  • 105
  • 1
  • 1
  • 9
  • Thanks, that still gives me a turtle.Terminator error if I close the program when it's still drawing, how do I make that stop? – Zubia Jan 06 '20 at 01:54