从 tkinter 中的文本小部件复制格式化文本

2024-03-03

我正在使用 tkinter 在 Python 中开发 APA 引文制作器。我使用文本小部件在生成引文后显示引文,但每当我复制文本(目前使用 ctrl+c 快捷方式)时,它都会丢失其格式。是否有某种方法可以从文本小部件复制格式化文本(例如斜体)而不是未格式化的文本?


要将格式化文本复制到剪贴板,您需要 python 和支持文本格式化的系统剪贴板之间的接口。我已经发现klembord https://pypi.org/project/klembord/这应该适用于 Linux 和 Windows(Mac 用户可能可以采用以下解决方案富施乐 https://pypi.org/project/richxerox/).

这个想法是(1)将格式化文本从文本小部件转换为 html,然后(2)将其添加到剪贴板:

  1. With text.dump(index1, index2, tag=True, text=True)可以从小部件中检索文本和标签。它返回一个类似的列表(这是下面示例中小部件的内容):

     [('text', 'Author et al. (2012). The title of the article. ', '1.0'),
      ('tagon', 'italic', '1.48'),
      ('text', 'Journal Name', '1.48'),
      ('tagoff', 'italic', '1.60'),
      ('text', ', ', '1.60'),
      ('tagon', 'bold', '1.62'),
      ('text', '2', '1.62'),
      ('tagoff', 'bold', '1.63'),
      ('text', '(599), 1–5.', '1.63'),
      ('text', '\n', '1.74')]
    

    所以很容易将每个关联起来('tagon/off', tagname)使用字典与相应的 html 标签配对,并将小部件内容转换为 html。

  2. klembord.set_with_rich_text(txt, rich_txt)把字符串txt及其在剪贴板中的 html 格式的等效内容。

这是一个完整的示例(在 Linux 中测试,我能够从文本小部件复制文本并将其粘贴到带有格式的文字处理器中):

import tkinter as tk
import klembord

root = tk.Tk()
text = tk.Text(root)
text.pack(fill='both', expand=True)

text.tag_configure('italic', font='TkDefaultFont 9 italic')
text.tag_configure('bold', font='TkDefaultFont 9 bold')

TAG_TO_HTML = {
    ('tagon', 'italic'): '<i>',
    ('tagon', 'bold'): '<b>',
    ('tagoff', 'italic'): '</i>',
    ('tagoff', 'bold'): '</b>',
}

def copy_rich_text(event):
    try:
        txt = text.get('sel.first', 'sel.last')
    except tk.TclError:
        # no selection
        return "break"
    content = text.dump('sel.first', 'sel.last', tag=True, text=True)
    html_text = []
    for key, value, index in content:
        if key == "text":
            html_text.append(value)
        else:
            html_text.append(TAG_TO_HTML.get((key, value), ''))
    klembord.set_with_rich_text(txt, ''.join(html_text))
    return "break"  # prevent class binding to be triggered

text.bind('<Control-c>', copy_rich_text)

text.insert("1.0", "Author et al. (2012). The title of the article. ")
text.insert("end", "Journal Name", "italic")
text.insert("end", ", ")
text.insert("end", "2", "bold")
text.insert("end", "(599), 1–5.")

root.mainloop()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 tkinter 中的文本小部件复制格式化文本 的相关文章

随机推荐