You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tkinter提取CSV选中行的指定列(Id)数据

提取选中行的Id列数据解决方案

核心修改点

  • 选中行返回的record是包含info和Id的列表,直接通过索引[1]即可提取Id列内容
  • 修复原代码中showinfo调用错误和answer变量未定义的问题

修改后的完整代码

import csv
import tkinter.ttk as ttk
from tkinter import *
from tkinter import messagebox as mb


def item_selected(event):
    # 存储所有选中的Id
    selected_ids = []
    for selected_item in tree.selection():
        item = tree.item(selected_item)
        record = item['values']
        # 提取Id列(列表索引为1,对应第二列数据)
        selected_id = record[1]
        selected_ids.append(selected_id)
        print(selected_id)  # 仅打印Id列内容
    
    # 弹窗展示选中结果并处理用户确认
    if selected_ids:
        mb.showinfo(title='已选中的Id', message='\n'.join(selected_ids))
        answer = mb.askyesno(title='确认选择', message='是否确认当前选择?')
        if answer:
            mb.showinfo(title='操作完成', message='感谢您的选择')
            # 此处可添加存储selected_ids的逻辑,比如写入文件或数据库
        else:
            mb.showinfo(title='返回', message='请重新选择')
            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'].strip()  # 去除CSV单元格中多余空格
        Id = row['Id'].strip()
        tree.insert("", 0, values=(info, Id))

if __name__ == '__main__':
    root.mainloop()

关键说明

  1. Id列提取逻辑:record是Treeview返回的整行数据列表,格式为[info值, Id值],因此record[1]直接对应Id列内容
  2. 批量存储支持:用selected_ids列表收集所有选中行的Id,方便后续批量操作(如写入文件、数据库)
  3. 原代码问题修复:
    • 将未限定命名空间的showinfo改为mb.showinfo(对应导入的messagebox as mb)
    • 通过mb.askyesno获取用户确认结果,解决原代码中answer变量未定义的问题
    • 读取CSV时添加strip()处理,去除单元格中可能存在的冗余空格

内容的提问来源于stack exchange,提问作者ISMAIL MULLA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:20:28