Python 删除tkinter文本小部件中的重复行
有没有办法删除tkinter中的重复行 代码如下:Python 删除tkinter文本小部件中的重复行,python,tkinter,duplicates,Python,Tkinter,Duplicates,有没有办法删除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
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()
在这里,当我单击“删除”按钮时,我希望删除文本小部件中的所有重复行
在本例中,我有以下字符串:
"""
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.
我已经解释了它与评论,以了解在进行中。这看起来很简单,但我相信它可以进行更多优化。将文本作为字符串,对其进行操作(可能有用),然后将其放回
关于从列表中删除重复项,stackoverflow有很多问题,而文本小部件实际上就是字符串列表。你有没有研究过如何从字符串列表中删除重复项?@BryanOakley:是的,我尽了全力,但没有成功。再次感谢你的快速回答@CoolCloud,但我面临一个小问题。当我运行此函数时,末尾有一些不必要的空行。有没有办法删除这些空行?@Lenovo360尝试在funcYes末尾添加文本。删除('end-1c','end')
,这就解决了问题,谢谢@Lenovo360我还删除了一些行,看一看。文本小部件中的第一个字符是“1.0”
,而不是“0.0”
。