Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python python turtle graphics window not responding

TiffanyWart

New Coder
[CODE lang="python" title="This code works"]import turtle
player=turtle.Turtle()
def space():
print("spacebar pressed")
turtle.onkeypress(space, "space")
turtle.listen()[/CODE]
[CODE lang="python" title="This code doesn't work" highlight="7-8"]import turtle
player=turtle.Turtle()
def space():
print("spacebar pressed")
turtle.onkeypress(space, "space")
turtle.listen()
while True:
a=1[/CODE]
When I have no while loop the code works and everytime i press spacebar it'll print "spacebar pressed"
When I do have a while loop the code doesn't work and the turtle graphics window doesn't respond.
Why doesn't it work when I have the while loop? How can I fix this issue?
 
Hi @TiffanyWart,

Did you try the solution @Krusty the Senile provided?
Yes. Putting the listen command inside the while loop doesn't work. It doesn't seem the turtle module on python doesn't like while loops with events. I found someone having the same problem here and while trying things I found out that if you put something that has to do with the screen the problem is fixed:
[CODE lang="python" title="This code works" highlight="10-11"]import turtle
pen=turtle.Turtle()
def space():
print("spacebar pressed")
turtle.onkeypress(space, "space")
turtle.listen()
pen.hideturtle()
pen.penup()
while True:
pen.goto(-100,100)
pen.goto(100,-100)[/CODE]
Putting a way to exit the loop does work, but only after the loop is finished. Imagine I press the spacebar 8 times while the while loop is going, then when the while loop finishes, it prints "spacebar pressed" 8 times. The same thing happens with a for loop. Well at least I found a fix, but I still don't know why the turtle module acts with way.

Solved
 
Last edited:
Back
Top Bottom