如何在Tkinter中获取tkhtmlview HTMLText编辑后的HTML内容
解决tkhtmlview中HTMLText编辑后获取HTML内容的问题
你之前尝试把HTMLText传入Tkinter Text组件的方法行不通,因为HTMLText本质是封装了Text组件的Frame,直接放入Text会显示组件的内部标识符(比如.!frame)。正确的做法是使用HTMLText自带的方法来获取编辑后的HTML内容:
方法:使用get_html()方法
HTMLText组件内置了get_html()方法,专门用于获取编辑后的HTML内容,直接调用就能得到对应格式的代码。
修改后的示例代码
from tkinter import * from tkhtmlview import HTMLText def get_edited_html(): # 获取编辑后的HTML内容 edited_html = html_label.get_html() print("编辑后的HTML:") print(edited_html) # 也可以把内容展示在新窗口的文本框里 show_win = Toplevel(window) text_box = Text(show_win) text_box.pack(fill=BOTH, expand=True) text_box.insert(END, edited_html) window = Tk() html_sample = "<p><strong>in love (with </strong>someone or something<strong>)</strong></p>" html_label = HTMLText(window, html=html_sample) html_label.place( x=269.0, y=331.0, width=426.0, height=178.0) # 添加按钮触发获取操作 get_btn = Button(window, text="获取编辑后的HTML", command=get_edited_html) get_btn.place(x=269.0, y=520.0) window.mainloop()
额外说明
get_html()会将当前编辑的内容自动转换成带标签的HTML格式,保留加粗、段落等原有结构。- 如果需要实时监听内容变化,可以给HTMLText内部的Text组件绑定按键释放事件,在回调中调用
get_html():
# 绑定实时监听事件 html_label.text.bind("<KeyRelease>", lambda e: print(html_label.get_html()))
内容的提问来源于stack exchange,提问作者ZZZ
相关产品推荐
相关产品推荐

