猿问

Pygame 文本不显示

我是 python 的新手(和编码本身),并试图在 pygame 中创建一个 Hello World 脚本。它在 python 3.2 和 pygame 1.9.2 中。我有一本书,我直接从中复制了它,但是当我运行它时,我得到的只是一个黑色窗口。这是我的代码:


import pygame

import sys

pygame.init()

from pygame.locals import *

white = 255,255,255

blue = 0,0,200

screen = pygame.display.set_mode((600,500))

pygame.font.init

myfont = pygame.font.Font(None,60)

textImage = myfont.render("Hello Pygame", True, white)

screen.fill(blue)

screen.blit(textImage, (100,100))

pygame.display.update

这本书使用的是完全相同的版本,但我仍然无法让它工作。


jeck猫
浏览 292回答 2
2回答

慕妹3242003

好的,有几个问题。PyGame 屏幕更新功能是update(),您缺少该调用和字体 init 上的括号。pygame.display.update()screen = pygame.display.set_mode((600,500))pygame.font.init()其次,您的程序会立即退出。您需要实现一个事件循环,并等待窗口关闭消息。这对我有用:import sysimport pygamefrom pygame.locals import *white = 255,255,255blue  = 0,0,200pygame.init()screen = pygame.display.set_mode((600,500))pygame.font.init()myfont = pygame.font.Font(None,60)textImage = myfont.render("Hello Pygame", True, white)screen.fill(blue)screen.blit(textImage, (100,100))pygame.display.update()while (True):    event = pygame.event.wait()    if event.type == QUIT:        pygame.quit()        sys.exit()我知道您才刚刚开始,但稍后可以节省您时间(并使其更容易)的一件事是将您的窗口宽度和高度放入变量中。然后根据这些值在屏幕上定位项目。这样,当您稍后更改显示大小(或其他)时,您只需要更改这两个地方的代码。WIDTH  = 600HEIGHT = 500pygame.init()screen = pygame.display.set_mode((WIDTH, HEIGHT))...text_width  = textImage.get_width()text_height = textImage.get_height()# Centre text #TODO - handle text being larger than windowscreen.blit(textImage, ( (WIDTH-text_width)//2 , (HEIGHT-text_height)//2 ))注意://是python中的整数除法

芜湖不芜

在最后一行的更新调用中缺少一个 ():pygame.display.update()
随时随地看视频慕课网APP

相关分类

Python
我要回答