我正在尝试用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()
要按&#39; +&#39;关键,我将不得不举行“转移”。 &安培;按&#39; =&#39;同时。问题是当我释放换档键(或只是按下换档键)时,它会将尺寸值减小1.为什么?
此外,如果我将所有这些代码放入主函数中:
def main():
import turtle
...
...
...
wn.onkey(addsize,'+')
...
...
wn.mainloop()
main()
显示错误消息:
NameError: name 'size' is not defined
我打电话给&#39; size&#39;一个全局变量,但为什么现在没有定义?
答案 0 :(得分:0)
您需要使用'plus'
和'minus'
将函数绑定到 + 和 - 键的键释放事件:< / p>
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)