要将格式化文本复制到剪贴板,您需要 python 和支持文本格式化的系统剪贴板之间的接口。我发现klembord应该适用于 Linux 和 Windows(Mac 用户可能可以将以下解决方案改编为richxerox)。
\n这个想法是(1)将格式化文本从文本小部件转换为 html,然后(2)将其添加到剪贴板:
\ntext.dump(index1, index2, tag=True, text=True)可以从小部件中检索文本和标签。它返回一个类似的列表(这是下面示例中小部件的内容):
 [(\'text\', \'Author et al. (2012). The title of the article. \', \'1.0\'),\n  (\'tagon\', \'italic\', \'1.48\'),\n  (\'text\', \'Journal Name\', \'1.48\'),\n  (\'tagoff\', \'italic\', \'1.60\'),\n  (\'text\', \', \', \'1.60\'),\n  (\'tagon\', \'bold\', \'1.62\'),\n  (\'text\', \'2\', \'1.62\'),\n  (\'tagoff\', \'bold\', \'1.63\'),\n  (\'text\', \'(599), 1\xe2\x80\x935.\', \'1.63\'),\n  (\'text\', \'\\n\', \'1.74\')]\n因此,很容易(\'tagon/off\', tagname)使用字典将每一对与相应的 html 标签关联起来,并将小部件内容转换为 html。
klembord.set_with_rich_text(txt, rich_txt)将字符串txt及其 html 格式的等效项放入剪贴板中。
这是一个完整的示例(在 Linux 中测试,我能够从文本小部件复制文本并将其粘贴到带有格式的文字处理器中):
\nimport tkinter as tk\nimport klembord\n\nroot = tk.Tk()\ntext = tk.Text(root)\ntext.pack(fill=\'both\', expand=True)\n\ntext.tag_configure(\'italic\', font=\'TkDefaultFont 9 italic\')\ntext.tag_configure(\'bold\', font=\'TkDefaultFont 9 bold\')\n\nTAG_TO_HTML = {\n    (\'tagon\', \'italic\'): \'<i>\',\n    (\'tagon\', \'bold\'): \'<b>\',\n    (\'tagoff\', \'italic\'): \'</i>\',\n    (\'tagoff\', \'bold\'): \'</b>\',\n}\n\ndef copy_rich_text(event):\n    try:\n        txt = text.get(\'sel.first\', \'sel.last\')\n    except tk.TclError:\n        # no selection\n        return "break"\n    content = text.dump(\'sel.first\', \'sel.last\', tag=True, text=True)\n    html_text = []\n    for key, value, index in content:\n        if key == "text":\n            html_text.append(value)\n        else:\n            html_text.append(TAG_TO_HTML.get((key, value), \'\'))\n    klembord.set_with_rich_text(txt, \'\'.join(html_text))\n    return "break"  # prevent class binding to be triggered\n\ntext.bind(\'<Control-c>\', copy_rich_text)\n\ntext.insert("1.0", "Author et al. (2012). The title of the article. ")\ntext.insert("end", "Journal Name", "italic")\ntext.insert("end", ", ")\ntext.insert("end", "2", "bold")\ntext.insert("end", "(599), 1\xe2\x80\x935.")\n\nroot.mainloop()\n