Home > Blockchain >  How to get every item inside a listbox in tkinter?
How to get every item inside a listbox in tkinter?

Time:09-17

How do I make it so that I get all the items inside a listbox into a variable? I only manage to get the last item only. I want to print the items of a listbox into a new window but I only print the last item only.

  get_content = listbox2.get(0, END)
            bb = Label(receipt_window, text = "Pizzeria")
            line1 = Label(receipt_window, text = "----------------------------------------------------------------")
            for con_item in get_content:
                con = (con_item.split('PHP'))
                con1 = con[0]
                con2 = con[1]
                rec_content = f'{con1:<40}costs PHP{con2:<8}'
                receipt = Label(receipt_window, text = rec_content)
            bb.pack()
            line1.pack()
            receipt.pack()

The listbox contains: Listbox Content

The result: result

CodePudding user response:

It is because you use same variable receipt for the labels created inside the for loop and call receipt.pack() outside the for loop, so the last label created inside for loop will be packed only.

You need to call receipt.pack() inside the for loop:

    get_content = listbox2.get(0, END)
    bb = Label(receipt_window, text='Pizzeria')
    line1 = Label(receipt_window, text='----------------------------------------------------------------')
    bb.pack()
    line1.pack()
    for con_item in get_content:
        con1, con2 = con_item.split('PHP')
        rec_content = f'{con1:<40}costs PHP{con2:<8}'
        receipt = Label(receipt_window, text=rec_content)
        receipt.pack()

Note that it is better to use fixed width (monospaced) font for the labels.

  • Related