我有一个2列的csv文件,使用tkinter我显示.csv文件,然后我选择我想要的特定行,但事情是我只想存储选定行的列数据,例如,如果我选择行1我需要存储列2行1的数据在一个变量中。请帮助我实现这一点下面我的csv文件
info,Id
ABC,123
CDE,456
EFG,789
下面是我的python代码
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()
预期的结果是,当我打印变量记录时,它应该打印仅ID示例,选择第1行时,变量应该仅包含123。我观察到的是['ABC','123']。它应该删除['ABC']并仅打印123。
任何形式的帮助将不胜感激。提前感谢。
1条答案
按热度按时间yvgpqqbh1#
可以使用
tree.set()
代替tree.item()
: