Is there any way to remove duplicate lines in tkinter?
Here’s the code:
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 worldnnHello worldnnBye byennnnnBye byenBye bye''') remove_button = Button(root , text = "Remove Duplicate Lines" , command = remove_duplicate) remove_button.pack() mainloop()
Here when I click on the
remove_button, I want all the duplicate lines in my text widget to be removed.
In this case, I have the string:
""" Hello world Hello world Bye bye Bye bye Bye bye """
, so when I remove the duplicate lines, I should get something like:
""" Hello world Bye bye """
Is there any way to achieve this in tkinter?
It would be great if anyone could help me out.
The basic idea is to get all the text in the widget, remove the duplicates and add to a new list. Now add the new list items to the text widget, like:
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.
I have explained it with comments to understand-on-the-go. This seems pretty straightforward, though I am sure it can be optimized more.