Turtle graphic screen not responding - python

So I'm trying to draw some text on the screen and everytime I press the turtle graphic screen it becomes unresponsive. When I tried fixing it by adding the mainloop it won't continue with rest of the code. I saw somewhere I should add
done()
at the end of the block but python says it doesn't exist and I tried putting turtle.done() but nothing.
Here is the code:
def draw_robot(choice_robot,robots):
stats = robots[choice_robot]
style = 'Arial',14,'bold'
t.setheading(-90)
t.write('Name: '+choice_robot,font=style,align = 'center')
t.forward(25)
t.write('Battery: '+stats[0],font=style,align = 'center')
t.forward(25)
t.write('Intelligence: '+stats[1],font=style,align = 'center')
turtle.mainloop()
how can i fix this?

The turtle.mainloop() should not appear in a subroutine. Generally, it should be the last thing executed on a page of turtle code. I.e., either literally the last statement or the last thing a main() routine does. It turns control over to tkinter's event handler where upon all interaction with turtle is through events (key strokes, mouse motion, etc.)
Below is roughly how I would expect a proper turtle program to be laid out:
from turtle import Turtle, Screen # force Object-oriented interface
STYLE = ('Arial', 14, 'bold')
def draw_robot(choice_robot, robots):
stats = robots[choice_robot]
t.setheading(-90)
t.write('Name: ' + choice_robot, font=STYLE, align='center')
t.forward(25)
t.write('Battery: ' + stats[0], font=STYLE, align='center')
t.forward(25)
t.write('Intelligence: ' + stats[1], font=STYLE, align='center')
screen = Screen()
t = Turtle()
my_choice_robot = None # whatever ...
my_robots = None # whatever ...
draw_robot(my_choice_robot, my_robots)
screen.mainloop()

Related

No description errors and code not working on different computers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
I'm very new to Python, I'm using Python 3.10 and have been practicing a lot the past few weeks.
Overview:
I'm creating Hangman using Turtle, Pynput, Tkinter, and Time modules.
Issues:
On my work computer, the file runs fine up until trying to implement a second 'listen' bind to add the option to start the game - it works using the escape key to exit the game window.
The issue is the error 'not in main loop', I'm pretty new to this and I found that I need to have main loop on the end on my file, this fixed the first issue where I was trying to bind escape to the quit function.
Fast forward to the main issue - on my personal laptop the code does not want to work at all, the window opens and the welcome greeting shows up, but then the program crashes and throws this error "Exception has occurred: Terminator exception: no description" relating directly to line 33 which is "game_menu = turtle.Turtle()" I feel like it will throw this for other things as well.
This was not happening on my work computer, and it all loaded properly until I was trying to fix the second key bind issue to add a bind to start the game (where I would create the meat of game somehow, with the letters and words etc).
I have tried moving the code around to try and put the greeting and menu into functions, I've tried just moving the code to different places to see if it would work in the While True loop.
The while True is pretty confusing and I might be missing something that needs to be in it.
In any case, this is the code below, if anyone can please tell me what I';m doing wrong or why it won't work on my laptop but will on my other computer that would be great. (Using Visual Studio Code).
Thanks so much.
START CODE:
# Modules
from tkinter import *
import turtle
from turtle import *
import time
from pynput import keyboard
# Game Screen
width = 800
height = 800
game_window = turtle.Screen()
game_window.setup(width, height)
game_window.bgcolor('#dfe4db')
game_window.title("Hangman by Name")
# Game Greeting Text
welcome_greeting = turtle.Turtle()
welcome_greeting.color('black')
welcome_greeting.hideturtle()
welcome_greeting.penup()
welcome_greeting.setpos(-70, 0)
welcome_greeting.pendown()
welcome_greeting.write('Welcome to Hangman', move=True,
align='left', font=('Arial', 20, 'normal'))
time.sleep(1)
turtle.bye()
# Game Menu
game_menu = turtle.Turtle()
game_menu.color('black')
game_menu.shape('square')
game_menu.hideturtle()
game_menu.penup()
game_menu.setpos(-70, 0)
game_menu.write("Press 'Up Arrow' to start game\nPress 'ESC' to quit",
align='center', font=('Arial', 20, 'bold'))
if keyboard.Key.esc:
turtle.bye()
# Hangman Top Panel Stockhold
top_panel = turtle.Turtle()
turtle.tracer()
top_panel.speed(0)
top_panel.hideturtle()
top_panel.color('#4f371b')
top_panel.shape('square')
top_panel.penup()
top_panel.showturtle()
top_panel.setpos(-170, 260)
top_panel.shapesize(stretch_len=20)
# Hangman Left Side Panel Stockhold
left_panel = turtle.Turtle()
turtle.tracer()
left_panel.speed(0)
left_panel.hideturtle()
left_panel.color('#4f371b')
left_panel.shape('square')
left_panel.penup()
left_panel.setpos(-380, 20)
left_panel.left(90)
left_panel.showturtle()
left_panel.shapesize(stretch_len=25)
# Hangman Rope
rope = turtle.Turtle()
turtle.tracer()
rope.speed(0)
rope.hideturtle()
rope.color('#4f371b')
rope.shape('square')
rope.right(90)
rope.shapesize(stretch_len=5, stretch_wid=.5)
rope.penup()
rope.setpos(-160, 199)
rope.showturtle()
# Hangman Base Stockhold
base_panel_ground = turtle.Turtle()
turtle.tracer()
base_panel_ground.speed(0)
base_panel_ground.hideturtle()
base_panel_ground.color('#1c5721')
base_panel_ground.shape('square')
base_panel_ground.shapesize(stretch_len=600, stretch_wid=10)
base_panel_ground.penup()
base_panel_ground.setpos(390, -290)
base_panel_ground.showturtle()
# Hangman Body Parts:
# Head
def hangman_head():
hangman_head = turtle.Turtle()
hangman_head.speed(0)
hangman_head.color('#ff9966')
hangman_head.shape('circle')
hangman_head.shapesize(2.5, 2.5, 2.5)
hangman_head.penup()
hangman_head.setpos(-160, 155)
hangman_head.pendown()
# Body
def hangman_body():
hangman_body = turtle.Turtle()
hangman_body.speed(0)
hangman_body.color('#6600ff')
hangman_body.shape('square')
hangman_body.left(90)
hangman_body.shapesize(stretch_len=5)
hangman_body.shapesize(1.5, 3.5, 4.5)
hangman_body.penup()
hangman_body.setpos(-160, 90)
hangman_body.pendown()
# Left Arm
def hangman_left_arm():
hangman_left_arm = turtle.Turtle()
hangman_left_arm.speed(0)
hangman_left_arm.color('#ff9966')
hangman_left_arm.shape('square')
hangman_left_arm.shapesize(1.5, .5, 1.5)
hangman_left_arm.shapesize(stretch_wid=.5, stretch_len=2.5)
hangman_left_arm.left(40)
hangman_left_arm.penup()
hangman_left_arm.setpos(-189, 104)
# Right Arm
def hangman_right_arm():
hangman_right_arm = turtle.Turtle()
hangman_right_arm.speed(0)
hangman_right_arm.color('#ff9966')
hangman_right_arm.shape('square')
hangman_right_arm.shapesize(1.5, .5, 1.5)
hangman_right_arm.shapesize(stretch_wid=.5, stretch_len=2.5)
hangman_right_arm.left(140)
hangman_right_arm.penup()
hangman_right_arm.setpos(-129, 102)
# Left Leg
def hangman_left_leg():
hangman_left_leg = turtle.Turtle()
hangman_left_leg.speed(0)
hangman_left_leg.color('#ff9966')
hangman_left_leg.shape('square')
hangman_left_leg.shapesize(stretch_len=1.7, stretch_wid=.7)
hangman_left_leg.right(90)
hangman_left_leg.penup()
hangman_left_leg.setpos(-170, 35.6)
# Right Leg
def hangman_right_leg():
hangman_right_leg = turtle.Turtle()
hangman_right_leg.speed(0)
hangman_right_leg.color('#ff9966')
hangman_right_leg.shape('square')
hangman_right_leg.shapesize(stretch_len=1.7, stretch_wid=.7)
hangman_right_leg.right(90)
hangman_right_leg.penup()
hangman_right_leg.setpos(-150, 35.6)
# Clear Hangman
# Clear Head
def clear_head():
hangman_head.clear()
# Clear Body
def clear_hangman_body():
hangman_body.clear()
# Clear Left Arm
def clear_left_arm():
hangman_left_arm.clear()
# Clear Right Arm
def clear_right_arm():
hangman_right_arm.clear()
# Clear Left Leg
def clear_left_leg():
hangman_left_arm.clear()
# Clear Right Leg
def clear_right_leg():
hangman_right_leg.clear()
# Lose Game
def lose_game():
you_lose = turtle.Turtle()
you_lose.color('black')
you_lose.hideturtle()
you_lose.penup()
you_lose.setpos(-70, 340)
you_lose.write(
'Better Luck Next Time!'
'(No Hangmen were harmed in the making of this game)',
align='center', font=('Arial', 20, 'bold'))
# Clear Game
def game_clear():
clear_hangman_body()
clear_head()
clear_left_arm()
clear_right_arm()
clear_left_leg()
clear_right_leg()
# Win Game
def game_win():
you_win = turtle.Turtle()
you_win.color('black')
you_win.hideturtle()
you_win.penup()
you_win.setpos(-70, 340)
you_win.write(
'Congratulations! (No Hangmen were harmed in the making of this game)',
align='center', font=('Arial', 20, 'bold'))
# Storing the Words and Letters:
# Stored Letters For Display
word_display = []
# Printing the Word to be Guessed
def print_word():
pass
# Categories:
# Topics
topics = {1: "Animals", 2: "Music",
3: "Elements", 4: "Mythology", 5: "Countries"}
# Topic Words
dataset = {
"Animals": [
"FELINE", "CANINE", "SNAKE", "TORTOISE", "TURTLE", "OWL",
"SHARK", "FISH", "ANT EATER", "MOLLUSK", "SEAGULL", "ELEPHANT",
"ECHIDNA", "KOOKOOBURRA", "KANGAROO", "PYTHON"],
"Music": [
"CLASSICAL", "ROCK N ROLL", "JAZZ", "BLUES", "COUNTRY",
"ELECTRONIC", "CONTEMPORARY", "HIP HOP", "RAP", "POP",
"METAL", "PUNK ROCK", "ALTERNATIVE"],
"Elements": [
"HYDROGEN", "HELIUM", "LITHIUM", "BORON", "CARBON", "OXYGEN",
"NITROGEN", "MAGNESIUM", "ARGON", "SULFUR", "CHLORINE", "CALCIUM",
"IRON", "COPPER", "ZINC", "BROMINE", "INDIUM", "IODINE", "TERBIUM",
"IRIDIUM", "MERCURY", "ASTATINE", "URANIUM"],
"Mythology": [
"ODIN", "THOR", "LOKI", "HEL", "FORSETI", "YMIR", "FREYR",
"FREYJA", "FENRIR", "SKOLL", "ANGRBODA", "SKADI", "SEKHMET",
"ISIS", "HORUS", "SETH", "NEPHTHYS", "OSIRIS", "THOTH", "ANUBIS",
"BASTET", "ZEUS", "APOLLO", "ARTERMIS", "SELENE", "HERA", "APHRODITE",
"HAPHAESTUS", "ARES", "POSEIDON", "HERMES", "HADES"],
"Countries": [
"AUSTRALIA", "AMERICA", "MADAGASCAR", "EGYPT", "AFRICA", "CANADA",
"RUSSIA", "UKRAINE", "SINGAPORE", "SOUTH KOREA", "INDIA",
"NEW ZEALAND", "BRAZIL", "COLUMBIA", "THAILAND", "CHINA", "JAPAN",
"GERMANY", "HOLLAND", "ENGLAND", "SCOTLAND", "IRELAND", "GREECE"]}
# Main Game
while True:
game_window.tracer(0)
game_menu()
def quit_game():
game_window.bye()
def on_press(key):
if key == keyboard.Key.esc:
return False
else:
quit_game()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
quit_game()
game_window.mainloop()
I'm surprised this works at all. You exit turtle (turtle.bye()) shortly after starting but continue to call turtle methods. You import tkinter but use turtle in a standalone fashion instead of an embedded fashion necessary under tkinter. You import turtle twice, two different ways, which is always a warning sign for disaster. You invoke the (effectively) no-op turtle.tracer() multiple times. You have variables and functions with the same name.
Below is my rework of your code. I don't believe you need tkinter nor pynput, as everything you need is already in turtle. My advice is you focus on getting your basic game working first and not start out making text banners and the like:
from turtle import Screen, Turtle
from time import sleep
WIDTH, HEIGHT = 800, 800
BOLD_FONT = ('Arial', 20, 'bold')
NORMAL_FONT = ('Arial', 20, 'normal')
# Hangman Body Parts:
def create_head():
head = Turtle()
head.hideturtle()
head.speed('fastest')
head.color('#ff9966')
head.shape('circle')
head.shapesize(2.5)
head.penup()
head.setpos(-160, 155)
head.showturtle()
return head
def create_body():
body = Turtle()
body.hideturtle()
body.speed('fastest')
body.color('#6600ff')
body.shape('square')
body.left(90)
body.shapesize(1.5, 3.5, 4.5)
body.penup()
body.setpos(-160, 90)
body.showturtle()
return body
def create_left_arm():
left_arm = Turtle()
left_arm.hideturtle()
left_arm.speed('fastest')
left_arm.color('#ff9966')
left_arm.shape('square')
left_arm.shapesize(stretch_wid=0.5, stretch_len=2.5)
left_arm.left(40)
left_arm.penup()
left_arm.setpos(-189, 104)
left_arm.showturtle()
return left_arm
def create_right_arm():
right_arm = Turtle()
right_arm.hideturtle()
right_arm.speed('fastest')
right_arm.color('#ff9966')
right_arm.shape('square')
right_arm.shapesize(stretch_wid=0.5, stretch_len=2.5)
right_arm.left(140)
right_arm.penup()
right_arm.setpos(-129, 102)
right_arm.showturtle()
return right_arm
def create_left_leg():
left_leg = Turtle()
left_leg.hideturtle()
left_leg.speed('fastest')
left_leg.color('#ff9966')
left_leg.shape('square')
left_leg.shapesize(stretch_len=0.7, stretch_wid=1.7)
left_leg.penup()
left_leg.setpos(-170, 35.6)
left_leg.showturtle()
return left_leg
def create_right_leg():
right_leg = Turtle()
right_leg.hideturtle()
right_leg.speed(0)
right_leg.color('#ff9966')
right_leg.shape('square')
right_leg.shapesize(stretch_len=0.7, stretch_wid=1.7)
right_leg.penup()
right_leg.setpos(-150, 35.6)
right_leg.showturtle()
return right_leg
# Clear Hangman
def game_clear():
hangman_body.clear()
hangman_head.clear()
hangman_left_arm.clear()
hangman_right_arm.clear()
hangman_left_leg.clear()
hangman_right_leg.clear()
def game_lose():
marker.write('Better Luck Next Time!', align='center', font=BOLD_FONT)
def game_win():
marker.write('Congratulations!', align='center', font=BOLD_FONT)
# Game Screen
screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('#dfe4db')
screen.title("Hangman by Name")
screen.onkey(screen.bye, 'Escape')
screen.listen()
# Game Greeting Text
marker = Turtle()
marker.hideturtle()
marker.penup()
marker.sety(40)
marker.write('Welcome to Hangman', align='center', font=BOLD_FONT)
marker.home()
marker.write("Press 'ESC' to quit at any time", align='center', font=NORMAL_FONT)
panel = Turtle()
panel.hideturtle()
panel.speed('fastest')
panel.shape('square')
panel.penup()
# Hangman Top Panel Stockhold
top_panel = panel.clone()
top_panel.color('#4f371b')
top_panel.setpos(-170, 260)
top_panel.shapesize(stretch_len=20)
top_panel.showturtle()
# Hangman Left Side Panel Stockhold
left_panel = panel.clone()
left_panel.color('#4f371b')
left_panel.setpos(-380, 20)
left_panel.shapesize(stretch_len=1, stretch_wid=25)
left_panel.showturtle()
# Hangman Rope
rope = panel.clone()
rope.color('#4f371b')
rope.setpos(-160, 199)
rope.shapesize(stretch_len=0.5, stretch_wid=5)
rope.showturtle()
# Hangman Base Stockhold
base_panel_ground = panel.clone()
base_panel_ground.color('#1c5721')
base_panel_ground.setpos(390, -290)
base_panel_ground.shapesize(stretch_len=600, stretch_wid=10)
base_panel_ground.showturtle()
# Storing the Words and Letters:
hangman_head = create_head()
hangman_body = create_body()
hangman_left_arm = create_left_arm()
hangman_right_arm = create_right_arm()
hangman_left_leg = create_left_leg()
hangman_right_leg = create_right_leg()
sleep(1)
marker.clear()
screen.mainloop()

