0

I am trying to create a simple "Store App" that will add the item name and cost to a dictionary and then output it, but whenever I go to run my program it adds both items to cart before I have even clicked the buttons. I am not sure if it is a python problem, or something to do with how Tkinter works. Any help would be appreciated.

from tkinter import *

root = Tk()
root.title("Number Sorter")
root.geometry('600x600')

cart_list = {"Item_Name": [], "Price": []}

def purchaseClick(Name, Price):
    cart_list["Item_Name"].append(Name)
    cart_list["Price"].append(Price)

title1 = Label(root, text="The Solar War by A.G Riddle")
item1_name = "The Solar War"
item1_price = 11.99
title1.pack()

purchasebtn = Button(root, text="Purchase", command = purchaseClick(item1_name, item1_price))
purchasebtn.pack()

title2 = Label(root, text="Elon Musk By Ashlee Vance")
item2_name = "Elon Musk"
item2_price = 9.99
title2.pack()

purchasebtn = Button(root, text="Purchase", command = purchaseClick(item2_name, item2_price))
purchasebtn.pack()

cart_list_show = Label(root, text=cart_list)
cart_list_show.pack()

root.mainloop()

1 Answers1

2

This is happening because Button.command takes a function as an argument, not the output. So, you have to pass just purchaseClick and not purchaseClick(item1, price1).

But in your case you need to pass in arguments too, so change the line from

purchasebtn = Button(root, text="Purchase", command = purchaseClick(item1_name, item1_price))

to this,

purchasebtn = Button(root, text="Purchase", command = lambda : purchaseClick(item1_name, item1_price))

I am fairly sure this is gonna do the work for you.

Navaneeth Reddy
  • 315
  • 1
  • 12