Tkinter帮助查看器

4 投票
3 回答
4394 浏览
提问于 2025-04-15 17:32

我有一个简单的Tkinter应用程序,使用Python编写。我想给它添加帮助文档;有什么简单的方法可以把帮助查看器集成到这个应用里吗?最好是跨平台的(虽然我主要在Windows上使用)?

我可以想象用普通的HTML来写帮助文档。

3 个回答

1

我发现一个叫做tkinterweb的包(https://pypi.org/project/tkinterweb/)提供了一个HtmlFrame,可以用来显示HTML内容。我想使用markdown格式,而Python-Markdown(https://python-markdown.github.io/)可以把markdown转换成HTML,所以我就同时用了这两个工具。它们都可以通过pip安装。

pip install markdown
pip install tkinterweb

这里有一些示例代码:

import tkinter as tk
from tkinterweb import HtmlFrame
import markdown
import tempfile

root = tk.Tk()
frame = HtmlFrame(root, messages_enabled=False)

m_text = (
    'Markdown sample (https://en.wikipedia.org/wiki/Markdown#Examples)\n'
    '\n'
    'Heading\n'
    '=======\n'
    '\n'
    'Sub-heading\n'
    '-----------\n'
    '\n'
    '# Alternative heading #\n'
    '\n'
    'Paragraphs are separated\n'
    'by a blank line.\n'
    '\n'
    'Two spaces at the end of a line  \n'
    'produce a line break.\n'
    '\n'
    'Text attributes _italic_, **bold**, `monospace`.\n'
    '\n'
    'Horizontal rule:\n'
    '\n'
    '---\n'
    '\n'
    'Bullet lists nested within numbered list:\n'
    '\n'
    '  1. fruits\n'
    '     * apple\n'
    '     * banana\n'
    '  2. vegetables\n'
    '     - carrot\n'
    '     - broccoli\n'
    '\n'
    'A [link](http://example.com).\n'
    '\n'
    '![Image](Icon-pictures.png "icon")\n'
    '\n'
    '> Markdown uses email-style\n'
    'characters for blockquoting.\n'
    '>\n'
    '> Multiple paragraphs need to be prepended individually.\n'
    '\n'
    'Most inline <abbr title="Hypertext Markup Language">HTML</abbr> is supported.\n'
)

'''
# normally read the text from a file
with open('sample.md', 'r') as f:
    m_text = f.read()
'''
m_html = markdown.markdown(m_text)
temp_html = tempfile.NamedTemporaryFile(mode='w')
f = open(temp_html.name, 'w')
f.write(m_html)
f.flush()
frame.load_file(f.name)
frame.pack(fill="both", expand=True)
root.mainloop()

如果你把用markdown生成的HTML和维基百科上的内容进行对比,你会发现它的效果非常好。不过,HtmlFrame的效果就没那么理想了,但对于基本的文档来说,应该还是够用的。

更新:我发现tkinterweb是基于tkhtml的,所以这个解决方案也存在一些其他人提到的缺陷。

2

你可以继续用HTML写东西,然后用像这个这样的工具:Tkhtml,它能很好地显示HTML,而且比较轻便。 :)

这里还有Python的封装。希望这对你有帮助。

3

或者直接打开一个外部的网页浏览器,可以使用标准库里的 webbrowser 模块。

import webbrowser
webbrowser.open('/path/to/help/file.html')

如果你想写文档,可以看看 sphinx

撰写回答