【发布时间】: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