Python结合Tkinter实现简单的论语阅读器

 更新时间:2026年06月14日 09:07:30   作者:金銀銅鐵  
这篇文章主要为大家详细介绍了Python如何结合Tkinter实现简单的论语阅读器,文章的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以了解下

背景

TkDocs tutorial 里介绍了 Tkinter,其中有 A First (Real) Example 一文,这篇文章里有一个使用Tkinter 生成图形化界面的简单例子。我想在那篇文章的基础上实战一下,于是想到可以写一个简单的《论语》阅读器,但是《论语》的篇幅有点长,于是又把目标缩小到《论语》第一章,也就是《学而》的阅读器。

完整代码

完整的代码如下

from tkinter import *
from tkinter import ttk
import textwrap

root = Tk()
root.title("論語 -> 學而")

def create_frame(row, col):
    frame = ttk.Frame(root, padding=(3, 3, 12, 12))
    frame.grid(column=col, row=row, sticky=(N, W, E, S))
    frame['borderwidth'] = 2
    frame['relief'] = 'sunken'
    return frame

button_frame = create_frame(0, 0)
chinese_text_frame = create_frame(0, 1)
english_text_frame = create_frame(0, 2)

chinese_label = ttk.Label(chinese_text_frame, text="")
chinese_label.grid(column=0, row=0, sticky=W)

english_label = ttk.Label(english_text_frame, text="")
english_label.grid(column=0, row=0, sticky=W)

button_dict = {}
section_num = 1
n = 4
section_num_lower_bound = 1
section_num_upper_bound = 16

chinese_text = [
    "",
    "子曰:「學而時習之,不亦說乎?有朋自遠方來,不亦樂乎?人不知而不慍,不亦君子乎?」",
    "有子曰:「其為人也孝弟,而好犯上者,鮮矣;不好犯上,而好作亂者,未之有也。君子務本,本立而道生。孝弟也者,其為仁之本與!」",
    "子曰:「巧言令色,鮮矣仁!」",
    "曾子曰:「吾日三省吾身:為人謀而不忠乎?與朋友交而不信乎?傳不習乎?」",
    "子曰:「道千乘之國:敬事而信,節用而愛人,使民以時。」",
    "子曰:「弟子入則孝,出則弟,謹而信,汎愛眾,而親仁。行有餘力,則以學文。」",
    "子夏曰:「賢賢易色,事父母能竭其力,事君能致其身,與朋友交言而有信。雖曰未學,吾必謂之學矣。」",
    "子曰:「君子不重則不威,學則不固。主忠信,無友不如己者,過則勿憚改。」",
    "曾子曰:「慎終追遠,民德歸厚矣。」",
    "子禽問於子貢曰:「夫子至於是邦也,必聞其政,求之與?抑與之與?」子貢曰:「夫子溫、良、恭、儉、讓以得之。夫子之求之也,其諸異乎人之求之與?」",
    "子曰:「父在,觀其志;父沒,觀其行;三年無改於父之道,可謂孝矣。」",
    "有子曰:「禮之用,和為貴。先王之道斯為美,小大由之。有所不行,知和而和,不以禮節之,亦不可行也。」",
    "有子曰:「信近於義,言可復也;恭近於禮,遠恥辱也;因不失其親,亦可宗也。」",
    "子曰:「君子食無求飽,居無求安,敏於事而慎於言,就有道而正焉,可謂好學也已。」",
    "子貢曰:「貧而無諂,富而無驕,何如?」子曰:「可也。未若貧而樂,富而好禮者也。」子貢曰:「《詩》云:『如切如磋,如琢如磨。』其斯之謂與?」子曰:「賜也,始可與言詩已矣!告諸往而知來者。」",
    "子曰:「不患人之不己知,患不知人也。」"
]

