【问题标题】:'float' object cannot be interpreted as an integer'float' 对象不能解释为整数
【发布时间】:2018-03-19 17:34:15
【问题描述】:

这是我的代码:

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 行,在 y 范围内 (0, sheet_size[1], cell_height): TypeError: 'float' object cannot be 解释为整数

【问题讨论】:

  • sheet_size[1]cell_height 不是整数 - 它是一个浮点数......所以首先以一种有意义的方式将它们变成一个整数......
  • 你能告诉我怎么做吗

标签: python python-3.x


【解决方案1】:

这是来自Python 3 docs

range 构造函数的参数必须是 整数(要么 内置 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
...

【讨论】:

  • 您也可以使用// 代替/ 并跳过int,因为/ 在两个整数之间会产生一个浮点结果。
猜你喜欢
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多