我有一個包含 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()
預期的結果是當我列印變數記錄時,它應該列印 Only the ID Example for selection row 1 該變數應該只包含 123 我觀察到的是 ['ABC', '123'] 它應該消除 ['ABC'] 和僅列印 123。
任何形式的幫助將不勝感激。提前致謝。
uj5u.com熱心網友回復:
您可以使用tree.set()代替tree.item():
def item_selected(event):
record = tree.set(tree.selection(), 'Id')
print(record)
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512053.html
上一篇:未解決的參考“Tk”?[復制]
