简体   繁体   中英

TypeError: unsupported operand type(s) for +=: 'method' and 'int'

I want to my program to increase the pensize of Python's turtle when the Page UP key is pressed. I tried the following:

#!/usr/bin/env python3
import turtle
wn=turtle.Screen()
wn.title('Control using first letter of desired action')
py=turtle.Turtle()
py.color('blue')
size=1
def front():
    py.fd(90)
def back():
    py.bk(90)
def right():
    py.rt(45)
def left():
    py.lt(45)
def increasize():
    global size
    while size>=1 and size<=20:
        py.pensize+=1
def decreasize():
    global size
    while size>=1 and size<=20:
        py.pensize-=1
wn.onkey(front,'w')
wn.onkey(back,'s')
wn.onkey(right,'d')
wn.onkey(left,'a')
wn.onkey(increasize,'Prior')
wn.onkey(decreasize,'Next')
wn.listen()
wn.mainloop()

But it gives an error. Full traceback:

Exception in Tkinter callback
Traceback (most recent call last):
  File "c:\program files\python3\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "c:\program files\python3\lib\turtle.py", line 686, in eventfun
    fun()
  File "D:\Python\draw_straight_key.py", line 19, in increasize
    py.pensize+=1
TypeError: unsupported operand type(s) for +=: 'method' and 'int'
Exception in Tkinter callback
Traceback (most recent call last):
  File "c:\program files\python3\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "c:\program files\python3\lib\turtle.py", line 686, in eventfun
    fun()
  File "D:\Python\draw_straight_key.py", line 23, in decreasize
    py.pensize-=1
TypeError: unsupported operand type(s) for -=: 'method' and 'int'

It looks like pensize() is a method (not a variable) and needs to be called: https://docs.python.org/2/library/turtle.html#turtle.pensize

Try this:

pensize = py.pensize()
pensize += 1
py.pensize(pensize)

You need to call the pensize method with the new size. A method reference cannot be added to

For example, in increasize

size += 1
py.pensize(size)

Also, unless you want the size to always be one size (20), then change the while loop to an if statement

while size>=1 and size<=20:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM