Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

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)
question from:https://stackoverflow.com/questions/65926437/switch-in-python-turtle-module

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ifs 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...