How to draw square in Turtle module without filling color?

I am trying to draw a square in turtle without any thing filled in it. I would manually draw it with a loop, but I am trying to write a program where if the square is touched, something would happen. If I drew it with a loop, even if I touch the border, it would not work, because the actual turtle isn't there.
We can do this by dedicating one turtle as the button. We need to change its shape, size and fill color and assign it a button event handler:
from turtle import Screen, Turtle
def thanks(x, y):
marker.write("Thank you!", align='center', font=('Arial', 24, 'bold'))
marker = Turtle()
marker.hideturtle()
marker.penup()
marker.sety(-200)
button = Turtle()
button.shape('square')
button.fillcolor('white')
button.shapesize(3)
button.onclick(thanks)
screen = Screen()
screen.mainloop()
Click on the square in the middle of the screen and it will thank you for doing so.
I am trying to draw a square in turtle without any thing filled in it.
The above solution does use a filled turtle, it just happens to be white fill. We can't draw within the square that is this button. If that's the need, then we can draw the square with a loop, but move our onclick() from the turtle to the screen. We'll need to make the onclick() itself determine if it's in the right place:
from turtle import Screen, Turtle
BUTTON_POSITION = (100, 100)
BUTTON_SIZE = 60
def thanks(x, y):
bx, by = BUTTON_POSITION
if bx < x < bx + BUTTON_SIZE and by < y < by + BUTTON_SIZE:
turtle.write("Thank you!", align='center', font=('Arial', 24, 'bold'))
turtle = Turtle()
turtle.hideturtle()
# draw the button
turtle.penup()
turtle.goto(BUTTON_POSITION)
turtle.pendown()
for _ in range(4):
turtle.forward(BUTTON_SIZE)
turtle.left(90)
# decorate our button a bit
turtle.penup()
turtle.forward(BUTTON_SIZE/2)
turtle.left(90)
turtle.forward(BUTTON_SIZE/2)
turtle.dot()
# position turtle for writing later
turtle.goto(0, -200)
screen = Screen()
screen.onclick(thanks)
screen.mainloop()

