Pygame文本不显示

时间:2018-10-23 21:56:33

标签: python 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

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

2 个答案:

答案 0 :(得分:1)

好,有几个问题。

PyGame屏幕更新功能为update(),您缺少该调用以及字体初始化的括号。

pygame.display.update()
screen = pygame.display.set_mode((600,500))
pygame.font.init()

第二,您的程序立即退出。您需要实现一个事件循环,并等待窗口关闭消息。

这对我有用:

import sys
import pygame
from pygame.locals import *

white = 255,255,255
blue  = 0,0,200

pygame.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  = 600
HEIGHT = 500

pygame.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 window
screen.blit(textImage, ( (WIDTH-text_width)//2 , (HEIGHT-text_height)//2 ))

注意://是python中的整数除法

答案 1 :(得分:0)

最后一行的更新调用上缺少():

pygame.display.update()
相关问题