在 tkinter.treeview 中选择一个单元格并获取单元格数据 [英] Select a cell in tkinter.treeview and get the cell data

查看:87
本文介绍了在 tkinter.treeview 中选择一个单元格并获取单元格数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用鼠标指针在 tkinter.treeview() 创建的表格中选择一个单元格并打印出该单元格的值.我该怎么做?

I would like to use a mouse pointer to select a cell in a table created by tkinter.treeview() and print out the cell's value. How can I do this?

以下是创建 tkinter.treeview 表的示例代码.在这种情况下,我想使用鼠标指针单击其中一个值,例如机场".但是,当我单击该单元格时,会改为选择整行(即小部件项).我怎样才能避免这种情况,以便我能得到我想要的?

Below is a sample code to create a tkinter.treeview table. In this case, I would like to use my mouse pointer to click on one of the values say "Airport". However, when I click that cell, the entire row (i.e. the widget item) is instead selected. How can I avoid this so that I can get what I want?

import tkinter as tk
import tkinter.ttk as ttk

class App(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.tree = ttk.Treeview(parent, columns=("size", "modified"))
        self.tree["columns"] = ("date", "time", "loc")

        self.tree.column("date", width=80)
        self.tree.column("time", width=80)
        self.tree.column("loc", width=100)

        self.tree.heading("date", text="Date")
        self.tree.heading("time", text="Time")
        self.tree.heading("loc", text="Loc")
        self.tree.bind('<ButtonRelease-1>', self.selectItem)

        self.tree.insert("","end",text = "Name",values = ("Date","Time","Loc"))
        self.tree.insert("","end",text = "John",values = ("2017-02-05","11:30:23","Airport"))
        self.tree.insert("","end",text = "Betty",values = ("2014-06-25","18:00:00","Orchard Road"))

        self.tree.grid()

    def selectItem(self, event):
        curItem = self.tree.focus()
        print (self.tree.item(curItem))


if __name__ == "__main__":
    window = tk.Tk()
    app = App(window)
    window.mainloop()

推荐答案

感谢 Bryan Oakley 的指导,我将 selectItem 回调修改为:

Thanks to Bryan Oakley's guidance, I have revised the selectItem callback to:

def selectItem(self, event):
    curItem = self.tree.item(self.tree.focus())
    col = self.tree.identify_column(event.x)
    print ('curItem = ', curItem)
    print ('col = ', col)

    if col == '#0':
        cell_value = curItem['text']
    elif col == '#1':
        cell_value = curItem['values'][0]
    elif col == '#2':
        cell_value = curItem['values'][1]
    elif col == '#3':
        cell_value = curItem['values'][2]
    print ('cell_value = ', cell_value)

它给了我想要的.希望这个脚本能帮助任何其他提出同样问题的人.

It gave me what I wanted. Hope this script will help any other asking the same question.

这篇关于在 tkinter.treeview 中选择一个单元格并获取单元格数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