python程序5:一个电子书阅读器

今天写一个电子书阅读器,用到的依然是tkinter模块,实现文本的读取,退出,更改文字大小,颜色,插入书签,跳转书签等功能。

实现代码如下:

import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import simpledialog
import pickle

class EbookReader(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title("Ebook Reader")
        self.pack()

        self.create_widgets()

    def create_widgets(self):
        # 文件菜单
        menubar = tk.Menu(self.master)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_file)
        menubar.add_cascade(label="File", menu=filemenu)

        # 文本框
        self.text = tk.Text(self, wrap="word")
        self.text.pack(expand=True, fill="both")

        # 书签菜单
        bookmarkmenu = tk.Menu(menubar, tearoff=0)
        bookmarkmenu.add_command(label="Add Bookmark", command=self.add_bookmark)
        bookmarkmenu.add_command(label="Go to Bookmark", command=self.go_to_bookmark)
        menubar.add_cascade(label="Bookmark", menu=bookmarkmenu)

        # 字体菜单
        fontmenu = tk.Menu(menubar, tearoff=0)
        fontmenu.add_command(label="Increase Font Size", command=self.increase_font_size)
        fontmenu.add_command(label="Decrease Font Size", command=self.decrease_font_size)
        fontmenu.add_command(label="Change Font Color", command=self.change_font_color)
        menubar.add_cascade(label="Font", menu=fontmenu)

        self.master.config(menu=menubar)
        # 打开文件
    def open_file(self):
        filepath = filedialog.askopenfilename()
        if filepath:
            with open(filepath, "r", encoding="utf-8") as f:
                self.text.delete("1.0", "end")
                self.text.insert("end", f.read())
        # 保存文件
    def save_file(self):
        filepath = filedialog.asksaveasfilename()
        if filepath:
            with open(filepath, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", "end"))
        # 加入书签
    def add_bookmark(self):
        bookmark_name = simpledialog.askstring(title="Add Bookmark", prompt="Enter bookmark name:")
        if bookmark_name:
            self.text.tag_add(bookmark_name, "sel.first", "sel.last")
            bookmark_info = {"index": self.text.index("sel.first"), "name": bookmark_name}
            with open("bookmarks.pickle", "ab") as f:
                pickle.dump(bookmark_info, f)
        # 跳转书签
    def go_to_bookmark(self):
        with open("bookmarks.pickle", "rb") as f:
            bookmarks = []
            while True:
                try:
                    bookmark_info = pickle.load(f)
                    bookmarks.append(bookmark_info)
                except EOFError:
                    break
        bookmark_names = [bookmark["name"] for bookmark in bookmarks]
        selected_bookmark_name = simpledialog.askstring(title="Go to Bookmark", prompt="Enter bookmark name:",
                                                        autocomplete=bookmark_names)
        if selected_bookmark_name:
            try:
                selected_bookmark_info = next(bookmark for bookmark in bookmarks if bookmark["name"] == selected_bookmark_name)
                self.text.tag_remove("sel", "1.0", "end")
                self.text.tag_add("sel", selected_bookmark_info["index"])
                self.text.mark_set("insert", selected_bookmark_info["index"])
                self.text.see("insert")
            except StopIteration:
                messagebox.showerror(title="Error", message="Bookmark not found.")
        # 字体变大
    def increase_font_size(self):
        current_size = int(self.text.cget("font").split()[1])
        new_size = current_size + 2
        self.text.configure(font=("TkDefaultFont", new_size))
        # 字体变
    def decrease_font_size(self):
        current_size = int(self.text.cget("font").split()[1])
        new_size = current_size - 2
        if new_size > 0:
            self.text.configure(font=("TkDefaultFont", new_size))
        # 字体变色
    def change_font_color(self):
        color = tk.colorchooser.askcolor()[1]
        if color:
            self.text.configure(fg=color)

root = tk.Tk()
app = EbookReader(master=root)
app.mainloop()

运行尝试一下:

那么自己在pycharm里练习一下,并打包生成exe文件。

发表评论

zh_CNChinese