Reputation: 145
Hello Python community,
Im using Python 3.6 and Im stumped on how to display a stored item in an empty list to a list box. Can anyone evaluate my code and tell me what I'm missing? Thanks in advance!
from tkinter import *
root = Tk()
root.title("Name Entry")
root.geometry("240x250")
mylist = []
def get_data(l):
l.append(box1.get())
print(l)
label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)
ID=StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)
botonA = Button(root, text = "accept",command=lambda: get_data(mylist), width = 5)
botonA.grid(row = 0, column = 2)
list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7)
for item in mylist:
list_names.insert("end", item)
root.mainloop()
With the help from Matteo, I was able to creat what I wanted. Thanks again for clearing this up for me! :)
{from tkinter import *
root = Tk()
root.title("Name Entry")
root.geometry("240x250")
mylist = []
def get_data(l):
l.append(box1.get())
print(l)
display_data()
def display_data():
list_names.delete(0, "end")
for items in mylist:
list_names.insert(END, items)
label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)
ID = StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)
botonA = Button(root, text = "accept",command = lambda: get_data(mylist),
width = 5)
botonA.grid(row = 0, column = 2)
list_names = Listbox(root)
list_names.grid(row = 2, column = 1, rowspan = 7)
root.mainloop()}
Upvotes: 0
Views: 725
Reputation: 633
You have to insert the element when the button is pressed! In your code you are adding it to the listbox when mylist was empty.
Here is the working code:
from tkinter import *
root = Tk()
root.title("Name Entry")
root.geometry("240x250")
mylist = []
def get_data(l):
l.append(box1.get())
list_names.insert(END, l)
print(l)
label1 = Label(root, text="ID:", height=2)
label1.grid(row=0, column=0)
ID = StringVar()
box1 = Entry(root, bd=4, textvariable=ID)
box1.grid(row=0, column=1)
botonA = Button(root, text="accept", command=lambda: get_data(mylist), width=5)
botonA.grid(row=0, column=2)
list_names = Listbox(root)
list_names.grid(row=2, column=1, rowspan=7)
root.mainloop()
I also modified two other things:
I'm not sure if it's what you wanted but l.append(box1.get()) adds to the listbox all the element of the list, and not just the last one as I think you need.
list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7) means that the list_names variable is the result of the grid function (which is None). You have to first save the ListBox variable, and the grid it.
Upvotes: 2