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

点击Treeview获取Pandas DataFrame行索引时遇类型错误问题

问题:Tkinter Treeview双击行获取DataFrame索引报错

我想通过双击Treeview的行,获取从Excel导入的DataFrame的行索引,写了这段代码:

def OnDoubleClick(event): #use this to fill the row values by index and column
    browe.set(billing_tree.identify_row(event.y)) 
    print(browe.get())

其中browe是IntVar类型变量。运行后报错:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\uncsb\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 592, in get
    return self._tk.getint(value)
           ^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: expected integer but got "I001"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\uncsb\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\uncsb\OneDrive\Documents\Python\PythonApplication3\PythonApplication3.py", line 9893, in OnDoubleClick
    print(browe.get())
          ^^^^^^^^^^^
  File "C:\Users\uncsb\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 594, in get
    return int(self._tk.getdouble(value))
               ^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: expected floating-point number but got "I001"

我确认DataFrame的索引是数值型,但搞不懂为什么返回的是"I001"这类值。


原因与解决方案

原因

identify_row(event.y)返回的不是DataFrame的行索引,而是Tkinter Treeview内部的行ID,格式为I加数字(比如I001、I002),这是Treeview用来标识自身行的内部标识,和你导入的DataFrame索引没有直接关联。同时你把这个字符串类型的行ID赋值给IntVar,必然会因为类型不匹配报错。

解决步骤

  1. 绑定DataFrame索引到Treeview行:插入Treeview行时,要把DataFrame的索引存入该行的values或tags中,这样双击时才能提取到对应索引。
  2. 获取并转换索引:通过identify_row拿到内部行ID后,用item()方法取出该行数据,从中提取出之前绑定的DataFrame索引,再赋值给IntVar(确保是整数类型)。

示例代码

方式1:将索引存入values

插入Treeview行时的代码:

# 假设df是你的DataFrame
for idx, row in df.iterrows():
    # 把DataFrame索引idx作为values的第一个元素插入
    billing_tree.insert('', 'end', values=(idx, row['列名1'], row['列名2'], ...))

双击事件修正代码:

def OnDoubleClick(event):
    row_id = billing_tree.identify_row(event.y)
    if row_id:
        # 获取该行的values数据
        item_data = billing_tree.item(row_id)['values']
        # 提取第一个元素作为DataFrame索引
        df_index = item_data[0]
        # 赋值给IntVar
        browe.set(df_index)
        print(df_index)

方式2:将索引存入tags

插入Treeview行时的代码:

for idx, row in df.iterrows():
    # 把索引转为字符串存入tags
    billing_tree.insert('', 'end', values=(row['列名1'], row['列名2'], ...), tags=(str(idx),))

双击事件修正代码:

def OnDoubleClick(event):
    row_id = billing_tree.identify_row(event.y)
    if row_id:
        # 从tags中取出索引并转为整数
        df_index = int(billing_tree.item(row_id)['tags'][0])
        browe.set(df_index)
        print(df_index)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:45:27