首页 > 解决方案 > 删除 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 中实现这一点?

如果有人可以帮助我,那就太好了。

标签: pythontkinterduplicates

解决方案


基本思想是获取小部件中的所有文本,删除重复项并添加到新列表中。现在将新列表项添加到文本小部件,例如:

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.

我已经用评论解释了它,以便在旅途中理解。这看起来很简单,尽管我相信它可以进行更多优化。


推荐阅读