[英]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.我想让我的程序在按下 Page UP 键时增加 Python 乌龟的笔大小。 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看起来 pensize() 是一种方法(不是变量),需要调用: 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.您需要使用新尺寸调用 pensize 方法。 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此外,除非您希望大小始终为一个大小 (20),否则将 while 循环更改为 if 语句
while size>=1 and size<=20:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.