0
votes

I have two tkinter listboxes (parent and child) and two buttons (add_button and remove_button). The child listbox gets items from the parent listbox via the add_button and there is an option of removing the items from the child listbox via the remove_button.

My problem is that after the GUI is loaded and the add_button is pressed, the first item in the parent listbox is added to the child listbox even if it is not ACTIVE. The same happens to the child_frame, in that the first item is removed after pressing the remove_button even if it is not ACTIVE. I want a way to prevent this. Additionally, I want an item to be added to the child listbox only once no matter how many times the add_button is pressed.

The code below is a part of another bigger code. Any help will be valued in solving the problems outlined above. Thanks in advance.

Here is the code:

from Tkinter import *

root = Tk()
root.geometry('330x200')

names = ['Bill', 'Jack', 'Joanne', 'Ann', 'Dave', 'Jane']


def add_name():
    x = parent.get(ACTIVE)
    child.insert(END, x)


def remove_name():
    child.delete(ACTIVE)


parent = Listbox(root)
for name in names:
    parent.insert(END, name)

parent.place(x=5, y=5)

add_button = Button(root, text='Add',
                    command=add_name)
add_button.place(x=148, y=5)

remove_button = Button(root, text='Remove',
                       command=remove_name)
remove_button.place(x=138, y=50)

child = Listbox(root)
child.place(x=200, y=5)

root.mainloop()
1
I want a way to prevent this What I read is that you want to stop an item being added when the add button is pressed?? What exactly do you want the add button to do in detail? For your second question, you will have to program a statement to see if the item to add is already in the list displayed in the listbox before adding. - user4171906
No, I don't want to stop an item being added when the add_button is pressed. I want to prevent adding an item if it is not selected, because currently the first item in the parent listbox is being added when I press the add_button without selecting anything. Kindly suggest a program for my second question - Jorge

1 Answers

0
votes

Why not replace ACTIVE by curselection -

def add_name():
    if len(parent.curselection()) != 0:
        x = parent.get(parent.curselection())
        child.insert(END, x)
    else:
        print "select an element first"


def remove_name():
    if len(parent.curselection()) != 0:
        child.delete(child.curselection())
    else:
        print "select an element first"