在类中使用列表

时间:2016-12-18 16:39:44

标签: list python-3.x class tkinter-canvas

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

  

" TypeError:list indices必须是整数或切片,而不是float"

这里是代码(抱歉,如果它是原始的,这是我第一次使用画布和课程,我在三小时内输入了这个代码)

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()

1 个答案:

答案 0 :(得分:1)

for i in self.coords:

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

这意味着当你写self.coords[i]=self.coords[i]+thrust时可能不是你想要的。 (由于i不是索引,而是self.coords中的

您必须使用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。这是暂时的。