lundi 23 septembre 2019

How to add the results from checkbutton and text entries on GUI into dictionary in key:value format?

Trying to create a simple shopping list app, that will have user check the checkbox then enter the number of items. The button press should output a name with the number of item. for example, Apples 10, 1 banan etc. I would like to grow the fruits dictionary and later add other items to GUI, like meats/fish, general etc.

I thought the logical way would be to create a dictionary {key:value} where key would be the name of the checkbox, and a value will be the number inside entry text box.

Could you please show me how to do this? Thanks!

tried following some examples but could not understand how to extract a text="Apples" from checkbox and add this as a key into dictionary. Also played with lambda as output but nothing really materialized because all examples alreaddy had a dictionary created. here is my example.

from tkinter import *

item_list = []
items_dict = {}

    # mget gets output from checkboxes and prints results
def mget():
    print(apples.get(), pears.get(), bananas.get(),apricots.get())
    print(apples_qnty.get(),pears_qnty.get(), bananas_qnty.get(), 
    apricots_qnty.get())
    #item_list.append(apples.get)

 window = Tk()


apples = IntVar()
chk_apples = Checkbutton(window,text="Apples", 
variable=apples).grid(row=1,sticky=W) 
apples_qnty = StringVar()
apples_qnty = Entry(width=3)
apples_qnty.grid(column=1, row = 1)
item_list.append("Apples")

pears = IntVar()
chk_pears = Checkbutton(window,text="Pears", 
variable=pears).grid(row=2,sticky=W)
pears_qnty = StringVar()
pears_qnty = Entry(width=3)
pears_qnty.grid(column=1, row = 2)
item_list.append("Pears")

bananas = IntVar()
Checkbutton(window,text="Bananas", 
variable=bananas).grid(row=3,sticky=W)
bananas_qnty = StringVar()
bananas_qnty = Entry(width=3)
bananas_qnty.grid(column=1, row = 3)
item_list.append("Bananas")


apricots = IntVar()
Checkbutton(window,text="Apricots", 
variable=apricots).grid(row=4,sticky=W)

apricots_qnty = StringVar()
apricots_qnty = Entry(width=3)
apricots_qnty.grid(column=1, row = 4)
item_list.append("Apricots")

print(item_list)  # just to see list


Button(window,text="print check box states", command = mget).grid(row=5,sticky=W)
Button(window,text="exit", command =window.destroy).grid(row=5,sticky=E)

window.mainloop()

I would like the program to do the following: user checks on checkbuttons and enters numbers of items. pressing the button would output the items selected. For example, Apples 4, Bananas 1 etc... If the checkbutton is unchecked then don't output anything.




Aucun commentaire:

Enregistrer un commentaire