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

标签 python pygame typeerror

我想看看大学项目的 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

运行为:

截图

ScreenShot

控制台

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

关于python - pygame 错误 : TypeError: must be 2-item sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24189241/

相关文章:

python - 使用 Django ORM 作为跨主机的多进程锁

python - 如何在配置文件中存储格式化字符串?

python - 区分组中的对象

python - 如何从 pygame 中的 if 语句中 blit 文本?

Javascript 错误停止 $document.ready()

javascript - 类型错误:showToastrMessage.init 不是函数

python - 附加 RTF 格式样式

python - 合并两个字典,连接字符串值?

python - 如何将一些对象分布到整个屏幕上

python-2.7 - PyInstaller 2.0 类型错误 : compile() expected string without bull bytes