【问题标题】:pygame error: TypeError: must be 2-item sequencepygame错误:TypeError:必须是2项序列
【发布时间】:2019-04-01 20:40:00
【问题描述】:

我想看看一个大学项目的 pygame 模块。我找到了一个非常简短的教程,我按照该教程为游戏创建了一个窗口。

这是我的代码:

import sys
import pygame
from pygame.locals import *

pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode(screen_width,screen_height)
pygame.display.set_caption("pygame test")
pygame.mouse.set_visible(True)

done = False
while not done:
  for event in pygame.event.get():
    if (event.type == KEYUP) or (event.type == KEYDOWN):
      print(event)
    if (event.key == K_ESCAPE):
      done = True

如果我尝试执行应用程序,它会失败并出现以下错误:

screen=pygame.display.set_mode(screen_width,screen_height)
TypeError: must be 2-item sequence, not int

据我了解函数调用,它应该像我的示例一样工作。对在线错误的进一步研究并没有让我得到任何有用的结果。

我正在运行 OSX Mavericks、X11(或更好的 XQuartz)以及最新的 python 运行时和 pygame 所需的所有模块。

也许你可以帮助我。

【问题讨论】:

    标签: python pygame typeerror


    【解决方案1】:

    您需要tuple,而不是整数:

    screen = pygame.display.set_mode((screen_width,screen_height))
    

    这是因为您可以将其他变量传递给set_mode

    screen = pygame.display.set_mode((screen_width, screen_height), 0, 32)
    

    这是您编辑的代码:

    import sys
    import pygame
    from pygame.locals import *
    
    pygame.init()
    
    screen_width = 800
    screen_height = 600
    screen = pygame.display.set_mode((screen_width,screen_height))
    pygame.display.set_caption("pygame test")
    pygame.mouse.set_visible(True)
    
    done = False
    while not done:
      for event in pygame.event.get():
        if (event.type == KEYUP) or (event.type == KEYDOWN):
          print(event)
        if (event.key == K_ESCAPE):
          done = True
    

    运行如下:

    截图

    控制台

    bash-3.2$ python test.py
    <Event(2-KeyDown {'scancode': 0, 'key': 304, 'unicode': u'', 'mod': 0})>
    <Event(2-KeyDown {'scancode': 0, 'key': 310, 'unicode': u'', 'mod': 1})>
    <Event(3-KeyUp {'scancode': 0, 'key': 304, 'mod': 1024})>
    <Event(3-KeyUp {'scancode': 0, 'key': 310, 'mod': 0})>
    bash-3.2$ 
    

    如您所见here,您需要在尺寸周围使用方括号或常规括号。

    【讨论】:

      【解决方案2】:

      您需要传递一个tuple,而不是两个单独的int 来解析。仔细看pygame docs

      screen = pygame.display.set_mode((screen_width, screen_height))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-31
        • 2020-03-29
        • 2021-11-14
        • 1970-01-01
        • 2014-09-09
        • 1970-01-01
        • 2018-04-26
        • 2015-05-23
        相关资源
        最近更新 更多