关于#Python#的问题,如何解决?

问题遇到的现象和发生背景

今天是教师节,我想写个Python代码送给我的恩师,然后出现了bug

问题相关代码,请勿粘贴截图
import pygame
import sys
from pygame.locals import *
import random
import time


SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
FPS = 50
PINK = (255, 192, 203)


def showText(screen, text):
    font = pygame.font.SysFont("microsoftyahei", random.randint(10, 50))

    text = font.render(text,
                       True,
                       (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

    text_x = SCREEN_WIDTH
    text_y = random.randint(0, SCREEN_HEIGHT)

    screen.blit(text, (text_x, text_y))

    while text_x > -100:
        text_x += 1

        screen.blit(text, (text_x, text_y))

        pygame.display.update()


def run():
    with open("blessing.txt", "r", encoding="utf-8") as f:
        blessings = f.read()
        f.close()

    # print(blessings)
    blessingList = blessings.split("\n")
    # print(blessingList)

    fpsClock = pygame.time.Clock()

    pygame.init()

    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

    pygame.display.set_caption("教师节快乐!")

    image_loveHeart = pygame.image.load("images/爱心.webp")

    screen.blit(image_loveHeart, (int((SCREEN_WIDTH - 567) / 2), int((SCREEN_HEIGHT - 500) / 2)))

    # print(pygame.font.get_fonts())

    pygame.mixer.music.load("./music/小蓓蕾组合 - 每当我走过老师窗前.mp3")
    pygame.mixer.music.play(-1, 0.0)

    while True:

        screen.fill(PINK)

        screen.blit(image_loveHeart, (int((SCREEN_WIDTH - 567) / 2), int((SCREEN_HEIGHT - 500) / 2)))

        """
        font = pygame.font.SysFont("microsoftyahei", random.randint(10, 50))
    
        text = font.render(random.choice(blessingList),
                           True,
                           (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    
        text_x = SCREEN_WIDTH
        text_y = random.randint(0, SCREEN_HEIGHT)
    []([]())
        screen.blit(text, (text_x, text_y))
        """

        for event in pygame.event.get():

            if event.type == QUIT:
                pygame.quit()
                sys.exit(0)

        pygame.display.update()

        fpsClock.tick(FPS)

        showText(screen, random.choice(blessingList))

        time.sleep(random.random())


if __name__ == "__main__":
    run()


运行结果及报错内容

虽然卡住了,但没报错

img

img

我的解答思路和尝试过的方法

我尝试过打断点,可就是跳不进showText去,要跳就是跳到random的界面,如果直接跳过就Connected

我想要达到的结果

背景音乐正常播放,然后文字随机高度按一定间隔从右边往左边行走

问题出在showtext函数里面。pygame的while循环必须不停地刷新event,否则就会出现卡住的情况。
解决方法:在showtext里面的while循环中加上for event in pygame.event.get().......的代码