我的错在哪里
“这个代码只是我代码的一部分 我只是复制了一部分”
import turtle
wn=turtle.Screen()
wn.bgcolor("black")
wn.title("Pacman")
wn.setup(900,700)
class Pacman(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("yellow")
self.penup()
self.speed(0)
def up(self):
self.goto(self.xcor(),self.ycor()+24)
def down(self):
self.goto(self.xcor(),self.ycor()-24)
def left(self):
self.goto(self.xcor()-24,self.ycor())
def right(self):
self.goto(self.xcor()+24,self.ycor())
wn.listen()
wn.onkey(Pacman.down, "Down")
wn.onkey(Pacman.up, "Up")
wn.onkey(Pacman.right, "Right")
wn.onkey(Pacman.left, "Left")
wn.tracer(0)
while True:
wn.update()
失败
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\asus\AppData\Local\Programs\Python\Python37-
32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\asus\AppData\Local\Programs\Python\Python37-
32\lib\turtle.py", line 686, in eventfun
fun()
TypeError: up() missing 1 required positional argument: 'self'
当我点击右,下,上或左按钮方块不动,在控制台写这个失败
在
wn.listen()
之前做pacman_instance = Pacman()
问题是您试图对类而不是类的实例执行操作
“Pacman”是一个类模板,所以不能这样调用它的方法。您应该创建Pacman对象(如下所示):
然后你可以像这样运行你的函数:
或者(如果我没弄错的话)你可以试试这个,我认为这也应该管用:
如果您只需在
Pacman = Pacman()
行之前添加wn.listen()
,它就可以工作了问题是您试图访问一个未实例化的类,使用这一行创建这个实例,所有操作都将正常工作;)
相关问题 更多 >
编程相关推荐