Python lists not updating with .append() - python

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()

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

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

python tkinter button command does not work

I'm trying to create a program in python tkinter which user first have to login, then the first page is closed and new one opens with some buttons inside.
button must change it's color and text on click but it does not do anything
from tkinter import *
def button_clicked(button):
Button(button).configure(bg="red", text="not Active")
def open_setting_page():
loginPage.destroy()
setting_page = Tk()
setting_page.title("Setting")
setting_page.geometry("400x300")
b2 = Button(setting_page, text="Active", height=5, width=10, bg="green",command=lambda:button_clicked(b2)).grid(row=0, column=0)
b3 = Button(setting_page, text="Active", height=5, width=10, bg="green",command=lambda:button_clicked(b3)).grid(row=0, column=1)
setting_page.mainloop()
#program starts here
loginPage = Tk()
loginPage.title("Security System")
loginPage.geometry("400x300")
Label(text="\n\n\n\n").pack()
l1 = Label(text="Enter Password:")
l1.pack()
password_entry = Entry()
password_entry.insert(0, "Enter Your Password...")
password_entry.pack()
b1 = Button(text="Login", command=open_setting_page)
b1.pack()
loginPage.mainloop()
I want the buttons color and text be changed on click but noting happens when I click it.
there are two problems in this code:
in open_setting_page() -> the variables b2 and b3 become None because Button(XXX).grid() returns None -> lets separate the button creation and the grid placement into 2 steps.
in button_clicked(button) function -> Button(button).configure is wrong. it should be button.configure(XX) to get hold of the button that you gave to the function.
Here is how these two functions could look like:
def button_clicked(button):
button.configure(bg="red", text="not Active")
def open_setting_page():
loginPage.destroy()
setting_page = Tk()
setting_page.title("Setting")
setting_page.geometry("400x300")
b2 = Button(setting_page, text="Active", height=5, width=10, bg="green", command=lambda: button_clicked(b2))
b3 = Button(setting_page, text="Active", height=5, width=10, bg="green", command=lambda: button_clicked(b3))
b2.grid(row=0, column=0)
b3.grid(row=0, column=1)
setting_page.mainloop()

Python tkinter how to save a variable in a list and return it

I am trying to make a program that records user input (drinks) and displays these inputs when a person wants to view them. .
Specifically, I want the drinks to be displayed when the user clicks the 'View Log' button (second_button). I think this needs to be done in the viewlog function, but I am stuck with the best way to do this. I am unsure of how to best store the inputs and how to retrieve them.
from tkinter import *
root = Tk()
root.title('Simple App')
first_label = Label(root, text="Welcome to the program", font=('Arial', 20)).pack()
def save_drink(added_drink, top):
global drinks_list
drinks_list = []
newtop = Toplevel(root)
newtop.geometry("200x200")
newtop.title("Drink Added")
label = Label(
newtop,
text= "{} Added".format((added_drink.get())), font=('Mistral 20')).pack()
close_btn = Button(newtop, text='Close', font=('Mistral 20'), command=lambda t=top, n=newtop: close(t,n))
close_btn.pack()
drinks_list.append(added_drink.get())
def add_drink():
top = Toplevel(root)
top.geometry("750x250")
top.title("Record Drink")
label = Label(top, text= "What drink did you have?", font=('Mistral 18')).pack()
added_drink = Entry(top, font=6)
added_drink_string = str(added_drink)
added_drink.pack()
added_drink_button = Button(top, text='Add Drink', font=3,
command=lambda: save_drink(added_drink, top)).pack()
def close(top, newtop):
top.destroy()
newtop.destroy()
def viewlog():
logtop = Toplevel(root)
logtop.title('Drinks Log')
label_text = Label(logtop, text="Today's Drinks", font=('Arial', 20)).pack()
label2 = Label(logtop, text=print(drinks_list), font=('Arial', 16))
# here we need to take the items in drinks_list and display them on a screen
close_btn = Button(logtop, text="Close", pady=20, font=('Times New Roman', 20), command=logtop.destroy).pack()
first_button = Button(root, text="Add drink", command=add_drink).pack()
second_button = Button(root, text="View log", command=viewlog).pack()
root.mainloop()
you need to pack the label, and remove print() from the label text variable
label2 = Label(logtop, text=(drinks_list), font=('Arial', 16)).pack()

