Python3中Pygame编译方法及无报错自定义函数不执行问题咨询
代码运行故障原因
你遇到的文本不显示问题是因为代码里误将print_text函数名覆盖为元组,导致所有文本绘制逻辑失效,共两处错误:
start_game()函数中写了print_text = (win, sentence_s, 100, 250, 40, (255, 0, 0)),多写了等号,没有实际调用文本绘制函数,同时将原函数定义覆盖为了元组- 主循环末尾写了
print_text = (win, "Typing Speed", 120, 80, 80, (0, 255, 255)),同样多写等号,进一步覆盖了函数定义
去掉两处的等号,正常调用函数即可恢复文本显示功能。另外get_sentence()函数直接读取new.txt文件,若同级目录没有该文件会触发异常,测试阶段可以先写死测试句子避免文件不存在的问题。
Python3中使用Pygame的方法
不需要手动编译Pygame,直接安装官方预编译包即可:
- 全平台通用安装命令:
pip install pygame
如果确实需要自行编译(适配特殊架构、修改源码等场景):
- 先安装对应系统的依赖库:SDL2、SDL2_ttf、SDL2_image、SDL2_mixer开发包
- 拉取Pygame官方源码,执行
python setup.py build完成编译 - 编译完成后执行
python setup.py install安装到本地环境即可
修正后可运行代码
import pygame import sys import random from pygame.locals import * pygame.init() width = 800 height = 600 black = (0, 0, 0) red = (255, 0, 0) input_text = '' typing = False win = pygame.display.set_mode((width, height)) pygame.display.set_caption("Type Speed Program") def print_text(screen, massage, x, y, font_s, clr): font = pygame.font.Font(None, font_s) text = font.render(massage, True, clr) screen.blit(text, (x, y)) def get_sentence(): # 测试时可先注释掉文件读取,用固定句子测试 # t_f = open('new.txt').read() # sentences = t_f.split("\n") # sentence = random.choice(sentences) sentence = "This is a test sentence for typing speed check." return sentence def start_game(): sentence_s = get_sentence() # 去掉等号,正常调用函数 print_text(win, sentence_s, 100, 250, 40, (255, 0, 0)) pygame.draw.rect(win, (255, 255, 0), (75, 300, 650, 50), 3) start_game() while True: win.fill(black, (75, 300, 650, 50)) print_text(win, input_text, 80, 310, 35, (255, 255, 255)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() if event.button == 1: if (75 <= x <= 725) and (300 <= y <= 350): typing = True input_text = '' elif event.type == KEYDOWN: if typing: if event.key == K_RETURN: print(input_text) if event.key == K_BACKSPACE: input_text = input_text[:-1] else: input_text += event.unicode # 去掉等号,正常调用函数 print_text(win, "Typing Speed", 120, 80, 80, (0, 255, 255)) pygame.display.update()
注:已移除函数内重复的pygame.display.update()调用,统一在主循环末尾刷新即可,避免重复刷新导致的画面闪烁问题。
内容的提问来源于stack exchange,提问作者Neda Jalali
相关产品推荐
相关产品推荐

