简体   繁体   中英

Switch in Python Turtle Module

I'm trying to make a simple switch that changes a variable (in this case switchvalue) when I hit a key. My approach doesn't seem to be working, the key detection is working as far as I can tell.

import turtle
from turtle import Turtle, Screen

screen = Screen()

jack = Turtle("turtle")
jack.color("red", "green")
jack.pensize(10)
jack.speed(0)
switchvalue = 1


def switch():
    global switchvalue
    if switchvalue == 1:
        switchvalue = 0
    if switchvalue == 0:
        switchvalue = 1




turtle.listen()

turtle.onkey(switch,"s")

screen.mainloop()

if switchvalue == 0:
    jack.forward(100)

You got your logic wrong at the function switch() . See what happens in the beggining when switchvalue is 1

def switch():
    global switchvalue
    if switchvalue == 1: # True
        switchvalue = 0 # change it to 0
    if switchvalue == 0: # Whoops, True again, because you switched it to 0 before
        switchvalue = 1

As you can see you are changing switchvalue to 0 then checking if it is 0 and then it gets changed back to 1 , in other words both if statements are executed. You should instead use elif or else so that if one succeds the " if loop" (metaphorically speaking) will break aka the other if s will not be checked.

def switch():
    global switchvalue
    # IF one if succeds all the others will not be accounted
    if switchvalue == 1:
        switchvalue = 0
    elif switchvalue == 0:
        switchvalue = 1

Even if you fix the elif issue that @Countour-Integral points out, this code isn't going to work. Code after the mainloop() call isn't executed until after turtle shuts down, at which time forward() is meaningless:

screen.mainloop()

if switchvalue == 0:
    jack.forward(100)

You're mixing the functional API of turtle with its object-oriented API which is why you need your double import of turtle:

import turtle
from turtle import Turtle, Screen

This only leads to trouble. Let's rewrite the program to use just the object-oriented API and actually work:

from turtle import Turtle, Screen

switchvalue = True

def switch():
    global switchvalue

    switchvalue = not switchvalue

def move():
    delay = 100  # if not moving, slow for human intervention

    if switchvalue:
        jack.forward(1)
        delay = 0  # moving, check back right away

    screen.ontimer(move, delay)  # delay in milliseconds

screen = Screen()

jack = Turtle('turtle')
jack.color('red', 'green')
jack.speed('fastest')
jack.pensize(10)

screen.onkey(switch, 's')
screen.listen()

move()

screen.mainloop()

When the program starts, the turtle will be wandering off to the right. By pressing 's', you can stop and restart this motion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM