TransWikia.com

Possible to create a listbox by click on a button

Stack Overflow Asked by SCH on December 3, 2020

I will create multiple entry box for user to input, and click on a button that will store all entry value in to a array, entries will be cleared, and then stored user can store another set of entry values.

So this button will do 2 functions:
1: store values in to my array
2: create 1st listbox with values from 1st array

In result, i can end up with multiple sets of array, and each sets of array with its own listbox.

I have not find related guide to this, or ‘dynamic create listbox’ did not help me. Possible to share examples if this doable.

One Answer

Welcome to Stack Overflow Community.

As far as I understand your question, I have tried this

from tkinter import *

root = Tk()

def saveClear():
    global entry_list
    listbox = Listbox(root)
    for entry in entry_list:
        listbox.insert(END, entry.get())
        entry.set('')
    listbox.pack(padx = 10, pady = 10)
    
entry_list = []
for _ in range(5):
    ent_var = StringVar()
    ent = Entry(root, textvariable = ent_var)
    entry_list.append(ent_var)
    ent.pack(padx = 10, pady = 10)

but = Button(root, text = 'Save and Clear', command = saveClear)
but.pack(padx = 10, pady = 10)

root.mainloop()

UPDATE: In order to get the values form a ListBox(), you will need to make use of listvariable attribute with the target as Variable() to store the values as a tuple and use the .get() method to get the value of the same.

Here is the updated code:

from tkinter import *

root = Tk()

def retrieve(index):    
    global values
    if index == 'all':
        for value in values:
            print(value.get())
    else:
        print(values[index].get())

values = []
def saveClear():
    global entry_list, values
    list_var = Variable()
    listbox = Listbox(root, listvariable = list_var)
    for entry in entry_list:
        listbox.insert(END, entry.get())
        entry.set('')
    values.append(list_var)
    listbox.pack(padx = 10, pady = 10)

entry_list = []
for _ in range(5):
    ent_var = StringVar()
    ent = Entry(root, textvariable = ent_var)
    entry_list.append(ent_var)
    ent.pack(padx = 10, pady = 10)

but = Button(root, text = 'Save and Clear', command = saveClear)
but.pack(padx = 10, pady = 10)

root.mainloop()
retrieve('all') #OR specify the index that you wish to retrieve

Here the retrieve() is called after the end of mainloop(), i.e., it will be executed after the termination of the mainloop, but you can use this function in your code as you require.

Hope it helped. Cheers!

Correct answer by AST on December 3, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP