【问题标题】:Why does my Python turtle shape size decrease when pressing 'shift'为什么按下“shift”时我的 Python 乌龟形状尺寸会减小
【发布时间】:2016-01-18 17:46:38
【问题描述】:

我正在尝试在 Python 中创建一个海龟,所以我可以通过按键盘上的 +/- 来增加/减小它的大小

import turtle

turtle.setup(700,500)
wn = turtle.Screen()
testing_turtle = turtle.Turtle()


size = 1
def dropsize():
    global size
    if size>1:
        size-=1
        print(size)    # To show the value of size
        testing_turtle.shapesize(size)

def addsize():
    global size
    if size<20:    # To ensure the size of turtle is between 1 to 20
        size+=1
        print(size)
        testing_turtle.shapesize(size)


wn.onkey(addsize,'+')
wn.onkey(dropsize,'-')


wn.listen()
wn.mainloop()

要按“+”键,我必须同时按住“shift”和“=”。问题是当我释放 shift 键(或只是按下 shift 键)时,它会将 size 值减少 1。为什么?

如果我把所有这些代码放到一个主函数中:

def main():
    import turtle
    ...
    ...
    ...
    wn.onkey(addsize,'+')
    ...
    ...

    wn.mainloop()
main()

出现错误消息:

NameError: name 'size' is not defined

我曾将“大小”称为全局变量,但为什么现在没有定义它?

【问题讨论】:

    标签: python python-3.x turtle-graphics


    【解决方案1】:

    您需要使用'plus''minus'将函数绑定到+-键的按键释放事件:

    wn.onkey(addsize,'plus')
    wn.onkey(dropsize,'minus')
    

    要解决NameError 异常,请将size 变量放在主循环之外,或者使用nonlocal 语句代替global

    def addsize():
        nonlocal size
        if size<20:    # To ensure the size of turtle is between 1 to 20
            size+=1
            print(size)
            testing_turtle.shapesize(size)
    

    【讨论】:

    • 感谢优雅。现在我知道我使用了错误的加号和减号键。但是我确实想知道为什么当我在原始代码中按 shift 时大小会减小......我不应该触发 dropsize 函数吗?
    • @Le0:我刚刚向new question 询问了这种行为。
    • 非常感谢。仍然试图理解整个事情,但你清楚地让我了解如何......
    猜你喜欢
    • 2020-09-03
    • 2016-10-02
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2011-03-16
    • 2012-03-03
    • 1970-01-01
    • 2012-07-01
    相关资源
    最近更新 更多