Home > Blockchain >  Python lists not updating with .append()
Python lists not updating with .append()

Time:10-05

I am trying to make a program that stores drinks and displays them when a user wants to (when they click b5), but the .append() function isn’t working. I think it’s because the list is not saving after the user inputs a drink. My guess is that I might need a while loop somewhere, but I am not sure where to put it. I also wonder if there isn’t a better way of storing and retrieving these. Here is a shortened version of the code.

Here are the relevant functions.

def save_d(added_drink_ent, top):
    global drinks_list
    drinks_list = []
    newtop = Toplevel(root)
    newtop.geometry("200x200")
    newtop.title("Drink Added")
    label = Label(newtop, text=f"Added {added_drink_ent.get()}")
    label.pack()
    close_btn = Button(newtop, text='Close', command=lambda t=top, n=newtop: close(t,n))
    close_btn.pack()
    drinks_list.append(added_drink_ent.get())

def add_drink():
    top = Toplevel(root)
    top.title("Add Drink")
    top.geometry('400x100')
    label = Label(top, text="Add a new drink to the list.")
    label.pack()
    entry_drink_ent = Entry(top)
    entry_drink_string = str(entry_drink_ent)
    entry_drink_ent.pack()
    b1 = Button(top, text='Submit Add Drink', command=lambda: save_d(entry_drink_ent, top))
    b1.pack()
    b2 = Button(top, text="Close", command=top.destroy)
    b2.pack()

def close(top, newtop):
    top.destroy()
    newtop.destroy()

def display():
    newtop2 = Toplevel(root)
    label3 = Label(newtop2, font=("Arial", 20))
    label3.config(text=f"These are the drinks you had today: {drinks_list}")
    label3.pack()

The buttons. b5 is the one that should display the list.

b1 = Button(root, text="START TIMER", width=25, borderwidth=5, command=start, font=('Arial', 30))
b1.pack()
b2 = Button(root, text="STOP TIMER", width=25, borderwidth=5, command=stop, font=('Arial', 30))
b2.pack()
b3 = Button(root, text="RESET BUTTON", width=25, borderwidth=5, command=reset, font=('Arial', 30))
b3.pack()
b4 = Button(root, text="ADD DRINK", width=25, borderwidth=5, command=add_drink, font=('Arial', 30))
b4.pack()
b5 = Button(root, text="DISPLAY DRINK LOG", width=26, borderwidth=5, command=display, font=('Arial', 30))
b5.pack()

CodePudding user response:

Are you clearing drink_lists in save_d every time?

def save_d(added_drink_ent, top):
    global drinks_list
    drinks_list = []

Perhaps define drink_lists outside of save_d (if not already done) as an empty list:

drinks_list = []

def save_d(added_drink_ent, top):
    # append to drink_lists here

CodePudding user response:

ok maybe I'm wrong but in save_d function, you start by using global variable drinks_list, and next line you set it to empty. So everytime you use the function, you erase the previous list before you add something into it. Hope this help

  • Related