为什么按“shift"时我的 Python 乌龟形状大小会减小 [英] Why does my Python turtle shape size decrease when pressing 'shift'

查看:22
本文介绍了为什么按“shift"时我的 Python 乌龟形状大小会减小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

导入海龟龟.setup(700,500)wn = 海龟.Screen()testing_turtle = 海龟.Turtle()大小 = 1def dropsize():全球规模如果尺寸>1:大小-=1print(size) # 显示大小的值testing_turtle.shapesize(大小)def addsize():全球规模if size<20: #保证海龟的大小在1到20之间尺寸+=1打印(尺寸)testing_turtle.shapesize(大小)wn.onkey(addsize,'+')wn.onkey(dropsize,'-')wn.listen()wn.mainloop()

<块引用>

要按+"键,我必须按住shift"键同时按=".问题是当我松开 shift 键(或只是按下 shift 键)时,它会将 size 值减少 1.为什么?

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

def main():进口龟.........wn.onkey(addsize,'+')......wn.mainloop()主要的()

出现错误消息:

NameError: name 'size' 未定义

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

解决方案

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

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

要解决 NameError 异常,请将 size 变量放在主循环旁边,或者使用 nonlocal 语句而不是 global :

def addsize():非局部大小if size<20: #保证海龟的大小在1到20之间尺寸+=1打印(尺寸)testing_turtle.shapesize(大小)

I am trying to create a turtle in Python so I could increase/ decrease it's size by pressing +/- on keyboard

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?

Also if I put all these code into a main function:

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

    wn.mainloop()
main()

A error message show up:

NameError: name 'size' is not defined

I had called 'size' a global variable but why it is not defined now?

解决方案

You need to use 'plus' and 'minus' to bind the functions to the key-release event of the + and - key:

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

To solve the NameError exception, either place your size variable otside your main loop or use the nonlocal statement instead of 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"时我的 Python 乌龟形状大小会减小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