简体   繁体   中英

Why Won't My shape Show Up in the Turtle Module

I am trying to create a Pong game, but when I create the paddle, it won't show up. How can I fix it? Here's my code:

import turtle

wm = turtle.Screen()
wm.title("Pong by Zachary Bye")
wm.bgcolor("black")
wm.setup(width=800, height=600)
wm.tracer(0)


#Paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize
paddle_a.penup()
paddle_a.goto(-350,0)

Two problems:

  1. Some settings are initialized and the pen is lifted up but the paddle turtle never draws anything. So there's nothing to see. Try calling a drawing function like .stamp() to print something.

    Also, as a general note, make sure your turtle's location is within the window bounds when you do draw with it, although x at -350 should be fine here.

  2. The main turtle loop is never run. This builds the window and blocks the script from exiting until the window is closed. I usually use turtle.exitonclick() but something like turtle.mainloop() also works. This belongs at the end of the main code.

import turtle

wm = turtle.Screen()
wm.title("Pong by Zachary Bye")
wm.bgcolor("black")
wm.setup(width=800, height=600)
wm.tracer(0)


#Paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize # this line does nothing
paddle_a.penup()
paddle_a.goto(-350,0)
paddle_a.stamp() # draw something
turtle.exitonclick() # run the main turtle loop

when I create the paddle, it won't show up.

The reason is you invoked tracer(0) which says, "don't draw anything until I explicitly call update() . And then you didn't call update() : This is how I would write your code fragment:

from turtle import Screen, Turtle

screen = Screen()
screen.title("Pong by Zachary Bye")
screen.setup(width=800, height=600)
screen.bgcolor('black')
screen.tracer(0)

# Paddle a
paddle_a = Turtle()
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.shapesize(5, 1)
paddle_a.penup()
paddle_a.setx(-350)

screen.update()
screen.mainloop()

My general rule is to avoid tracer() and update() until your code is basically working and you want to optimize the graphics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM