2

I'm designing a simple Python program that uses the Turtle graphics module to draw lines on the screen with the arrow keys.

import turtle

turtle.setup(400,500)                # Determine the window size
wn = turtle.Screen()                 # Get a reference to the window
wn.title("Handling keypresses!")     # Change the window title
wn.bgcolor("lightgreen")             # Set the background color
tess = turtle.Turtle()               # Create our favorite turtle

# The next four functions are our "event handlers".
def h1():
   tess.forward(30)

def h2():
   tess.left(45)

def h3():
   tess.right(45)

def h4():
    wn.bye()                        # Close down the turtle window

# These lines "wire up" keypresses to the handlers we've defined.
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "q")

# Now we need to tell the window to start listening for events,
# If any of the keys that we're monitoring is pressed, its
# handler will be called.
wn.listen()
wn.mainloop()

When I try to execute it, the following error is returned.

Traceback (most recent call last):
  File "C:\Users\Noah Huber-Feely\Desktop\PEN_Programming\Python\etchy_sketch1.py", line 32, in <module>
    wn.mainloop()
AttributeError: '_Screen' object has no attribute 'mainloop'

I'm using Python 2.7 and have had no trouble with Turtle graphics before. It is only now that I have begun working with key input that this problem has occurred.

Searching on the web, I only found articles about different issues and modules than the one I am currently experiencing.

Let me know if you need more information. Thanks!

1 Answer 1

3

It's still turtle.mainloop(), not wn.mainloop().

I suspect the reason for this is since you can make multiple screens, it makes sense to still have the turtle module manage all of the screens instead of trying to potentially make multiple mainloops work together.

Sign up to request clarification or add additional context in comments.

1 Comment

wn.mainloop() is only valid in Python 3. In Python 2, mainloop is a (global module) synonym for TK.mainloop. In Python 3, mainloop is a method of TurtleScreenBase that calls TK.mainloop. When using turtle standalone like this (i.e. not embedded in Tk) there is only ever one screen and no way to make others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.