python-3.x - 如何删除 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()
解决方案
您需要使用正则表达式进行此类匹配。在<*>
你的行中:
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)
推荐阅读
- python - Python不合作
- java - FireStore 数据插入 (Android Studio 3.6.1)
- php - PHP 等效于按位运算 NodeJs 脚本
- bash - bash中的递归复制文件保留目录树
- linux - Apache 不会监听除端口 80 以外的其他端口
- c++ - 如何从一个类中的命名空间初始化所有变量
- r - tidyverse 列名和反引号(有时会产生转义字符错误,例如斜杠)
- mysql - 如何使休眠不覆盖要保存的对象中的 ID,而是使用其 ID?
- c# - listview .clear() 方法
- python - Kivy-通过kv文件添加在py文件中定义的自定义小部件