首页 > 解决方案 > 如何删除 tkinter 文本中的通配符?

问题描述

我想删除 < > 中的每个文本。我曾经 replace('<*>',' ') 但它根本没有删除它们。

例如,我的文本是"<a/ddff>Nitin Hardeniya - 2015 - ‎Computers" I want it to turn into "Nitin Hardeniya - 2015 - ‎Computers"

请告诉我应该如何更正我的代码。

这是代码:

import tkinter as tk

root = tk.Tk()
text = root.clipboard_get()
def onclick():
    text_widget.delete("1.0", "end")   
    text_widget.insert(tk.END, text.replace('<*>',' '))   

root = tk.Tk()
text_widget = tk.Text(root)
text_widget.insert(tk.END, text)  #inserting the data in the text widget
text_widget.pack()

button = tk.Button(root, text = "Press me!", command = onclick)
button.pack()

root.mainloop()

标签: python-3.xtkinterwildcard

解决方案


您需要使用正则表达式进行此类匹配。在<*>你的行中: text.replace('<*>',' ')不是正则表达式它是严格匹配(参见replace函数文档)

一种方法是

def onclick():
    original = text_widget.get("1.0", "end")   
    pattern = re.compile(r'(<[^<>]+>)')
    fixed= pattern.sub(r" ", original )
    text_widget.delete("1.0", "end")   
    text_widget.insert(tk.END, fixed)   

推荐阅读