0

I am trying to speed up my turtle whenever I press the space bar.

I have a code that looks something like this

import turtle


instructions = [20,30,40,20,50,5,20,30,40,200,5]
speed = 0

wn = turtle.Screen()
drone = turtle.Turtle()

speed = 1
def sped():
    global speed
    speed += 1


for instruction in instructions:
    drone.forward(instruction)
    drone.left(45)
    wn.onkey(sped, "space")
    drone.speed(speed)
    print(speed)

However, the speed is always 1. I've tried scouring the internet but nothing comes up. How do I fix this?

wel
  • 234
  • 2
  • 11
  • 1
    `onkey` should be added one time, up front, and `wn.listen()` needs to be called to activate it. – ggorlen Jan 13 '23 at 06:44
  • Does this answer your question? [Turtle.onkeypress isn't firing](https://stackoverflow.com/questions/45545469/turtle-onkeypress-isnt-firing) – ggorlen Jan 13 '23 at 06:47
  • @ggorlen it does answer my question, however, i will like to keep this up because 1. the questions asked are not the same and in future, some people may come across the same problem as me, and 2. your short comment is more precise to my problem than having to filter out the large chunk of code in the link given. – wel Jan 13 '23 at 07:28
  • it's basically the same problem. You may think you're trying to increase speed, but if you added a `print()` into your `sped()` function, you'd see it's never called regardless of what you eventually want it to do, so they reduce to the same problem. Answers in the other thread adequately and thoroughly address the underlying issue, so it's a waste of work and less useful to future visitors to re-add all of that information here. Already, we have 2 poor answer attempts in this thread. Marking it as a dupe doesn't preclude people finding the solution via this post in any way. – ggorlen Jan 13 '23 at 13:56
  • @ggorlen I'm having another problem : currently, when I press and hold my space bar, it doesn't register for every single second that I press (and hold) the space bar. Is this normal? I can share the code with you. – wel Jan 14 '23 at 05:24
  • Feel free to ask a new question if you have another problem. – ggorlen Jan 14 '23 at 05:25

1 Answers1

0

just needed to add wn.listen() at the end

import turtle 
instructions = [20,30,40,20,50,5,20,30,40,200,5]
speed = 0

wn = turtle.Screen()
drone = turtle.Turtle()

speed = 1
def sped():
    global speed
    speed += 1


for instruction in instructions:
    drone.forward(instruction)
    drone.left(45)
    wn.onkeypress(sped, "space")
    drone.speed(speed)
    print(speed)
    wn.listen()
PerangO
  • 16