python turtle screen onclick code example

Example 1: python turtle movement

import turtle

wn = turtle.Screen()
wn.setup(width=700,height=400)
wn.title("Python Turtle Movement")

def playerUp():
  player.sety(player.ycor()+10)
def playerDown():
  player.sety(player.ycor()-10)
def playerRight():
  player.setx(player.xcor()+10)
def playerLeft():
  player.setx(player.xcor()-10)

player = turtle.Turtle()
player.speed(0) #this will make your player created instantly
player.shape("square") #set player shape
player.color("red") #set player color
player.penup() #prevent drawing lines
player.goto(0,0) #set player location

wn.onkeypress(playerUp, "w") #function, key
wn.onkeypress(playerDown, "s")
wn.onkeypress(playerRight, "d")
wn.onkeypress(playerLeft, "a")

#update the window
while True:
  wn.update()

Example 2: screen.onkey python

from turtle import Turtle, Screen

screen = Screen()
screen.setup(1200, 500)

# Ground

ground = Turtle()
ground.speed('fastest')

ground.penup()
ground.goto(-1000, -200)
ground.pendown()
ground.forward(2000)

# Player

player = Turtle()
player.speed('fastest')

PlayerX = -600

def moveX():
    global PlayerX

    screen.onkeypress(None, "w")  # disable handler in handler
    player.clear()
    player.penup()
    player.goto(PlayerX, -99)
    player.pendown()
    player.color("Slate Gray")
    player.begin_fill()
    player.circle(-50)
    player.end_fill()

    PlayerX -= 1

    screen.onkeypress(moveX, "w")  # reenable handler

screen.listen()

moveX()

screen.mainloop()  # change import & use turtle.mainloop() if Python 2