在 类 中使用列表

Using lists in classes

我正在尝试使用 canvas 在 python 3.5 中制作游戏。我有一个列表中三角形的坐标列表。我正在使用 class 来制作一个应该是玩家的对象。当我尝试实现一个移动系统时,我想到了使用一个列表,以便我可以使用 for 循环快速更改坐标,但是当我 运行 代码并按下按钮时,它给了我这个:

"TypeError: list indices must be integers or slices, not float"

这是代码(对不起,如果它是原始的,这是我第一次同时使用 canvas 和 class,我在三个小时内输入了它)

import sys
from tkinter import*


w = 600
h = 400

gui = Tk()
gui.geometry('1000x650')
canvas = Canvas(gui,width=w,height=h,bg='black')
canvas.place(relx=0.5,rely=0.35,anchor=CENTER)
class player():
    def __init__(self,x,y,a):
        self.x1 = x
        self.y1 = y
        self.x2 = x-a/2
        self.y2 = y+a
        self.x3 = x+a/2
        self.y3 = y+a
        self.coords = [self.x1,self.y1,self.x2,self.y2,self.x3,self.y3]
    def display(self):
        canvas.create_polygon(self.x1,self.y1,self.x2,self.y2,self.x3,self.y3,outline='white')
    def move(self,pos):
        if pos == True:
            thrust = 5
        else:
            thrust = -5
        while thrust > 0.1:
            for i in self.coords:
                self.coords[i]=self.coords[i]+thrust
            thrust-=1

up_arrow = Button(gui,text='^',command=lambda:p1.move(True))
up_arrow.place(relx=0.5,rely=0.7,anchor=CENTER)

p1 = player(w/2,h/2,50)
p1.display()

for i in self.coords:

这将依次为 self.coords 中的每个项目设置 i,而不是项目的索引。

这意味着当您编写 self.coords[i]=self.coords[i]+thrust 时可能不是您想要的。 (因为 i 不是索引,而是 self.coords 中的 item

您必须使用 range() 函数来为 i 提供您想要的值。

for i in range(len(self.coords)):
    self.coords[i]=self.coords[i]+thrust

您可能认为这可行

for i in self.coords:
    i = i + thrust

但它起作用,因为iself.coords中那个位置的值。它不是对它的引用。改变它不会改变self.coords。这是暂时的。