【问题标题】:Pygame window opening and closing immediatelyPygame窗口立即打开和关闭
【发布时间】:2021-09-09 19:06:02
【问题描述】:

所以当我设置

虽然不是 game_over = False

,我的窗口正常打开,但没有显示文本。而如果我将其设置为 True,文本会显示,但窗口会立即关闭。

代码如下:

***#Write a Python program to create a simple math quiz.
#Importing libraries
import pygame
import sys
import math
from pygame.locals import *
#Initialising fonts
pygame.init()
pygame.font.init()
#Assigning variables
WIDTH = 600
HEIGHT = 600
#Other important things
background_color = (127,255,0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
pygame.display.set_caption("Math Game")
screen.fill(background_color)
pygame.display.flip()
font = pygame.font.Font("freesansbold.ttf", 40)
textX=10
textY=10
def show_text(x,y):
    text=font.render("Math Game", True, (0,0,0))
    screen.blit(text,(x,y))
"""
#Adding the Calculator bit
x = input("Enter Your First Nummber To Add: ")
y = input("Enter Your Second Number To Add: ")
z = str(int(x)+int(y))
print(z)
"""
#Game loop
game_over = True
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
show_text(textX, textY)
pygame.display.update()***

【问题讨论】:

    标签: python python-3.x text pygame window


    【解决方案1】:

    这是Indentation 的问题。 show_textpygame.display.update() 必须在应用程序循环中而不是在应用程序循环之后调用。
    此外,您应该清除应用程序循环中的显示。

    game_over = False
    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
    
    # INDENTATION
    #-->|
        screen.fill(background_color)
        show_text(textX, textY)
        pygame.display.update()
    

    典型的 PyGame 应用程序循环必须:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多