So I am trying to build a restaurant menu.
I want to create buttons based on instances of class Food:
class Food:
instances=[]
def __init__(self,name,price):
self.name=name
self.price=price
Food.instances.append(self)
def __iter__(self):
for item in Food.instances:
yield item
def get_name(self)
return self.name
The code I have right now, works, but it also changes the Food.instances to button object, I want it to stay as Food objects, so I can call functions to get their name and price.
This is what I have right now:
def read_data(): #reads data from json file
global data
with open("restaurant\menu.json",'r') as f:
data=json.loads(f.read())
def get_instances(json_data): #gets Food instances based on data loaded from json file
for u in json_data:
x=Food(**u)
def get_buttons(frame,list_aux): #makes buttons based on instances of Food class
column=0
rows=0
for index,obj in enumerate(list_aux):
if column<3:
list_aux[index]=Button(frame,text=obj.get_name())
list_aux[index].grid(row=rows,column=column)
column+=1
else:
column=0
rows+=1
list_aux[index]=Button(frame,text=obj.get_name())
list_aux[index].grid(row=rows,column=column)
column+=1
read_data()
get_instances(data)
print(Food.instances)
list_aux=Food.instances #makes a copy of Food.instances to HOPEFULLY not mess up the class
root=Tk()
get_buttons(root,list_aux)
root.mainloop()
Before running get_buttons() function, when I print Food.instances I get:
[<__main__.Food object at 0x000001C0F0113E50>, <__main__.Food object at 0x000001C0EFD51960>, <__main__.Food object at 0x000001C0F0115A20>]
After running the function, printing list_aux results in:
[<tkinter.Button object .!button>, <tkinter.Button object .!button2>, <tkinter.Button object .!button3>]
But also, when print Food.instances, I get the same output and I lose all of the class methods written (get_name() and others I did not include here because are not relevant).
How can I keep creating those buttons, but not change Food.instances?
One workaround I have found is to modify the get_instances() function to:
def get_instances(json_data):
Food.instances=[] #this is the line that is added
for u in json_data:
x=Food(**u)
So I can call it again after get_buttons() function, deleting those tkinter.Button objects, creating Food objects again, and I can use the class methods as before, but I feel like this is extremly inefficient. How can I fix this?