Skip to main content
 首页 » 编程设计

python之pygame 错误 : TypeError: must be 2-item sequence

2025年05月04日13birdshome

我想看看大学项目的 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 所需的所有模块。

也许你能帮我。

请您参考如下方法:

您需要一个元组,而不是整数:

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 ,您需要在尺寸周围使用方括号或常规括号。