You need to enable JavaScript to run this app. Pygame/Python如何将文本保存到类实例实现待办事项内容持久化
优惠活动
大模型
产品
解决方案
定价
更多

Pygame/Python如何将文本保存到类实例实现待办事项内容持久化

方案实现说明

我们提供两种持久化方案,你可以根据需求选择:

方案1:单TXT文件存储(推荐,管理更简单)

适合你的16个输入框顺序固定的场景,所有内容按顺序存在一个文件内,第N行对应第N个输入框的内容。

实现逻辑:

  • 新增全局加载函数:应用启动时读取存储文件,按行解析内容分配给对应顺序的输入框,文件不存在时默认返回空内容。
  • 新增全局保存函数:触发保存时,按输入框列表顺序依次写入每行内容到文件。
  • 修改InputBox的回车逻辑:删除原来按回车清空文本的代码,触发全局保存操作。
  • 新增退出自动保存:防止用户未按回车直接关闭应用导致内容丢失。

修改后的完整代码:

import pygame
import datetime
import time
import os

pygame.init()
clock = pygame.time.Clock()
pygame.font.init()

# 存储文件路径
SAVE_FILE = "todo_save.txt"

# Font
text_font = pygame.font.Font('dogicapixelbold.ttf', 16)
color = (233, 248, 215)
active = False
# screen resolution
Width = 800
Height = 600
screen = pygame.display.set_mode((Width, Height))

# 加载保存的内容
def load_saved_content():
    if not os.path.exists(SAVE_FILE):
        return []
    with open(SAVE_FILE, 'r', encoding='utf-8') as f:
        lines = f.read().splitlines()
    return lines

# 保存所有输入框内容
def save_all_content(input_boxes):
    content = [box.text for box in input_boxes]
    with open(SAVE_FILE, 'w', encoding='utf-8') as f:
        f.write('\n'.join(content))

class InputBox:

    def __init__(self, x, y, w, h, text=''):
        self.rect = pygame.Rect(x, y, w, h)
        self.color = color
        self.text = text
        self.txt_surface = text_font.render(text, True, self.color)
        self.active = False
        self.txt_rect = self.txt_surface.get_rect()
        self.cursor = pygame.Rect(self.txt_rect.topright, (3, self.txt_rect.height + 5))
    def handle_event(self, event, input_boxes=None):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the user clicked on the input_box rect.
            if self.rect.collidepoint(event.pos):
                # Toggle the active variable.
                self.active = not self.active
            else:
                self.active = False
        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    print(self.text)
                    # 删掉原来清空文本的代码,触发保存
                    self.active = False
                    if input_boxes:
                        save_all_content(input_boxes)

                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode
                    # Cursor
                    self.txt_rect.size = self.txt_surface.get_size()
                    self.cursor.topleft = self.txt_rect.topright
                    # Limit characters           -20 for border width
                    if self.txt_surface.get_width() > self.rect.w - 15:
                        self.text = self.text[:-1]

    def draw(self, screen):
        # Blit the text.
        screen.blit(self.txt_surface, (self.rect.x + 5, self.rect.y + 10))
        # Blit the rect.
        pygame.draw.rect(screen, self.color, self.rect, 1)
        # Blit the  cursor
        if self.active:
            if time.time() % 1 > 0.5:
                # bounding rectangle of the text
                text_rect = self.txt_surface.get_rect(topleft=(self.rect.x + 5, self.rect.y + 10))
                # set cursor position
                self.cursor.midleft = text_rect.midright
                pygame.draw.rect(screen, self.color, self.cursor)

    def update(self):
        # Re-render the text.
        self.txt_surface = text_font.render(self.text, True, self.color)

def main():
    clock = pygame.time.Clock()
    input_box1 = InputBox(115, 170, 250, 36)
    input_box2 = InputBox(115, 224, 250, 36)
    input_box3 = InputBox(115, 278, 250, 36)
    input_box4 = InputBox(115, 333, 250, 36)
    input_box5 = InputBox(115, 386, 250, 36)
    input_box6 = InputBox(115, 440, 250, 36)
    input_box7 = InputBox(115, 494, 250, 36)
    input_box8 = InputBox(440, 170, 250, 36)
    input_box9 = InputBox(440, 224, 250, 36)
    input_box10 = InputBox(440, 278, 250, 36)
    input_box11 = InputBox(440, 333, 250, 36)
    input_box12 = InputBox(440, 386, 250, 36)
    input_box13 = InputBox(440, 440, 250, 36)
    input_box14 = InputBox(440, 494, 250, 36)
    input_box15 = InputBox(440, 115, 250, 36)
    input_box16 = InputBox(440, 61, 250, 36)
    input_boxes = [input_box1, input_box2, input_box3, input_box4, input_box5, input_box6, input_box7, input_box8,
                   input_box9, input_box10, input_box11, input_box12, input_box13, input_box14,
                   input_box15, input_box16]
    # 启动时加载保存的内容
    saved_content = load_saved_content()
    for idx, box in enumerate(input_boxes):
        if idx < len(saved_content):
            box.text = saved_content[idx]
            box.update()
    
    done = False

    while not done:
        # Background
        screen.fill((0, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出前保存所有内容
                save_all_content(input_boxes)
                done = True
            for box in input_boxes:
                box.handle_event(event, input_boxes)

        for box in input_boxes:
            box.update()

        for box in input_boxes:
            box.draw(screen)
        pygame.display.update()
        clock.tick(120)


if __name__ == '__main__':
    main()
    pygame.quit()

方案2:每个输入框单独存TXT文件

适合后续可能会增减输入框的场景,每个输入框独立管理自己的存储文件,互不影响。

核心修改点:

  • 给InputBox新增save_id初始化参数,作为当前输入框的唯一标识,对应存储文件名。
  • InputBox内部新增load和save方法,初始化时自动加载自身的存储内容,回车时自动保存自身内容到对应文件。

修改后的InputBox类示例:

class InputBox:
    def __init__(self, x, y, w, h, save_id, text=''):
        self.save_id = save_id
        self.save_path = f"box_{save_id}.txt"
        self.rect = pygame.Rect(x, y, w, h)
        self.color = color
        # 初始化时加载自身保存的内容
        self.text = self.load() if self.load() else text
        self.txt_surface = text_font.render(self.text, True, self.color)
        self.active = False
        self.txt_rect = self.txt_surface.get_rect()
        self.cursor = pygame.Rect(self.txt_rect.topright, (3, self.txt_rect.height + 5))
    
    def load(self):
        if os.path.exists(self.save_path):
            with open(self.save_path, 'r', encoding='utf-8') as f:
                return f.read().strip()
        return None
    
    def save(self):
        with open(self.save_path, 'w', encoding='utf-8') as f:
            f.write(self.text)
    
    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.active = not self.active
            else:
                self.active = False
        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    print(self.text)
                    self.active = False
                    # 回车保存自身内容
                    self.save()
                # 其余按键逻辑和原代码一致

创建输入框的时候传入唯一的save_id即可:

input_box1 = InputBox(115, 170, 250, 36, save_id=0)
input_box2 = InputBox(115, 224, 250, 36, save_id=1)
# 其余输入框以此类推,save_id不重复即可

内容的提问来源于stack exchange,提问作者Khoi58

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 18:42:01