问题
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?
回答1:
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)
来源:https://stackoverflow.com/questions/34860931/why-does-my-python-turtle-shape-size-decrease-when-pressing-shift