python - 删除 tkinter 文本小部件中的重复行
问题描述
有什么方法可以删除 tkinter 中的重复行吗?
这是代码:
from tkinter import *
root = Tk()
def remove_duplicate():
# Code to remove all duplicate lines in the text widget
pass
text = Text(root , width = 65, height = 20, font = "consolas 14")
text.pack()
text.insert('1.0' , '''Hello world\n\nHello world\n\nBye bye\n\n\n\n\nBye bye\nBye bye''')
remove_button = Button(root , text = "Remove Duplicate Lines" , command = remove_duplicate)
remove_button.pack()
mainloop()
在这里,当我单击 时remove_button
,我希望删除文本小部件中的所有重复行。
在这种情况下,我有字符串:
"""
Hello world
Hello world
Bye bye
Bye bye
Bye bye
"""
,所以当我删除重复的行时,我应该得到类似的东西:
"""
Hello world
Bye bye
"""
有没有办法在 tkinter 中实现这一点?
如果有人可以帮助我,那就太好了。
解决方案
基本思想是获取小部件中的所有文本,删除重复项并添加到新列表中。现在将新列表项添加到文本小部件,例如:
def remove_duplicate():
val = text.get('0.0','end-1c').split('\n') # Initial values
dup = [] # Empty list to append all non duplicates
text.delete('0.0','end-1c') # Remove currently written words
for i in val: # Loop through list
if i not in dup: # If not duplicate
dup.append(i) # Append to list
dup.append('\n') # Add a new line
text.insert('0.0',''.join(dup)) # Add the new data onto the widget
text.delete('end-1c','end') # To remove the extra line.
我已经用评论解释了它,以便在旅途中理解。这看起来很简单,尽管我相信它可以进行更多优化。
推荐阅读
- c - 如何计算玻璃汁的体积?
- javascript - 使用 JavaScript 中的点击问题一一递增循环迭代
- r - 创建假人后保存标签包装中的标签
- android - 有没有办法在应用程序中打开 NFC 标签 URL,而不是 google/safari?
- reactjs - 我正在寻找一种在 react-redux-firebase 中使用 firestore connect 获取某些字母的方法
- c++ - 运行 C++ 项目
- r - 使用 R 从网站中查找所有 csv 链接
- javascript - 是否有 ESLint 规则来防止 `Promise
` to `boolean` 强制转换 - typescript-compiler-api - 打字稿转换器,`node.parent`未定义
- mysql - 无法使用外键 Maria DB 创建表