Trying to create a functional Product Info Gatherer using csv and tkinter module. So far the searching method works but the data it's getting is wrong for the description.
import csv
import tkinter
from tkinter import *
CsvFile = "products.csv"
main = Tk()
main.geometry('500x500')
Entry1 = Entry(main, width = 20)
Entry1.pack()
lbl = Label(main, text = "a")
lbl.pack()
lb2 = Label(main, text = "a")
lb2.pack()
lb3 = Label(main, text = "a")
lb3.pack()
def find():
with open(CsvFile) as csvcsv:
reader = csv.DictReader(csvcsv)
barcode = Entry1.get()
for row in reader:
if barcode == row['barcode1']:
for desc, pice in row.items():
lbl.config(text = desc)
lb2.config(text = pice)
break
else:
lbl.config(text='This Product is currently unavailable')
Button(main, text='search', command = find).place(x=100, y=170)
main.mainloop()
I feel like there's something wrong with the lines between 26 to 30( starting from "if barcode" to "break" ) but i couldnt get the right code to make it work.
The csv file looks like this:(since in made this in excel)
barcode desc pice
1111111 Test $5.00
the code only shows "pice" for lbl and not the "Test" from the desc row. Though the Price shows correctly.
CodePudding user response:
If you print out the content of desc
and pice
in the inner for loop like below:
for desc, pice in row.items():
print(desc, pice)
...
Then you will get the following result in the console:
barcode 1111111
desc Test
pice $5.00
So the labels lbl
and lb2
will be updated with the contents of the last iteration of the for loop, i.e. pice
and $5.00
.
Actually you don't need the inner for loop. Just access the required contents using the column names:
def find():
with open(CsvFile) as csvcsv:
reader = csv.DictReader(csvcsv)
barcode = Entry1.get()
for row in reader:
if barcode == row['barcode']:
lbl.config(text=row['desc'])
lb2.config(text=row['pice'])
break
# it is better to use 'else' for the 'for' statement
else:
lbl.config(text='This Product is currently unavailable')