1

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?

unor
  • 92,415
  • 26
  • 211
  • 360
Le0
  • 107
  • 1
  • 8

1 Answers1

0

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)
elegent
  • 3,857
  • 3
  • 23
  • 36
  • Thanks elegent. Now I know that I've used a wrong key for plus and minus. However I do wonder why the size decreases when I press shift in my original code... I shouldn't have triggered the dropsize function right? – Le0 Jan 19 '16 at 02:21
  • @Le0: I just asked a [new question](http://stackoverflow.com/q/34932365/4594443) about this behavior. – elegent Jan 21 '16 at 20:13
  • Thank you so much. Still trying to understand the whole thing but you clearly give me some insight into how... – Le0 Jan 31 '16 at 11:28