Python turtle not moving on arrow press

I am trying to make my turtle (main_ship) move across the bottom of my screen according to when the user presses the left and right arrow keys but the turtle is not moving. I have used the same code before when making Pong so I'm not sure why it's not working.
import turtle
wn = turtle.Screen()
wn.title("Game")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
main_ship = turtle.Turtle()
main_ship.speed(0)
main_ship.shape("turtle")
main_ship.color("green")
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.penup()
main_ship.goto(0, -290)
main_ship.left(90)
def main_ship_right():
x = main_ship.xcor()
x += 20
main_ship.setx(x)
def main_ship_left():
x = main_ship.xcor()
x -= 20
main_ship.setx(x)
while True:
wn.update()
wn.mainloop()
wn.listen()
wn.onkeypress(main_ship_right, "Right")
wn.onkeypress(main_ship_left, "Left")
When I press the arrow keys, nothing happens but the code still runs and there are no error messages.
You have to assign keys before mainloop() which runs all time till you close window.
You don't need while True because mainloop() already runs internal loop.
You may have to remove wm.tracer(0) or you will have to run wn.update() to refresh elements in window.
import turtle
# --- functions ---
def main_ship_right():
x = main_ship.xcor()
x += 20
main_ship.setx(x)
wn.update()
def main_ship_left():
x = main_ship.xcor()
x -= 20
main_ship.setx(x)
wn.update()
# --- main ---
wn = turtle.Screen()
wn.title("Game")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
main_ship = turtle.Turtle()
main_ship.speed(0)
main_ship.shape("turtle")
main_ship.color("green")
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.penup()
main_ship.goto(0, -290)
main_ship.left(90)
wn.update()
wn.listen()
wn.onkeypress(main_ship_right, "Right")
wn.onkeypress(main_ship_left, "Left")
wn.mainloop()
For this style of motion, there's another way to implement it. The idea is to leave the cursor moving in it's original orientation, but use settiltangle() to make it look like it's facing upward.
This lets us use forward(20) and backward(20) to move our cursor, and not have to write:
x = main_ship.xcor()
x += 20
main_ship.setx(x)
Works great for Space Invader style games, where the player faces upwards but moves sideways:
from turtle import Screen, Turtle
from functools import partial
screen = Screen()
screen.title("Game")
screen.bgcolor('black')
screen.setup(width=800, height=600)
main_ship = Turtle('turtle')
main_ship.speed('fastest')
main_ship.color('green')
main_ship.shapesize(stretch_wid=2, stretch_len=4)
main_ship.settiltangle(90)
main_ship.penup()
main_ship.sety(-290)
screen.onkeypress(partial(main_ship.forward, 20), 'Right')
screen.onkeypress(partial(main_ship.backward, 20), 'Left')
screen.listen()
screen.mainloop()
Only works in the turtle library that comes with Python -- online Python development sites usually provide limited turtle implementations that don't include methods like settiltangle().

