Sid
Sid

Reputation: 151

how to move items from one listbox to another listbox in tkinter

I am new to python and trying to learn tkinter. Could somebody help me with this problem please Ive been stuck on it for days. I want to move an item from one list box to another. I first tried using bind and <> but couldnty get that to work. I then created a function and tried just using a button. I can select data from the first listbox with the mouse and have managed to put it in a label, but I really need it to go into a second listbox - but cant get that to work.Any help please

from tkinter import *
from tkinter import ttk
my_window = Tk()

my_listbox_in = Listbox(my_window, height='5')
my_listbox_in.grid(row=0, column=0)
my_listbox_out = Listbox(my_window, height='5')
my_listbox_out.grid(row=0, column=2)

my_list = ['1', '2', '4', '6']

for item in my_list:
    my_listbox_in.insert(END, item)


def delete():
    my_listbox_in.delete(ANCHOR)
# delete all    my_listbox_in.delete(0,END)


def select():
#   my_label.config(text=my_listbox_in.get(ANCHOR))
    my_listbox_out.insert(my_listbox_in.get(ANCHOR))


button1 = Button(my_window, text='Delete', command=delete)
button1.grid(row=0, column=1)

button2 = Button(my_window, text='select', command=select)
button2.grid(row=1, column=1)


my_label = Label(my_window, text='my_label')
my_label.grid(row=2, column=1)

#my_listbox_in.bind('<<ListboxSelect>>', select())

mainloop()

Upvotes: 1

Views: 1602

Answers (1)

figbeam
figbeam

Reputation: 7176

Could it be this simple...?

def select():
    my_listbox_out.insert(END, my_listbox_in.get(ANCHOR))
    # ---------------------^  forgot to specify insert point

Update to answer

As for binding; I assume you mean binding to keyboard arrow keys. Then here's an example:

from tkinter import *
from tkinter import ttk

my_window = Tk()

my_listbox_in = Listbox(my_window, height='5')
my_listbox_in.grid(row=0, column=0, padx=10, pady=10)
my_listbox_out = Listbox(my_window, height='5')
my_listbox_out.grid(row=0, column=2, padx=(0,10), pady=10)
my_instructions = Label(my_window, text='Use arrow keys to move selected items')
my_instructions.grid(row=1, column=0, columnspan=3, pady=(0,10))

my_list = ['1', '2', '4', '6']

for item in my_list:
    my_listbox_in.insert(END, item)

def select(event=None):
    my_listbox_out.insert(END, my_listbox_in.get(ANCHOR))
    my_listbox_in.delete(ANCHOR)

def deselect(event=None):
    my_listbox_in.insert(END, my_listbox_out.get(ANCHOR))
    my_listbox_out.delete(ANCHOR)

my_window.bind('<Right>', select)
my_window.bind('<Left>', deselect)

mainloop()

The functions do not preserve item order, but you can let the callback function sort them if that's important.

Upvotes: 1

Related Questions