tkinter 文本小部件作为 html
我已经构建了用于发送电子邮件的 tkinter 应用程序.电子邮件正文应该从文本小部件中获取带有格式/样式的文本.有什么方法可以做同样的事情.
I had built tkinter app for sending email. The body of email should get the text with formatting/style from the text widget. Is there any method for doing the same.
get 方法只给出文本,而不给出样式/格式.
get method is only given the text but not the style/formatting.
文本小部件有一个名为 dump
的方法,它可以序列化文本小部件中的所有内容.它返回一个元组列表.每个元组将采用 (key, value, index) 形式.key 将是以下之一:text
、mark
、tagon
、tagoff
、image
或 window
.该值将取决于键.例如,对于 tagon
和 tagoff
,值将是标签的名称.对于 text
,它是文本.
The text widget has a method named dump
which can serialize everything in the text widget. It returns a list of tuples. Each tuple will be of the form (key, value, index). key will be one of the following: text
, mark
, tagon
, tagoff
, image
, or window
. The value will be dependent on the key. For example, with tagon
and tagoff
the value will be the name of the tag. For text
it's the text.
考虑一个带有标记b"(粗体)和h1"(标题)标记的文本小部件.它可能看起来像这样:
Consider a text widget with the tags "b" for bold and "h1" for the header. It might look something like this:
当您调用 dump
方法(例如:self.text.dump("1.0", "end")
)时,您会得到如下内容:
When you call the dump
method (eg: self.text.dump("1.0", "end")
), you would get something like the following:
(
('mark', 'current', '1.0'),
('tagon', 'h1', '1.0'),
('text', 'Hello, world!', '1.0'),
('tagoff', 'h1', '1.13'),
('text', '\n', '1.13'),
('text', '\n', '2.0'),
('text', 'this is a test with some ', '3.0'),
('tagon', 'b', '3.25'),
('text', 'bold text', '3.25'),
('tagoff', 'b', '3.34'),
('text', '.', '3.34'),
('mark', 'insert', '3.35'),
('text', '\n', '3.35'),
)
转换程序只需要遍历该数据并处理每个键.如果您使用与 html 标签相对应的标签名称(例如:"b"
、"h1"
等),转换将变得相当简单.它可能看起来像这样:
A conversion program simply needs to loop over that data and process each key. If you use tag names that correspond to html tags (eg: "b"
, "h1"
, etc), the conversion becomes fairly simple. It might look something like this:
def convert(self):
html = ""
for (key, value, index) in self.text.dump("1.0", "end"):
self.converted.insert("end", str((key, value, index)) + "\n")
if key == "tagon":
html += "<{}>".format(value)
elif key == "tagoff":
html += "</{}>".format(value)
elif key == "text":
html += value
对于示例窗口,上面会产生类似这样的结果:
The above would yield something like this for the example window:
<h1>Hello, world!</h1>
this is a test with some <b>bold text</b>.
您必须添加一些额外的代码来处理段落,因为 dump
方法只返回换行符而不是每个段落的标签,但除此之外,它是一个相当简单的算法.
You'll have to add some additional code to handle paragraphs since the dump
method just returns newlines rather than tags for each paragraph, but otherwise it's a fairly straight-forward algorithm.