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.
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.
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.
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()
I am trying to get the turtle to stop moving forward when I press the escape key. When I press escape, nothing happens! Can anyone tell me why? A solution would be greatly appreciated.
import turtle
screen = turtle.Screen()
running = True
def stop():
running = False
print(running)
while running:
turtle.forward(1)
screen.onkey(stop, "Esc")
screen.listen()
I see several problems with your code. The primary one is a missing global statement in stop(). Secondary ones include: mixing the turtle function and object APIs; using key name 'Esc' instead of 'Escape'; putting onkey() and listen() in a loop; and potentially blocking events with your while loop.
I believe this code should do what you want:
from turtle import Screen, Turtle
running = True
def stop():
global running
running = False
def run():
if running:
turtle.forward(1)
screen.ontimer(run)
screen = Screen()
screen.onkey(stop, 'Escape')
screen.listen()
turtle = Turtle()
run()
screen.mainloop()
I'm a beginner with python and turtle. I want to make a dialogue box that asks a yes or no question. While I can get the box to pop up, how would I code it so that a "no" would close the turtle program and "yes" would keep it up? The part below the screen.textinput is wrong but I had it before for the terminal, and I imported turtle above.
screen = turtle.getscreen()
screen.textinput("Welcome to Bowling!", "Are you readt to bowl?!")
if start.lower() == 'yes':
print("Start!")
else:
print("Goodbye!")
turtle.clear
turtle.bye()
This should get you started:
import turtle
screen = turtle.Screen()
answer = screen.textinput("Welcome to Bowling!", "Are you ready to bowl?")
if answer is None or answer.lower().startswith('n'):
print("Goodbye!")
screen.clear()
screen.bye()
else:
print("Start!")
The key thing to remember is that textinput() returns the string the user typed or None if the user hits Cancel.
This is an alternative to cdlane's solution:
import turtle
screen = turtle.Screen()
answer = turtle.simpledialog.askstring("Welcome to Bowling!", "Are you ready to bowl?")
if answer is None or answer.lower().startswith('n'):
print("Goodbye!")
screen.clear()
screen.bye()
else:
print("Start!")
Note: I have not tested this code yet, I just tweaked cdlane's code
There are other options to the simpledialog function.
There are the askinteger and askfloat for integers and floats respectively. I haven't fully understood these as I just found the function while exploring around with the code prediction of VSCode