english_text = [
    "",
    '''The Master said, "Is it not pleasant to learn with a constant perseverance and application? Is it not delightful to have friends coming from distant quarters? Is he not a man of complete virtue, who feels no discomposure though men may take no note of him?"''',
    '''The philosopher You said, "They are few who, being filial and fraternal, are fond of offending against their superiors. There have been none, who, not liking to offend against their superiors, have been fond of stirring up confusion. The superior man bends his attention to what is radical. That being established, all practical courses naturally grow up. Filial piety and fraternal submission! - are they not the root of all benevolent actions?"''',
    '''The Master said, "Fine words and an insinuating appearance are seldom associated with true virtue."''',
    '''The philosopher Zeng said, "I daily examine myself on three points: whether, in transacting business for others, I may have been not faithful; whether, in intercourse with friends, I may have been not sincere; whether I may have not mastered and practiced the instructions of my teacher."''',
    '''The Master said, "To rule a country of a thousand chariots, there must be reverent attention to business, and sincerity; economy in expenditure, and love for men; and the employment of the people at the proper seasons."''',
    '''The Master said, "A youth, when at home, should be filial, and, abroad, respectful to his elders. He should be earnest and truthful. He should overflow in love to all, and cultivate the friendship of the good. When he has time and opportunity, after the performance of these things, he should employ them in polite studies."''',
    '''Zi Xia said, "If a man withdraws his mind from the love of beauty, and applies it as sincerely to the love of the virtuous; if, in serving his parents, he can exert his utmost strength; if, in serving his prince, he can devote his life; if, in his intercourse with his friends, his words are sincere - although men say that he has not learned, I will certainly say that he has."''',
    '''The Master said, "If the scholar be not grave, he will not call forth any veneration, and his learning will not be solid. Hold faithfulness and sincerity as first principles. Have no friends not equal to yourself. When you have faults, do not fear to abandon them."''',
    '''The philosopher Zeng said, "Let there be a careful attention to perform the funeral rites to parents, and let them be followed when long gone with the ceremonies of sacrifice - then the virtue of the people will resume its proper excellence."''',
    '''Zi Qin asked Zi Gong, saying, "When our master comes to any country, he does not fail to learn all about its government. Does he ask his information? or is it given to him?" Zi Gong said, "Our master is benign, upright, courteous, temperate, and complaisant and thus he gets his information. The master's mode of asking information! - is it not different from that of other men?"''',
    '''The Master said, "While a man's father is alive, look at the bent of his will; when his father is dead, look at his conduct. If for three years he does not alter from the way of his father, he may be called filial."''',
    '''The philosopher You said, "In practicing the rules of propriety, a natural ease is to be prized. In the ways prescribed by the ancient kings, this is the excellent quality, and in things small and great we follow them. Yet it is not to be observed in all cases. If one, knowing how such ease should be prized, manifests it, without regulating it by the rules of propriety, this likewise is not to be done."''',
    '''The philosopher You said, "When agreements are made according to what is right, what is spoken can be made good. When respect is shown according to what is proper, one keeps far from shame and disgrace. When the parties upon whom a man leans are proper persons to be intimate with, he can make them his guides and masters."''',
    '''The Master said, "He who aims to be a man of complete virtue in his food does not seek to gratify his appetite, nor in his dwelling place does he seek the appliances of ease; he is earnest in what he is doing, and careful in his speech; he frequents the company of men of principle that he may be rectified - such a person may be said indeed to love to learn."''',
    '''Zi Gong said, "What do you pronounce concerning the poor man who yet does not flatter, and the rich man who is not proud?" The Master replied, "They will do; but they are not equal to him, who, though poor, is yet cheerful, and to him, who, though rich, loves the rules of propriety." Zi Gong replied, "It is said in the Book of Poetry, 'As you cut and then file, as you carve and then polish.' - The meaning is the same, I apprehend, as that which you have just expressed." The Master said, "With one like Ci, I can begin to talk about the odes. I told him one point, and he knew its proper sequence."''',
    '''The Master said, "I will not be afflicted at men's not knowing me; I will be afflicted that I do not know men."'''
]

def adjust_chinese_text(text):
    return textwrap.fill(text, width=30)

def adjust_english_text(text):
    return textwrap.fill(text)

def ensure_button_enabled(button):
    if button.instate(['disabled']):
        button.state(['!disabled'])

def ensure_button_disabled(button):
    if button.instate(['!disabled']):
        button.state(['disabled'])

def update_text():
    chinese_label['text'] = adjust_chinese_text(chinese_text[section_num])
    english_label['text'] = adjust_english_text(english_text[section_num])

def update_prev_section_button_state():
    if section_num == section_num_lower_bound:
        ensure_button_disabled(button_dict['prev_section'])
    else:
        ensure_button_enabled(button_dict['prev_section'])

def update_next_section_button_state():
    if section_num == section_num_upper_bound:
        ensure_button_disabled(button_dict['next_section'])
    else:
        ensure_button_enabled(button_dict['next_section'])

def update_section_button_state():
    for i in range(section_num_lower_bound, section_num_upper_bound + 1):
        if i == section_num:
            ensure_button_disabled(button_dict[i])
        else:
            ensure_button_enabled(button_dict[i])

def update_button_state():
    update_prev_section_button_state()
    update_next_section_button_state()
    update_section_button_state()

def update():
    update_text()
    update_button_state()

def move_to_section(target):
    global section_num
    section_num = target
    update()

def add_button(row, col):
    curr_section_num = row * n + col + 1
    return ttk.Button(button_frame, text=str(curr_section_num), command=lambda: move_to_section(curr_section_num))

for row in range(n):
    for col in range(n):
        button = add_button(row, col)
        button.grid(column=col, row=row, sticky='E')
        section = row * n + col + 1
        button_dict[section] = button

def move_to_prev_section():
    global section_num
    section_num -= 1
    update()

def move_to_next_section():
    global section_num
    section_num += 1
    update()

prev_section_button = ttk.Button(button_frame, text="<<", command=move_to_prev_section)
prev_section_button.grid(column=1, row=n, sticky=W)

next_section_button = ttk.Button(button_frame, text=">>", command=move_to_next_section)
next_section_button.grid(column=2, row=n, sticky=E)

button_dict['prev_section'] = prev_section_button
button_dict['next_section'] = next_section_button

update()

root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
button_frame.columnconfigure(2, weight=1)
for child in button_frame.winfo_children(): 
    child.grid_configure(padx=5, pady=5)

root.mainloop()

需要解决哪些问题

在 中國哲學書電子化計劃 网站可以看到 《論語》 的全文。其中第一章的链接是 《學而》。我们的目标是,用Tkinter 生成简单的图形化界面,以便用户阅读《學而》中的内容。

章节问题

在 《學而》 中,可以看到《學而》共分为 16 个小节,所以可以在图形化界面中展示 16 个按钮,点击任意按钮后,展示对应那一小节的中英文内容。由于只有 16小节,我手动从 《學而》 页面把内容复制了下来,并将其拆分成对应的 list\ (完整的内容有点长,我在下方用 ... 表示略去的文字)

chinese_text = [
    "",
    "子曰:「學而時習之,不亦說乎?有朋自遠方來,不亦樂乎?人不知而不慍,不亦君子乎?」",
    ...
    "子曰:「不患人之不己知,患不知人也。」"
]

english_text = [
    "",
    '''The Master said, "Is it not pleasant to learn with a constant perseverance and application? Is it not delightful to have friends coming from distant quarters? Is he not a man of complete virtue, who feels no discomposure though men may take no note of him?"''',
    ...
    '''The Master said, "I will not be afflicted at men's not knowing me; I will be afflicted that I do not know men."'''
]

换行问题

有的小节的文字比较长(无论是原文还是翻译为英文后)。所以需要在合适的地方进行换行。我在 trae 的帮助下,了解到Python 中有 textwrap 模块适合处理这样的问题。我在 trae 提供的示例代码基础上,完成了这部分的逻辑 

