我在Tkinter做一个简单的降价分析。例如,标题可以被星号符号包围的概念
*Heading 1*
,
**Heading 2**
.
我使用regex来查找这种格式的字符串,标记它们并更改标记的样式。
我正在努力处理的项目是在搜索后从文本中删除星号符号。我尝试了一些代码(包括注释掉的代码),但它只是删除了标记的文本。
我的代码正确找到
*标题1
把它变成
*标题1
但不能删除标记符号
标题1
有人能帮我用算法从保留格式的标题中删除星号符号吗?
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
from tkinter import font
class HelpDialog(tk.Toplevel):
"""Seperate window to show the results of SSO Search"""
def __init__(self, parent,text):
super().__init__(parent)
self.title("Help")
self.defaultfont = font.Font(family="Sans Serif",size=12)
self.textbox = ScrolledText(self,height=40,width=80,font=self.defaultfont)
self.textbox.config(wrap=tk.WORD)
self.textbox.grid()
self.textbox.insert(0.0,text)
self.style()
def style(self):
self.h1font = font.Font(family="Sans Serif", size=18, weight="bold")
self.h2font = font.Font(family="Sans Serif", size=14, weight="bold")
self.h3font = font.Font(family="Sans Serif", size=12, weight="bold", slant="italic")
self.textbox.tag_configure("h1",font=self.h1font)
self.textbox.tag_configure("h2",font=self.h2font)
self.textbox.tag_configure("h3",font=self.h3font)
self.tag_match(r"^[\*]{1}[\w\d -]+[\*]{1}$", "h1")
self.tag_match(r"^[\*]{2}[\w\d -]+[\*]{2}$", "h2")
self.tag_match(r"^[\*]{3}[\w\d -]+[\*]{3}$", "h3")
def tag_match(self,regex,tag):
count = tk.IntVar()
self.textbox.mark_set("matchStart", "1.0")
self.textbox.mark_set("matchEnd", "1.0")
while True:
index = self.textbox.search(regex,"matchEnd","end",count=count,regexp=True)
if index=="": break
self.textbox.mark_set("matchStart",index)
self.textbox.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
self.textbox.tag_add(tag,"matchStart","matchEnd")
#Futile attempt to remove the ** from the headings
#text = self.textbox.get("matchStart", "matchEnd")
#orig_length = len(text)
#text = text.replace("*","").ljust(orig_length, " ")
#self.textbox.delete("matchStart", "matchEnd")
#self.textbox.insert("matchStart", text)
if __name__ == '__main__':
text = """*Heading 1*
A paragraph
**Heading 2**
Some more text
***Heading 3***
Conclusion
"""
root = tk.Tk()
root.withdraw()
HelpDialog(root,text)