Search code examples
pythonlinuxpycharm

Why is my turtle module crashing when I try run Turtle.shape("turtle")?


I am trying to code my first OOP turtle object. But When I try to add shape it crashes. My laptop is using Ubuntu 20.04 and running python 3.8. I am using Pycharm. See my code below:

from turtle import Turtle, Screen
timmy = Turtle()
my_screen = Screen()
print(my_screen.canvheight)
my_screen.exitonclick()
timmy.shape("classic")
print(timmy)

CRASHING MESSAGE OUTPUT

    Traceback (most recent call last):
    File "/usr/lib/python3.8/turtle.py", line 2779, in shape
    self._update()
  File "/usr/lib/python3.8/turtle.py", line 2661, in _update
    self._update_data()
  File "/usr/lib/python3.8/turtle.py", line 2647, in _update_data
    self.screen._incrementudc()
  File "/usr/lib/python3.8/turtle.py", line 1293, in _incrementudc
    raise Terminator
turtle.Terminator

Solution

  • Problem is that you run shape() after exitonclick() which waits for click and after click it closes window and stops all turtle and later it can't work with turtles - so it can't run timmy.shape() and this generate your error.

    exitonclick() is not for stoping code between other tasks. It is only to finish program.


    EDIT:

    This work without error

    from turtle import Turtle, Screen
    
    timmy = Turtle()
    
    my_screen = Screen()
    print(my_screen.canvheight)
    
    timmy.shape("classic")   # <--- before `exitonclick`
    print(timmy)
    
    my_screen.exitonclick()
    

    And if you want to run something after click then you have to use .onscreenclick(function) (without exitonclick()) and run code in function()

    from turtle import Turtle, Screen
    
    # --- functions ---
    
    def function(x, y):
        timmy.shape("classic")
        print('timmy:', timmy)
    
        # exit program
        my_screen.bye()
    
    # --- main ---
        
    timmy = Turtle()
    
    my_screen = Screen()
    print(my_screen.canvheight)
    
    my_screen.onscreenclick(function)
    
    # keep running
    my_screen.mainloop()