Python实例题:基于 Python 的简单电子词典
目录
Python实例题
题目
要求:
解题思路:
代码实现:
Python实例题
题目
基于 Python 的简单电子词典
要求:
- 使用 Python 构建一个电子词典,支持以下功能:
- 英汉 / 汉英双向翻译
- 单词发音功能
- 单词记忆功能(收藏、标记重点)
- 历史记录功能
- 支持离线词典(包含常用词汇)
- 使用
tkinter
构建图形用户界面。 - 实现单词查询和基本的词典功能。
解题思路:
- 使用
tkinter
构建界面,包括查询框、结果显示区和功能按钮。 - 设计词典数据结构,存储英汉 / 汉英词汇。
- 实现基本的查询、发音和记忆功能。
代码实现:
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import json
import random
import threading
import os
from datetime import datetimeclass DictionaryApp:def __init__(self, root):self.root = rootself.root.title("电子词典")self.root.geometry("700x500")# 词典数据self.dictionary = self._load_dictionary()# 收藏夹self.favorites = self._load_favorites()# 历史记录self.history = self._load_history()# 当前查询的单词self.current_word = None# 创建主界面self.create_main_window()def _load_dictionary(self):"""加载词典数据"""# 这里使用一个简化的词典示例# 实际应用中可以使用更大的词典文件return {"apple": ["苹果", "苹果树"],"book": ["书", "书籍", "本子"],"computer": ["计算机", "电脑"],"love": ["爱", "爱情", "喜欢"],"friend": ["朋友", "友人"],"hello": ["你好", "喂"],"world": ["世界", "地球"],"python": ["蟒蛇", "Python编程语言"],"code": ["代码", "编码", "密码"],"学习": ["study", "learn"],"中国": ["China", "Chinese"],"北京": ["Beijing", "Peking"],"英语": ["English", "language"],"词典": ["dictionary", "lexicon"]}def _load_favorites(self):"""加载收藏夹"""try:if os.path.exists("favorites.json"):with open("favorites.json", "r", encoding="utf-8") as f:return json.load(f)except Exception as e:print(f"加载收藏夹失败: {e}")return []def _save_favorites(self):"""保存收藏夹"""try:with open("favorites.json", "w", encoding="utf-8") as f:json.dump(self.favorites, f, ensure_ascii=False, indent=2)except Exception as e:print(f"保存收藏夹失败: {e}")def _load_history(self):"""加载历史记录"""try:if os.path.exists("history.json"):with open("history.json", "r", encoding="utf-8") as f:return json.load(f)except Exception as e:print(f"加载历史记录失败: {e}")return []def _save_history(self):"""保存历史记录"""try:with open("history.json", "w", encoding="utf-8") as f:json.dump(self.history, f, ensure_ascii=False, indent=2)except Exception as e:print(f"保存历史记录失败: {e}")def create_main_window(self):"""创建主窗口"""# 创建顶部框架 - 查询区域top_frame = ttk.Frame(self.root, padding=10)top_frame.pack(fill=tk.X)# 查询框ttk.Label(top_frame, text="查询:").pack(side=tk.LEFT, padx=5)self.query_var = tk.StringVar()query_entry = ttk.Entry(top_frame, textvariable=self.query_var, width=40)query_entry.pack(side=tk.LEFT, padx=5)query_entry.bind("<Return>", self.search_word)# 查询按钮ttk.Button(top_frame, text="查询", command=self.search_word).pack(side=tk.LEFT, padx=5)# 翻译方向ttk.Label(top_frame, text="方向:").pack(side=tk.LEFT, padx=5)self.direction_var = tk.StringVar(value="英汉")direction_combo = ttk.Combobox(top_frame, textvariable=self.direction_var, values=["英汉", "汉英"], width=5)direction_combo.pack(side=tk.LEFT, padx=5)# 创建中间框架 - 结果显示middle_frame = ttk.Frame(self.root, padding=10)middle_frame.pack(fill=tk.BOTH, expand=True)# 创建结果显示区域result_frame = ttk.LabelFrame(middle_frame, text="查询结果")result_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)self.result_text = scrolledtext.ScrolledText(result_frame, wrap=tk.WORD, state=tk.DISABLED)self.result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)# 创建历史记录区域history_frame = ttk.LabelFrame(middle_frame, text="历史记录")history_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)self.history_list = tk.Listbox(history_frame)self.history_list.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)self.history_list.bind("<Double-1>", self.on_history_select)# 更新历史记录显示self.update_history_display()# 创建底部框架 - 功能按钮bottom_frame = ttk.Frame(self.root, padding=10)bottom_frame.pack(fill=tk.X)ttk.Button(bottom_frame, text="发音", command=self.pronounce_word).pack(side=tk.LEFT, padx=5)ttk.Button(bottom_frame, text="收藏", command=self.toggle_favorite).pack(side=tk.LEFT, padx=5)ttk.Button(bottom_frame, text="查看收藏", command=self.show_favorites).pack(side=tk.LEFT, padx=5)ttk.Button(bottom_frame, text="清空历史", command=self.clear_history).pack(side=tk.LEFT, padx=5)def search_word(self, event=None):"""搜索单词"""word = self.query_var.get().strip()if not word:messagebox.showinfo("提示", "请输入要查询的单词")return# 更新当前单词self.current_word = word# 清空结果显示self.result_text.config(state=tk.NORMAL)self.result_text.delete(1.0, tk.END)# 查询词典direction = self.direction_var.get()translations = []if direction == "英汉" and word.lower() in self.dictionary:translations = self.dictionary[word.lower()]elif direction == "汉英" and word in self.dictionary:translations = self.dictionary[word]# 显示结果if translations:self.result_text.insert(tk.END, f"{word}\n\n")self.result_text.insert(tk.END, "翻译:\n")for i, trans in enumerate(translations, 1):self.result_text.insert(tk.END, f"{i}. {trans}\n")else:self.result_text.insert(tk.END, f"未找到单词 '{word}' 的翻译。")# 禁用编辑self.result_text.config(state=tk.DISABLED)# 添加到历史记录timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")self.history.append({"word": word, "timestamp": timestamp, "direction": direction})# 限制历史记录数量if len(self.history) > 100:self.history = self.history[-100:]# 保存历史记录self._save_history()# 更新历史记录显示self.update_history_display()def update_history_display(self):"""更新历史记录显示"""# 清空历史记录列表self.history_list.delete(0, tk.END)# 添加历史记录for item in reversed(self.history):direction = "英汉" if item["direction"] == "英汉" else "汉英"self.history_list.insert(tk.END, f"{item['timestamp']} - {item['word']} ({direction})")def on_history_select(self, event):"""处理历史记录选择"""selection = self.history_list.curselection()if not selection:returnindex = len(self.history) - selection[0] - 1if 0 <= index < len(self.history):item = self.history[index]self.query_var.set(item["word"])self.direction_var.set(item["direction"])self.search_word()def pronounce_word(self):"""发音功能"""if not self.current_word:messagebox.showinfo("提示", "请先查询一个单词")return# 实际应用中可以使用语音合成库实现发音功能# 这里仅显示提示信息threading.Thread(target=self._simulate_pronunciation).start()def _simulate_pronunciation(self):"""模拟发音"""self.status_var.set(f"正在发音: {self.current_word}")# 模拟发音过程time.sleep(1)self.status_var.set("就绪")def toggle_favorite(self):"""切换收藏状态"""if not self.current_word:messagebox.showinfo("提示", "请先查询一个单词")returnif self.current_word in self.favorites:self.favorites.remove(self.current_word)messagebox.showinfo("提示", f"已取消收藏单词 '{self.current_word}'")else:self.favorites.append(self.current_word)messagebox.showinfo("提示", f"已收藏单词 '{self.current_word}'")# 保存收藏夹self._save_favorites()def show_favorites(self):"""显示收藏夹"""# 创建新窗口favorites_window = tk.Toplevel(self.root)favorites_window.title("收藏夹")favorites_window.geometry("400x400")# 创建列表框favorites_list = tk.Listbox(favorites_window)favorites_list.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)# 添加收藏的单词for word in self.favorites:favorites_list.insert(tk.END, word)# 双击查询单词def on_favorite_select(event):selection = favorites_list.curselection()if selection:word = favorites_list.get(selection[0])self.query_var.set(word)self.search_word()favorites_window.destroy()favorites_list.bind("<Double-1>", on_favorite_select)# 添加删除按钮def remove_selected():selection = favorites_list.curselection()if selection:word = favorites_list.get(selection[0])if word in self.favorites:self.favorites.remove(word)favorites_list.delete(selection[0])self._save_favorites()button_frame = ttk.Frame(favorites_window)button_frame.pack(fill=tk.X, padx=10, pady=10)ttk.Button(button_frame, text="删除选中", command=remove_selected).pack(side=tk.RIGHT)def clear_history(self):"""清空历史记录"""if messagebox.askyesno("确认", "确定要清空所有历史记录吗?"):self.history = []self._save_history()self.update_history_display()if __name__ == "__main__":root = tk.Tk()app = DictionaryApp(root)root.mainloop()