In my code I made a clear() function to act as a normal clear button in my calculator but there is a problem

I made a calculator and I made it memorize in memory the first_number/F_NUM, and when I tried to use a function I made which is called: clear() to kind of delete the F_NUM from memory it gave me this error: (cannot delete function call).
#sorry for the messy code but if you can help me please do!
here is my code:
from cProfile import label
from tkinter import *
from tkinter import ttk
import tkinter.font as font
root = Tk()
root.title('Calculator')
root.geometry('300x400')
canvas = Canvas(root, width=300, height=400)
canvas.pack()
Helvetica_fornt = font.Font(family='Helvetica')
#-Functions of buttons-------------------------------------#
def button_click(number):
current = entry_1.get()
entry_1.delete(0, END)
entry_1.insert(0, current + number)
def clear():
entry_1.delete(0, END)
del globals(F_NUM) ##########Problem is here############
#ps comment this problem out to try the claculator
def Back_Space():
entry_1.delete(0, 1)
def addition():
first_number = entry_1.get()
global F_NUM
F_NUM = int(first_number)
entry_1.delete(0, END)
def equals():
second_number = entry_1.get()
entry_1.delete(0, END)
entry_1.insert(0, F_NUM + int(second_number))
#---------------------------------------------------------#
#---Buttons------------------------------------------------------#
# ps we only need lambda when there are parameters.
button_0 = Button(root, text='0', width=4, height=2,
command=lambda: button_click('0'))
button_0.place(x=65, y=350, width=65, height=50)
button_1 = Button(root, text='1', width=4, height=2,
command=lambda: button_click('1'))
button_1.place(x=0, y=301, width=65, height=50) # Location
button_2 = Button(root, text='2', width=4, height=2,
command=lambda: button_click('2'))
button_2.place(x=65, y=301, width=65, height=50) # Location
button_3 = Button(root, text='3', width=4, height=2,
command=lambda: button_click('3'))
button_3.place(x=130, y=301, width=65, height=50) # Location
button_add = Button(root, text='+', width=7, height=2,
command=addition)
button_add.place(x=195, y=301, width=105, height=50) # Location
button_clear = Button(root, text='Clear', width=12, height=2,
command=clear)
button_clear.place(x=195, y=100, width=105, height=50) # Location
back_space = Button(root, text='BackSpace', width=12, height=2,
command=Back_Space)
back_space.place(x=195, y=51, width=105, height=50) # Location
equals_button = Button(root, text='=', width=12, height=2,
command=equals)
equals_button.place(x=195, y=350, width=105, height=50) # Location
#-------------------------------------------------------------------#
#-The entry-----------------------------------------------------------#
entry_1 = Entry(root, borderwidth=3, font=Helvetica_fornt)
entry_1.place(x=1, y=1, width=296, height=50)
#---------------------------------------------------------------------#
root.mainloop()
del globals(F_NUM)
globals is function, globals(F_NUM) is function call, del statement should be followed by target. In your case variable name, if you want to del something from globals dict using function then first use global variable name followed by del statement for example:
def deletex():
global x
del x
x = 10
print(x) # 10
deletex()
print(x) # NameError: name 'x' is not defined

how to change root color using tkinter with a button command

