Python Forum

Full Version: tkinter| listbox.insert problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi! I'm beginner with tkinter, I have one question.
When I select item from the list, I want to copy it and added again to the same list. However, the list is updating with numbers only. Line 4:

def add_me():
    selected_items = listbox.curselection()
    for item in selected_items:
        listbox.insert(END, item)
        print(item, 'is added')


listbox = Listbox(root, width = 40, height = 15, selectmode = MULTIPLE)
listbox.insert(0, 'Python')
listbox.insert(1, 'C++')
listbox.insert(2, 'C#')
listbox.insert(3, 'PHP')
listbox.pack(pady = 25)

btn = Button(root, text = 'Print', command = print_me).place(x = 200, y = 300)
btn2 = Button(root, text = 'Delete', command = delete_me).place(x = 300, y = 300)
btn3 = Button(root, text = 'Add', command = add_me).place(x = 400, y = 300)
Output:
2 is added
2 is added
3 is added


I will appreciate any help, Thank you!
please show enough code so that we can run it.
(Sep-29-2020, 03:24 PM)Larz60+ Wrote: [ -> ]please show enough code so that we can run it.

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



def print_me():
    selected_items = listbox.curselection()
    for item in selected_items:
        print(listbox.get(item))


def delete_me():
    selected_items = listbox.curselection()
    for item in selected_items:
        listbox.delete(item)


def add_me():
    selected_items = listbox.curselection()
    for item in selected_items:
        listbox.insert(END, item)
        print(item, 'is added')


listbox = Listbox(root, width = 40, height = 15, selectmode = MULTIPLE)
listbox.insert(0, 'Python')
listbox.insert(1, 'C++')
listbox.insert(2, 'C#')
listbox.insert(3, 'PHP')
listbox.pack(pady = 25)

btn = Button(root, text = 'Print', command = print_me).place(x = 200, y = 300)
btn2 = Button(root, text = 'Delete', command = delete_me).place(x = 300, y = 300)
btn3 = Button(root, text = 'Add', command = add_me).place(x = 400, y = 300)


root.geometry('650x450+650+350')
root.mainloop()
Just like in the print_me function where you get the value corresponding to the given index, you need to do that in the function add_me
Change
def add_me():
    selected_items = listbox.curselection()
    for item in selected_items:
        listbox.insert(END, item)
        print(item, 'is added')

to
def add_me():
    selected_items = listbox.curselection()
    for item in selected_items:
        item_value = listbox.get(item)
        listbox.insert(END, item_value)
        print(item_value, 'is added')