我是一个学习python三周左右的年轻人,我发现我写的这个类好长,导致出现问题时溯源和改代码比较麻烦,你有什么解决思路吗?
(该类的代码如下:)
import os.path
import json as js
from tkinter import *
from tkinter import messagebox
from classes.class_FontManager import FontManager
from classes.class_OptionMenuManager import OptionMenuManager
class Main:
def __init__(self):
self.root = Tk()
self.root.title('互动小说阅读器')
self.font_manager = FontManager(self.root)
self.option_menu_manager = OptionMenuManager(self.root, self.font_manager)
self.novel_title = ''
self.page_memory = []
self.current_page = ''
self.story_data = {}
self.page_data = {}
self.novel_content = StringVar()
self.novel_content_label = Label(self.root,
textvariable=self.novel_content,
font=self.font_manager.current_font)
self.novel_content_label.grid(row = 1, column = 0, columnspan=1, padx=10, pady=10, sticky = W)
self.novel_list = []
self.option_list = []
self.go_back_button = Button(text='返回上一页',
command=self.go_back_to_last_page,
font=self.font_manager.current_font)
self.go_back_button.grid(row = 2, column = 0, padx=10, pady=10, sticky = W)
# 为变量添加“追踪回调”(当变量的值改变时触发某函数)
self.font_manager.font_family.trace_add("write", self.option_menu_manager.set_menu_font)
self.font_manager.font_size.trace_add("write", self.option_menu_manager.set_menu_font)
self.font_manager.font_weight.trace_add("write", self.option_menu_manager.set_menu_font)
self.trace_op = None
self.start()
def start(self):
self.load_novel_list()
self.load_reading_progress()
self.load_story_data()
self.option_menu_manager.make_novel_menu(self.novel_title, self.novel_list)
self.renew_page_content()
self.option_menu_manager.selected_novel.trace_add("write", self.react_to_selected_novel)
self.trace_op = self.option_menu_manager.selected_option.trace_add("write", self.react_to_selected_option)
self.root.mainloop()
def load_reading_progress(self):
path = 'novel_content_storage/reading_progress.json'
# 要是文件不存在就先创建并写入默认内容
if not os.path.exists(path):
# 所有小说默认页码记忆为第一页
initial_reading_progress_data = {"last_novel": self.novel_list[0]}
for novel_title in self.novel_list:
initial_reading_progress_data[novel_title] = ["page_1"]
with open(path, 'w', encoding='utf-8') as f:
js.dump(initial_reading_progress_data, f)
# 读取存储的小说记忆和页码记忆
with open(path, 'r', encoding='utf-8') as f:
memory_file = js.load(f)
self.novel_title = memory_file['last_novel']
self.page_memory = memory_file[self.novel_title]
self.current_page = self.page_memory[-1]
print('\n阅读进度读取成功 ', self.novel_title, ' ', self.current_page)
def load_story_data(self):
# 加载该故事所有内容
path = f"novel_content_storage/{self.novel_title}.json"
# 小说文件不存在时的异常处理
if not os.path.exists(path):
print('故事内容加载失败,因为文件路径不存在 ', self.novel_title)
self.novel_title = f'《{self.novel_title}》小说文件丢失,请点击此处重新选择要阅读的小说'
self.current_page = 'page_0'
self.story_data = {"page_0": {
"novel_content": "抱歉,您上次阅读的小说文件丢失,请点击右上角展开小说列表,重新选择要阅读的小说",
"option_list": [
"1.抱歉,您上次阅读的小说文件丢失,请点击右上角展开小说列表,重新选择要阅读的小说"
],
"new_page_list": [
"page_0"
]
}
}
with open(path, "r", encoding="utf-8") as f:
self.story_data = js.load(f)
print('故事内容加载成功 ', self.novel_title)
def load_page_data(self):
try:
# 加载这一页的内容
self.page_data = self.story_data[self.current_page]
print('\n本页内容加载成功 ', self.novel_title, ' ', self.current_page, '\n', self.page_data)
# 保存阅读进度
self.save_reading_progress__page()
except KeyError:
# 页面内容不存在时的异常处理
messagebox.showerror('错误', '该页内容加载失败,因为对应文件不存在\n即将自动回撤至上一页')
print('错误:页码', self.current_page, '不存在,无法加载故事数据')
# 修改页码记忆列表并更新页码
del self.page_memory[-1]
print('修改后的self.page_memory:', self.page_memory)
self.current_page = self.page_memory[-1]
return
def load_novel_list(self):
path = 'novel_content_storage/novel_list.json'
with open(path, 'r', encoding='utf-8') as json_file:
self.novel_list = js.load(json_file)
print('小说标题列表文件加载成功 ', self.novel_list)
def save_reading_progress__page(self):
print('\n开始存储阅读进度 ', self.novel_title, ' ', self.current_page)
path = 'novel_content_storage/reading_progress.json'
# 读取现有数据并修改
with open(path, 'r', encoding='utf-8') as f:
progress_data = js.load(f)
if progress_data[self.novel_title][-1] == self.current_page:
print('页面未变更,无需修改')
return
progress_data[self.novel_title].append(self.current_page)
print('修改成功 ', progress_data)
#存储修改后的数据
with open(path, 'w', encoding='utf-8') as f:
js.dump(progress_data, f)
print('存储成功 ', progress_data)
# 修改self.page_memory列表
self.page_memory.append(self.current_page)
print('修改后的self.page_memory:', self.page_memory)
def save_reading_progress__novel(self):
print('开始存储阅读进度 ', self.novel_title, ' ', self.current_page)
path = 'novel_content_storage/reading_progress.json'
# 读取现有数据并修改
with open(path, 'r', encoding='utf-8') as f:
progress_data = js.load(f)
progress_data['last_novel'] = self.novel_title
print('修改成功 ', progress_data)
# 存储修改后的数据
with open(path, 'w', encoding='utf-8') as f:
js.dump(progress_data, f)
print('存储成功 ', progress_data)
def renew_page_content(self):
# 更新当前页面所需的故事数据
self.load_page_data()
# 更新正文内容
self.novel_content.set(self.page_data['novel_content'])
# 更新选项列表和选项菜单
# if self.trace_op:
# self.option_menu_manager.selected_option.trace_remove(("write",), self.trace_op)
self.option_list = self.page_data['option_list']
self.option_menu_manager.renew_option_menu(self.option_list)
# 先移除再重新添加追踪,防止正常加载过程中报错
# self.trace_op = self.option_menu_manager.selected_option.trace_add("write", self.react_to_selected_option)
def react_to_selected_novel(self, *args):
#try:
# 获取用户选择的小说的标题
novel_title_backup = self.novel_title
self.novel_title = self.option_menu_manager.selected_novel.get()
if not os.path.isfile(f'novel_content_storage/{self.novel_title}.json'):
print('错误:文件 ', self.novel_title, '.json 不存在,无法加载故事数据')
messagebox.showerror('错误',f'《{self.novel_title}》的小说文件丢失,无法加载')
# 把小说标题改回去
self.novel_title = novel_title_backup
self.option_menu_manager.selected_novel.set(self.novel_title)
return
# 保存小说选择
self.save_reading_progress__novel()
# 重新加载故事内容
self.load_reading_progress()
self.load_story_data()
# 先移除再重新添加追踪,防止正常加载过程中报错
# if self.trace_op:
# self.option_menu_manager.selected_option.trace_remove(("write",), self.trace_op)
# 刷新页面内容
self.renew_page_content()
# except FileNotFoundError:
# # 文件加载路径不存在的异常处理
# print('错误:文件 ', self.novel_title, '.json 不存在,无法加载故事数据')
# messagebox.showerror('错误', f'《{self.novel_title}》的小说文件丢失,无法加载')
# # 把小说标题改回去
# self.novel_title = novel_title_backup
# self.option_menu_manager.selected_novel.set(self.novel_title)
# return
def react_to_selected_option(self, *args):
# 获取用户选项对应的索引
selected_option = self.option_menu_manager.selected_option.get()
# 如果用户没选择选项的异常处理
if not selected_option in self.option_list:
# messagebox.showerror('错误','请先点击“点击此处展开选项列表”以选择选项')
return
option_index = self.option_list.index(selected_option)
# 根据索引更新页面内容文件的页码
new_page_list = self.page_data['new_page_list']
self.current_page = new_page_list[option_index]
# 先移除再重新添加追踪,防止正常加载过程中报错
# if self.trace_op:
# self.option_menu_manager.selected_option.trace_remove(("write",), self.trace_op)
# 刷新页面内容
self.renew_page_content()
def go_back_to_last_page(self):
print('开始后撤阅读进度 ', self.novel_title, ' ', self.current_page)
path = 'novel_content_storage/reading_progress.json'
# 读取现有数据并去除页码记忆中最后一个页码
with open(path, 'r', encoding='utf-8') as f:
progress_data = js.load(f)
print('开始修改 ',progress_data)
# 不存在上一页时的处理
if len(progress_data[self.novel_title]) == 1:
print('不可修改:页码记录中仅有一个页码')
messagebox.showerror('错误','不存在上一页的阅读记录,无法返回上一页')
return
del progress_data[self.novel_title][-1]
print('修改成功 ', progress_data)
# 存储修改后的数据
with open(path, 'w', encoding='utf-8') as f:
js.dump(progress_data, f)
print('存储成功 ', progress_data)
# 修改页码记忆列表并更新页码
del self.page_memory[-1]
print('修改后的self.page_memory:', self.page_memory)
self.current_page = self.page_memory[-1]
# 刷新页面内容
self.renew_page_content()
最新发布