I have a csv file with 2 columns, Using tkinter I am displaying the .csv file and then I am selecting the particular row which I want, but the thing is I want to store only the column data of selected row for example if I am selecting row 1 I need to store the data of column 2 row 1 in a variable. Please help me out to achieve this Below i the csv file
info,Id
ABC,123
CDE,456
EFG,789
Below is my python code
import csv
import tkinter.ttk as ttk
from tkinter import *
from tkinter import messagebox as mb
def item_selected(event):
for selected_item in tree.selection():
item = tree.item(selected_item)
record = item['values']
print(record)
# show a message
showinfo(title='You have selected below', message=','.join(record))
if answer:
mb.showinfo(title='Progress', message='Thanks for selecting')
else:
mb.showinfo(title='Return Back', message='Please try again')
root.destroy()
root = Tk()
root.title("info and ID")
width = 500
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry("%dx%d %d %d" % (width, height, x, y))
root.resizable(0, 0)
TableMargin = Frame(root, width=500)
TableMargin.pack(side=TOP)
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("info", "Id"), height=400, selectmode="extended",
yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('info', text="info", anchor=W)
tree.heading('Id', text="Id", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=200)
tree.column('#2', stretch=NO, minwidth=0, width=200)
tree.bind('<<TreeviewSelect>>', item_selected)
tree.pack()
with open('data.csv') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
info = row['info']
Id = row['Id']
tree.insert("", 0, values=(info, Id))
# Main
if __name__ == '__main__':
root.mainloop()
The expected result is when i print variable record it should print the Only the ID Example for selecting row 1 the variable should contain only 123 What I am observing is ['ABC', '123'] It should eliminate ['ABC'] and print only 123.
Any kind of help will be appreciated. Thanks in Advance.
CodePudding user response:
You can use tree.set()
instead of tree.item()
:
def item_selected(event):
record = tree.set(tree.selection(), 'Id')
print(record)
...