python - 只能将元组(不是 "int")连接到元组

标签 python python-3.x pygame

它没有像应有的那样移动,它说:

x += x_change TypeError: can only concatenate tuple (not "int") to tuple

代码在这里:

import pygame

pygame.init()

display_width = 800
display_height = 600

green = (30,255,50)

gameDisplay = pygame.display.set_mode((display_width,display_height))

pygame.display.set_caption("testV1.0")

clock = pygame.time.Clock()

CharacterImg = pygame.image.load("Character.png")
def Character(x,y):
    gameDisplay.blit(CharacterImg,(x,y))

x = (display_width * 0,45)
y = (display_height * 0,8)

x_change = 0

hit = False

while not hit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            hit = True

            if event.type == pygame.KEYDOWN:
                if pygame.key == K_LEFT:
                    x_change += -50
                if pygame.key == K_RIGHT:
                    x_change += 50

            if event.type == pygame.KEYUP:
                if pygame.key == K_LEFT:
                    x_change += 50
                if pygame.key == K_RIGHT:
                    x_change += -50

            x += x_change



        print(event)

    gameDisplay.fill(green)
    Character(x,y)
    pygame.display.update()
    clock.tick(30)

pygame.quit()
quit()

最佳答案

逗号创建元组,因此 x 和 y 都是元组。如果您想要 float ,请使用点(也不需要括号):

x = display_width * 0.45
y = display_height * 0.8
<小时/>

此外,在事件循环中,您必须将 pygame.key 替换为 event.key

x += x_change 可能应该在 while 循环中而不是在事件循环中。

并且您必须将该 block 缩进一次:

        if event.type == pygame.KEYDOWN:
            if pygame.key == K_LEFT:
                x_change += -50
            if pygame.key == K_RIGHT:
                x_change += 50

        if event.type == pygame.KEYUP:
            if pygame.key == K_LEFT:
                x_change += 50
            if pygame.key == K_RIGHT:
                x_change += -50

关于python - 只能将元组(不是 "int")连接到元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47727344/

相关文章:

python - 无法在空数组中添加元素。插入、追加和连接之间的区别

urls.py 中的 Django2 AttributeError

python - 如何在Python中恢复中断的FTP上传

python - 为什么 pygame 键码是特定于操作系统的?

python - Python 中的类字符列表映射如何工作?

python - 为什么我会收到 TypeError : '<' not supported between instances of 'int' and 'tuple' ?

python - 为什么一个对象在没有类的情况下仍然可以正常工作

python - 对已使用无服务器推出的 lambda 函数设置重试策略

python - 使用 ctypes 在 Python 中右键单击

python - 梵文的音节化