making an endpoint in turtle graphics

I'm making a maze with turtle graphics for a class project and I have one more main thing to complete before I'm finished...
I've created a second "turtle" to make a box at the endpoint. So the objective is to finish the maze and get the turtle in the box. But I am unsure how to make the box an actual endpoint and have a message pop up.
Here is my code:
from turtle import Turtle, Screen
screen = Screen()
screen.setup(650, 850)
screen.title("Turtle Keys")
screen.bgpic('scooby_doo_maze.gif')
move = Turtle(shape="triangle")
move.penup()
move.setx(-150)
move.sety(200)
move.pendown()
move.pensize(5)
box = Turtle(shape="square")
box.hideturtle()
box.speed(0)
box.penup()
box.setx(150)
box.sety(-190)
box.pendown()
box.right(90)
box.forward(100)
box.right(90)
box.forward(100)
box.right(90)
box.forward(100)
box.right(90)
box.forward(100)
def keyUp():
move.forward(12)
def keyLeft():
move.left(90)
def keyRight():
move.right(90)
def keyDown():
move.backward(12)
def keyReset():
move.reset()
move.penup()
move.setx(-150)
move.sety(200)
move.pendown()
move.pensize(5)
screen.onkey(keyUp, "Up")
screen.onkey(keyLeft, "Left")
screen.onkey(keyRight, "Right")
screen.onkey(keyDown, "Down")
screen.onkey(keyReset, "r")
screen.listen()
screen.exitonclick()
We just need to add few features. First, instead of drawing the end point with turtle box, we make turtle box the endpoint by expanding the turtle itself via box.shapesize(). This way, we can use move.distance(box) to determine if move is near the center of box.
Second, we need a function called by all the movement functions to test if above distance is close enough and then invoke the following:
Third, we introduce screen.textinput() to let the play know they've succeeded and offer then the option to play again, or quit. I've reworked your code below to introduce these additions and tweak it a bit for style:
from turtle import Turtle, Screen
screen = Screen()
screen.setup(650, 850)
screen.title("Turtle Keys")
screen.bgpic('scooby_doo_maze.gif')
def insideBox():
if move.distance(box) < 60:
play_again = screen.textinput("Success!", "Play again?")
if play_again and play_again.lower().startswith('y'):
keyReset()
else:
screen.bye()
def keyUp():
move.forward(12)
insideBox()
def keyLeft():
move.left(90)
def keyRight():
move.right(90)
def keyDown():
move.backward(12)
insideBox()
def keyReset():
move.reset()
move.penup()
move.goto(-150, 200)
move.pendown()
move.pensize(5)
screen.listen() # it's here because screen.textinput() unsets it
screen.onkey(keyUp, "Up")
screen.onkey(keyLeft, "Left")
screen.onkey(keyRight, "Right")
screen.onkey(keyDown, "Down")
screen.onkey(keyReset, "r")
move = Turtle(shape="triangle")
keyReset()
box = Turtle(shape="square")
box.color("black", "white")
box.shapesize(5, 5, 5)
box.penup()
box.goto(150, -190)
screen.mainloop()
This is a situation where I would avoid screen.exitonclick() as you need to click the window to get it to listen and easily end up closing it! Using screen.mainloop() should be sufficient and let the user close the window by not choosing to play again or using the window controls.