def adjust_chinese_text(text):
    return textwrap.fill(text, width=30)

def adjust_english_text(text):
    return textwrap.fill(text

运行效果

请将完整的代码(上文已提供)保存为 xue_er.py。使用下方的命令可以运行 xue_er.py

python3 xue_er.py

运行效果如下图所示

一开始停留在第 1 小节。点击按钮 1515,会看到如下的效果  (第 15 小节的内容比较长)

此时点击 >> 按钮,会来到第 16小节 

点击其他按钮的效果也是类似的,就不赘述了

《論語》 是古书,其文字没有版权问题。《論語》 页面上所展示的英文翻译,似乎是很久以前由某个外国人完成的,应该也没有版权保护了。trae 协助我完成了部分代码,那些代码很普通,即使没有它的帮助,也不难写出来(但应该会多花费不少时间)。

到此这篇关于Python结合Tkinter实现简单的论语阅读器的文章就介绍到这了,更多相关Python Tkinter论语阅读器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python使用PySimpleGUI和Pygame编写一个MP3播放器

    Python使用PySimpleGUI和Pygame编写一个MP3播放器

    这篇文章主要为大家详细介绍了Python如何使用PySimpleGUI和Pygame编写一个简单的MP3播放器,文中的示例代码讲解详细,感兴趣的小伙伴可以学习一下
    2023-11-11
  • 快速一键生成Python爬虫请求头

    快速一键生成Python爬虫请求头

    这篇文章主要介绍了如何快速一键生成Python爬虫请求头,帮助大家更好的理解和学习使用python爬虫,感兴趣的朋友可以了解下
    2021-03-03
  • 详解如何利用Numpy生成各种各样的数组

    详解如何利用Numpy生成各种各样的数组

    Numpy提供了多种函数和方法,可以方便地生成不同形状和类型的数组,今天小编就带大家学习一下如何利用 Numpy 生成各种各样的数组吧
    2023-07-07
  • Python使用Flask-SQLAlchemy连接数据库操作示例

    Python使用Flask-SQLAlchemy连接数据库操作示例

    这篇文章主要介绍了Python使用Flask-SQLAlchemy连接数据库操作,简单介绍了flask、Mysql-Python以及Flask-SQLAlchemy的安装方法,并结合实例形式分析了基于Flask-SQLAlchemy的数据库连接相关操作技巧,需要的朋友可以参考下
    2018-08-08
  • Python使用Gzip解压的示例详解

    Python使用Gzip解压的示例详解

    Python 中构建了许多用于压缩和解压缩目的的库,本文为大家介绍的Gzip库就是一种流行的数据压缩工具,下面我们就来看看如何使用 gzip 解压缩来解压缩压缩内容吧
    2023-11-11
  • 深入了解Python中描述器的使用

    深入了解Python中描述器的使用

    Python描述器是Python编程语言中的一个重要特性,它提供了一种灵活且强大的机制来控制属性访问行为。在本文中,我们将详细介绍Python描述器的概念、实现方式以及如何使用Python描述器来增强我们的Python程序
    2023-03-03
  • Python学习_几种存取xls/xlsx文件的方法总结

    Python学习_几种存取xls/xlsx文件的方法总结

    今天小编就为大家分享一篇Python学习_几种存取xls/xlsx文件的方法总结,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • python celery分布式任务队列的使用详解

    python celery分布式任务队列的使用详解

    这篇文章主要介绍了python celery分布式任务队列的使用详解,Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考虑使用celery,需要的朋友可以参考下
    2019-07-07
  • python寻找list中最大值、最小值并返回其所在位置的方法

    python寻找list中最大值、最小值并返回其所在位置的方法

    今天小编就为大家分享一篇python寻找list中最大值、最小值并返回其所在位置的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • Python机器学习算法之k均值聚类(k-means)

    Python机器学习算法之k均值聚类(k-means)

    这篇文章主要为大家详细介绍了Python机器学习算法之k均值聚类,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02

最新评论