Home > Mobile >  Hey All, I want to display the selected row from csv file but I am missing something that it is prit
Hey All, I want to display the selected row from csv file but I am missing something that it is prit

Time:09-01

Below is my code and csv file looks like

serail_number, Mac_Id
001, 19bc
002, 19bd
from tkinter import *
import tkinter.ttk as ttk
import csv
def OnDoubleClick(event):
    item = tree.selection()
    print('item:', item)
    print('event:', event)
    item = tree.selection()[0]
    print("you clicked on", tree.item(item,"text"))
root = Tk()
root.title("Python - Import CSV File To Tkinter Table")
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=("Serial number", "Mac 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('Serial number', text="Serial number", anchor=W)
tree.heading('Mac Id', text="Mac 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>>", OnDoubleClick)
tree.pack()
with open('data.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        serial_number = row['serial_number']
        Mac_Id = row['Mac_Id']
        tree.insert("", 0, values=(serial_number, Mac_Id))
#Main
if __name__ == '__main__':
    root.mainloop()**

As it is printing only row1 and column 1 when you select but I want to print both row1, Column1 and column2 and store the data into the variable

CodePudding user response:

change this:

print("you clicked on", tree.item(item,"text"))

to this:

values = tree.item(tree.selection())['values']
print("you clicked on", item, values)

or for everything in one list in one list, use:

values = [item]   tree.item(tree.selection())['values']
print("you clicked on", values)
  • Related