Pygame的窗口立即关闭?

时间:2019-03-23 23:35:24

标签: python-3.x pygame

当我尝试运行此pygame代码时,它会立即关闭?

当我停止绘制文本时,窗口不会立即关闭,所以我知道我做错了事。

import pygame
background_colour = (255, 255, 255)
(width, height) = (1920, 1080)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('fat')
screen.fill(background_colour)
font = pygame.font.Font(None, 32)
color = pygame.Color('dodgerblue2')
pygame.display.flip()
running = True
while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False




text = ""

while running:
  for event in pygame.event.get():
      if event.type == pygame.KEYDOWN:
        vanishingtext += event.unicode
        text += event.unicode
      elif event.type == pygame.K_BACKSPACE:
         text = text[:-1]        
      elif event.type == pygame.K_RETURN:
        interpret(text)
        text = ""
      else:
        pass

        txt_surface = font.render(text, True, color)
        screen.blit(txt_surface, (50, 100))

我希望出现一个允许我键入和退格的屏幕,如果我按Enter键,则文本应该完全消失,并且应该运行一个可以解释字符串的函数。我还没有将interpet定义为函数,但是在确定是否可以在屏幕上使用它之后,我便会这样做。

1 个答案:

答案 0 :(得分:1)

该代码未调用pygame.init()。还有两个事件循环,一旦running变成False,第二个事件循环将直接消失。

import pygame

pygame.init()

(width, height) = ( 400, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('fat')

background_colour = pygame.Color('white')
color   = pygame.Color('dodgerblue2')
font    = pygame.font.Font(None, 32)
clock   = pygame.time.Clock()
running = True
text    = ''

while running:

    # handle events and user-input
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if ( event.key >= pygame.K_SPACE and event.key <= pygame.K_z ):
                # Append key-stroke's character
                text += event.unicode
            elif ( event.key == pygame.K_BACKSPACE ):
                text = text[:-1]
            elif ( event.key == pygame.K_RETURN ):
                print("interpret(text) - NOT IMPLEMENTED")
                text = ""

    # repaint the screen
    screen.fill(background_colour)
    txt_surface = font.render(text, True, color)
    screen.blit(txt_surface, (50, 100))

    pygame.display.flip()
    clock.tick_busy_loop(60) # limit FPS

此代码为我提供了一个带有白色背景的名为“ fat”的窗口。在英文键盘上打字会给我蓝色字母,可以退格。按下 Enter 会有所处理。