Python - Keyboard Multiple Turtle Objects

I would like to create a program in which a Turtle object responds to key presses. I can do this, but I can't seem to understand how to move a second Turtle object, which is controlled by the computer, while the first one is moving. Any help would be appreciated.
Here is my code:
from turtle import *
from Tkinter import Tk
root = Tk()
root.withdraw()
turtle = Turtle()
def h1():turtle.forward(10)
def h2():turtle.left(45)
def h3():turtle.right(45)
def h4():turtle.back(10)
def h5(root=root):root.quit()
onkey(h1,"Up")
onkey(h2,"Left")
onkey(h3,"Right")
onkey(h4,"Down")
onkey(h5,"q")
listen()
root.mainloop()
Insert a second turtle before listen() that moves with keys w,a,s,d:
turtle2 = Turtle()
def h11():turtle2.forward(10)
def h21():turtle2.left(45)
def h31():turtle2.right(45)
def h41():turtle2.back(10)
onkey(h11,"w")
onkey(h21,"a")
onkey(h31,"d")
onkey(h41,"s")
I can't seem to understand how to move a second Turtle object, which
is controlled by the computer, while the first one is moving.
Below is some minimal code that does as you describe. Green turtle Pokey is computer controlled while red turtle Hokey is user controlled (click on the window first so your keystrokes are heard):
from turtle import Turtle, Screen
def move_pokey():
pokey.forward(10)
x, y = pokey.position()
if not (-width/2 < x < width/2 and -height/2 < y < height/2):
pokey.undo()
pokey.left(90)
screen.ontimer(move_pokey, 100)
hokey = Turtle(shape="turtle")
hokey.color("red")
hokey.penup()
pokey = Turtle(shape="turtle")
pokey.setheading(30)
pokey.color("green")
pokey.penup()
screen = Screen()
width = screen.window_width()
height = screen.window_height()
screen.onkey(lambda: hokey.forward(10), "Up")
screen.onkey(lambda: hokey.left(45), "Left")
screen.onkey(lambda: hokey.right(45), "Right")
screen.onkey(lambda: hokey.back(10), "Down")
screen.onkey(screen.bye, "q")
screen.listen()
screen.ontimer(move_pokey, 100)
screen.mainloop()
This is not finished code (shutdown of the timer event should be cleaner, Hokey's handlers should lock out additional events while running, etc.) but should give you a basic idea of how to go about it.

Categories