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

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

我想让我的程序在按下 Page UP 键时增加 Python 的乌龟的笔大小。 我尝试了以下方法:

#!/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()

但是报错。完整回溯:

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'

看起来 pensize() 是一个方法(不是变量),需要调用:https://docs.python.org/2/library/turtle.html#turtle.pensize

试试这个:

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

您需要使用新尺寸调用 pensize 方法。无法将方法引用添加到

例如,在增加

size += 1
py.pensize(size)

此外,除非您希望大小始终为一个大小 (20),否则请将 while 循环更改为 if 语句

while size>=1 and size<=20: