'float'对象不能解释为整数

时间:2017-10-08 11:39:22

标签: python python-3.x

这是我的代码:

import pygame, sys

pygame.init()

FPS = 30
clock = pygame.time.Clock()

screen = pygame.display.set_mode((480, 320))

mainsheet = pygame.image.load("walking.png")
sheet_size = mainsheet.get_size()
horiz_cells = 6
vert_cells = 5
cell_width = sheet_size[0] / horiz_cells
cell_height = sheet_size[1] / vert_cells

cell_list = []
for y in range (0, sheet_size[1], cell_height):
    for x in range (0, sheet_size[0], cell_width):
        surface = pygame.Surface((cell_width, cell_height))
        surface.blit(mainsheet, (0,0), (x, y, cell_width, cell_height))
        cell_list.append(surface)

cell_position = 0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if cell_position < len(cell_list) - 1:
            cell_position += 1
        else:
            cell_position = 0

screen.blit(cell_list[cell_position], (100, 10))

clock.tick(FPS)
pygame.display.update()

..错误是:

  

Traceback(最近一次调用最后一次):文件   “C:\ Users \ HP \ Desktop \ running.py”,第18行,in为y   (0,sheet_size [1],cell_height):TypeError:'float'对象不能   解释为整数

1 个答案:

答案 0 :(得分:2)

这是Python 3 docs

  

范围构造函数的参数必须为整数(或者   内置int或任何实现__index__特殊的对象   法)。

因此,您需要使用整数作为范围参数。

我不知道您的应用程序中究竟需要什么,但更改这些行将解决错误:

...
cell_width = int(sheet_size[0] / horiz_cells)
cell_height = int(sheet_size[1] / vert_cells)
...

...
cell_width = sheet_size[0] // horiz_cells
cell_height = sheet_size[1] // vert_cells
...