Search code examples
pythontkintercombobox

How to not display duplicates in a list using tkinter


How do I get this program to not display the same selection again to the user when its already been selected ? I know behind the scenes I can create a set of my entries for the code to continue using, but I cant seem to stop the display showing duplicate items if the user selects the same thing again. I thought the 'not in' statement might have worked. Any help please ?

from tkinter import *
from tkinter import ttk

root = Tk()
# set in pixels
root.geometry("1000x750+100+100")

my_list = set()


def combo_click(event):
    my_label = Label(root, text=myCombo.get()).pack()
    if myCombo.get() not in my_list:
        my_list.add(myCombo.get())
#        print('List without duplicate items (Set) ' + '\n')

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]

clicked = StringVar()
clicked.set(OptionList[0])
# *Options - https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
#drop = OptionMenu(root, clicked, *OptionList, command=selected)
#drop.pack(pady=100)

myCombo = ttk.Combobox(root, value=OptionList)
myCombo.current(0)
myCombo.bind("<<ComboboxSelected>>", combo_click)
myCombo.pack()

root.mainloop()

Solution

  • A method you could use to filter out duplicates in a list is the following code. I am assuming you are adding each bit of text to the Tkinter list through variables.

    In my code the variable: a is the item we wish to add to the list.

    Code to filter through entries to a Tkinter list:

    While True: #replace the bit inbetween w and t with your how long you want to do it 
    #add everything you add to a list before you add to Tkinter Listbox as shown below.   
        for x in tlist:
            if tlist contains a:
                print("Duplicate! This will not be added.")
            else:
                [whatever_you_called_your_listbox].insert(END,a)
                print(a,"Was added.")
    

    Hope this helps!