import tkinter
from tkinter import *
import random
a = random.randint(1, 10)
print(a)
root = Tk()
root.geometry("500x500")
root.title(" peleg's random number")
bglightmode = "black"
fglightmode = "white"
root["bg"] = format(bglightmode)
wrongtxt = "Wrong answer, the number was {}".format(a)
righttxt = "Correct, the number was {}".format(a)
def Take_input():
INPUT = inputtxt.get("1.0", "end-1c", )
print(INPUT)
if (INPUT == format(a)):
Output.insert(END, righttxt)
else:
Output.insert(END, wrongtxt)
l = Label(text="pick a number between 1-10")
l["bg"] = "black"
l["fg"] = "white"
inputtxt = Text(root, height=10,
width=35,
bg=format(bglightmode),
fg=format(fglightmode))
Output = Text(root, height=10,
width=35,
bg=format(bglightmode),
fg=format(fglightmode))
b1 = Button(root, height=2,
bg=format(bglightmode),
fg=format(fglightmode),
width=20,
text="Show",
command=lambda: Take_input())
b2 = Button(root, height=2,
width=20,
text="exit",
bg=format(bglightmode),
fg=format(fglightmode),
command=root.destroy)
b3 = Button(root, height=2,
width=20,
text="ready",
bg=format(bglightmode),
fg=format(fglightmode),
command = if bglightmode)
l.pack()
inputtxt.pack()
Output.pack()
b1.pack()
b2.pack()
b3.pack()
mainloop()
the main problem is here with this part of the code:
b3 = Button(root, height=2,
width=20,
text="ready",
bg=format(bglightmode),
fg=format(fglightmode),
command = if bglightmode)
i tryed fixing it but was unable, does anyone know the solution?
by the way im a beginner so sorry for the stupid question
also what im trying to do is a toggle button between light and dark mode i thought making a switch would be the easiest way but if there is an easier way please comment
i was wanting to do this
b3 = Button(root, height=2,
width=20,
text="ready",
bg=format(bglightmode),
fg=format(fglightmode),
command = if bglightmode == "black":
......
but because its in a button command i cant
If you want the 'ready' button to change root color from black to white (or some other color) then try this.
b3 = Button(
root,
height=2,
width=20,
text="ready",
bg=format(bglightmode),
fg=format(fglightmode),
command = lambda: root.config(background = [bglightmode, fglightmode][root.cget("background") == bglightmode]))
Or you could create a function and use 'ready' button to access it.
def Check_Color():
if root["background"] == bglightmode:
root["background"] = fglightmode
else:
root["background"] = bglightmode
b3 = Button(
root,
height=2,
width=20,
text="ready",
bg=format(bglightmode),
fg=format(fglightmode),
command = Check_Color)

Weird visual bug when running tKinter code

I have to code a little game for a school project and this is a part of the name input code. When i run this part of the code it leaves me with a visual bug. This is the code that i have:
from tkinter import *
def retrieve_input():
input = Naam1.get("1.0", "end-1c")
print(input)
input = Naam2.get("1.0", "end-1c")
print(input)
input = Naam3.get("1.0", "end-1c")
print(input)
def create_kiezen():
global Naam1
global Naam2
global Naam3
kiezen = Tk()
kiezen.geometry('600x600')
kiezen.title('Namen invoeren!')
kiezen.configure(background='darkgrey')
Spelen = Button(kiezen, text='Begin!', bd='5', height='2', width='15',
command=lambda: [kiezen.destroy(), Spelmenu()])
Terug = Button(kiezen, text='Terug', bd='5', height='2', width='15', command=lambda: [kiezen.destroy(), menu()])
Spelen.pack(anchor='s', side='right')
Terug.pack(anchor='s', side='left')
kiezen.minsize(600, 600)
kiezen.maxsize(600, 600)
naamblok = Canvas(kiezen, width=400, height=200)
naamblok.place(x=100, y=100)
Opslaan=Button(naamblok, height=1, width=10, text='Opslaan', command=lambda: retrieve_input())
Opslaan.place(x=160, y=150)
Naam1=Text(naamblok, width=10, height=5)
Naam1.place(x=160, y=40)
Naam2= Text(naamblok, width=10, height=5)
Naam2.place(x=160, y=60)
Naam3=Text(naamblok, width=10, height=1)
Naam3.place(x=160, y=80)
mainloop()
create_kiezen()
There are three input fields but for some reason, there is one input field that is really big. It overlaps my button and I don't really know how to fix this.
Any helps is appreciated!

Categories