I just discovered the turtle module, and I'm trying to use it. I'd like to run a program that draws a static graphic, and then close the window when the space bar is pressed. This program draws the graphic just fine – but then nothing happens when I press the – and fairly soon the blue wheel is spinning, and the window has become unresponsive in the mind of Windows.
How to do better? How to wait while remaining a "responsive window"?
Python 3.9,
Windows 10
import turtle
from time import sleep
t = turtle.Turtle()
turtle.onkey(turtle.bye, ' ')
t.forward(150)
t.rt(108)
while True:
sleep(0.2)
You're missing a call to the listen() method so your key press won't be heard. Also, don't reinvent the event loop -- neither while True: nor sleep() belong in an event-driven world like turtle:
from turtle import Screen, Turtle
turtle = Turtle()
turtle.forward(150)
turtle.right(108)
screen = Screen()
screen.onkey(screen.bye, ' ')
screen.listen()
screen.mainloop()
Related
I am trying to create a turtle crossing game but every time I run the program neither the screen.listen() gets executed nor the screen.exitonclick()
After running the program on clicking on the turtle window it does not close neither the turtle moves forward
import turtle
from turtle import Screen
from player import Player
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
screen.listen()
screen.onkey(player.go_up(), "Up")
turtle.TurtleScreen._RUNNING = True
game_is_on = True
while game_is_on:
time.sleep(0.1)
screen.update()
screen.exitonclick()
Although I tried adding the ._RUNNING method, yet it does not make any difference
There are a few issues here:
while game_is_on: is an infinite loop since game_is_on is never changed from True to False. Anything after the loop will never run. Avoid using this pattern; the typical way to make a real-time rendering loop in turtle is ontimer.
turtle.TurtleScreen._RUNNING = True messes with an undocumented internal property. Unless you have an absolute need to, you shouldn't touch internal properties in libraries because you may be corrupting the instance's state and the property can disappear after an update. I'm not sure what you're trying to do here, but either figure out a way using the public API or drop this code entirely if it's not really needed (I don't think it is--I've never used it in a turtle program).
Although the code for Player wasn't posted, screen.onkey(player.go_up(), "Up") is likely incorrect. It invokes the go_up() method immediately and sets its return value, probably None, as the onkey handler. You probably meant screen.onkey(player.go_up, "Up") which doesn't call the method immediately, but instead passes it to the handler so it can be called later on by the turtle library, when the key is pressed.
With a little stub for Player, I'd suggest a setup like:
import turtle
class Player:
def __init__(self):
self.turtle = turtle.Turtle()
def go_up(self):
self.turtle.setheading(90)
self.turtle.forward(10)
def tick():
#### the main loop; move/update entities here ####
screen.update()
screen.ontimer(tick, 1000 // 30)
screen = turtle.Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
screen.onkey(player.go_up, "Up")
screen.listen()
tick()
screen.exitonclick()
Now, you don't have any code in tick yet. This is the main update/rendering loop. The player's movement will be jerky because it's directly wired to the keyboard's retrigger mechanism. If this behavior isn't what you want, I suggest reacting to key presses and changing the player's position only inside of tick. See How to bind several key presses together in turtle graphics? for an example of this.
First, I import the turtle module and then creating a screen. After that, I try to create a turtle object, but it is not showed on the screen. Could anyone tell me what the issue is? I have written the following code in PyCharm:
import turtle as t
screen = t.Screen()
screen.title("My Snake Game")
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.exitonclick()
terry = t.Turtle(shape='square')
terry.color('white')
terry.goto(0, 0)
The screen.exitonclick() method does not only set the property that the screen will close after clicking it, it does also wait for this to happen. As this method waits for the screen to close, every code that is after it won't be executed untill the user closes the screen by clicking on it.
This means that the turtle will be created after the screen is closed and thus does not show up as the screen is closed. The solution for this is moving the screen.exitonclick() line to the end of the code.
screen.exitonclick() seems to wait for a mouse click before continuing. As you define your turtle after that, it doesn't come up on the screen. Try putting screen.exitonclick() at the very end of the code
The problem here is that you have the screen.exitonclick() in the middle. That generates another window that apears and desapears after screen.exitonclick() is executed. What you should do is to put screen.exitonclick() at the end.
import turtle as t
screen = t.Screen()
screen.title("My Snake Game")
screen.setup(width=600, height=600)
screen.bgcolor("black")
terry = t.Turtle(shape='square')
terry.color('white')
terry.goto(0, 0)
screen.exitonclick()
This would be the code.
I'm creating a game using the turtle module. I included in my code something like this to smooth out the animation:
screen.tracer(0)
Then I update the screen with:
screen.update()
However, when I run the code, the animation freezes. Does anyone know what's happened here?
well it works correctly!
the screen should always be in freeze mode (because of .tracer(0) method), unless it sees the .update() and then because of this method it refresh it state and then back to the freeze mode.
source: tracer documentation
so basically it should update the screen once but if you want to update the screen constantly, you should put the screen.update() (and your entire code) in a while loop. here is an example:
from turtle import Screen
screen = Screen()
screen.tracer(0)
game_is_on = True
while game_is_on:
screen.update()
# your code
screen.exitonclick()
I've been testing the turtle library for about 3 days now. One recurring 'issue' that I've been getting is the traceback error whenever I exit my application window. The terminal displays rows of details regarding the turtle update function and it ends with:
_tkinter.TclError: can't invoke "update" command: application has been destroyed
Here's my code:
import turtle
wn = turtle.Screen()
wn.title("Game Window")
wn.bgcolor("black")
wn.setup(width=1000, height=650)
wn.tracer(0)
run = True
while run:
wn.update()
I've been trying to wrap my head around the traceback report. I'm assuming it happens because the application continuously updates the window (as you can see in the while run block). So, there is a possibility that, once I exit the window, the application is already processing the wn.update() function, and it returns an error because it did not finish its operation. If that is the case, then what should I do about the update function? If not then, please, explain to me the issue and solution. Thank you!
The problem is your loop:
while run:
wn.update()
This is the wrong way to approach Python turtle programming. I see this loop often in SO questions so there must be a book ("Programming Python Turtle by Bad Example") or tutorial somewhere teaching people the wrong way to approach turtle.
Generally, I'd suggest you avoid tracer() and update() until your program is basically working and you now need to optimize its performance. If you do use tracer(), then you should only call update() when you are finished making changes and you want the user to see the current display. Something like:
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=1000, height=650)
screen.title("Game Window")
screen.tracer(0)
turtle = Turtle()
radius = 1
while radius < 300:
turtle.circle(radius, extent=1)
radius += 0.25
screen.update() # force above to be seen
screen.mainloop()
A key point to note is that our program ends with a mainloop() call which passes control onto Tk(inter)'s event loop. That's the same event loop that receives the window close event and closes down turtle cleanly.
from turtle import *
def PleaseStop():
SomeWord = input("Which word?")
Screen().onkey(PleaseStop,"a")
Screen().listen()
Pressing "a" will make the program ask "Which word?" forever.
No way to stop it besides closing the program. How do I get onkey to call the function only once?
You need to remove the event bindings by calling onkey with None as first parameter:
import turtle
def OnKeyA():
print 'Key "a" was pressed'
turtle.Screen().onkey(None, 'a')
turtle.Screen().onkey(OnKeyA, 'a')
turtle.Screen().listen()
turtle.mainloop()
Doesn't solve the problem. Print is fine either way, input() is
repeating itself forever, even with none.
I believe #Acorn was heading in the right direction with this but the example provided is incomplete. Here's what I feel is a more complete solution:
from turtle import Turtle, Screen, mainloop
def OnKeyA():
screen.onkey(None, 'a')
some_word = raw_input("Which word? ")
turtle.write(some_word, font=('Arial', 18, 'normal'))
screen = Screen()
turtle = Turtle()
screen.onkey(OnKeyA, 'a')
print("Click on turtle window to make it active, then type 'a'")
screen.listen()
mainloop()
Note that this approach is awkward, clicking the turtle graphics window to make it active, hitting 'a', going back to the console window to type your word. If/when you move to Python 3, you can use the turtle function textinput() to prompt for text from the user without having to use input() from the console.