为什么我的 Python 海龟形状在按下 'shift' 时会变小

Why does my Python turtle shape size decrease when pressing 'shift'

我正在尝试在 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()

To press the '+' key, I will have to hold 'shift' & press '=' at the same time. The problem is when I release the shift key ( or just press the shift key), it decreases the size value by 1. Why?

此外,如果我将所有这些代码放入主函数中:

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

    wn.mainloop()
main()

显示错误消息:

NameError: name 'size' is not defined

我曾将'size'称为全局变量,但为什么现在没有定义它?

您需要使用'plus''minus'将函数绑定到+和[=23=的key-release事件]-键:

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)