Tkintertable获取选定的数据

时间:2013-10-16 12:08:31

标签: python tkinter

我正在使用tkintertable并想检查选择了哪一行。这可能吗? 而且我还想对列进行排序并按照我想要的名称命名...

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我有点晚了,但我想我会回答这个问题,万一其他人通过像我这样的谷歌搜索找到了这个:P

有几种方法可以根据鼠标点击选择数据。

首先,您需要将鼠标单击绑定到回调函数,并且在此回调函数中,您需要获取数据。您可能需要在释放时绑定鼠标单击,以便在释放鼠标按钮时抓取数据。

您可以使用table.get_row_clicked()/ table.get_col_clicked()函数以及model.getValueAt()来获取单个单元格。

获取字典中整行的内容,其中column_name = key&所选行的内容列= value,您需要使用model.getRecordAtRow(row_index)。

示例:

from Tkinter import *
from ttk import *
from tkintertable.Tables import TableCanvas
from tkintertable.TableModels import TableModel

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.model = TableModel()
        self.table = TableCanvas(self, model=self.model)
        self.table.createTableFrame()
        root.bind('<ButtonRelease-1>', self.clicked)   #Bind the click release event

        self.create_widgets()

    def create_widgets(self):
        self.table.model.load('save.table')  #You don't have to load a model, but I usually
        self.table.redrawTable()             #Create a base model for my tables.

        d = dir(self.table)  #Will show you what you can do with tables.  add .model
                             #to the end to see what you can do with the models.
        for i in d:
            print i

    def clicked(self, event):  #Click event callback function.
        #Probably needs better exception handling, but w/e.
        try:
            rclicked = self.table.get_row_clicked(event)
            cclicked = self.table.get_col_clicked(event)
            clicks = (rclicked, cclicked)
            print 'clicks:', clicks
        except: 
            print 'Error'
        if clicks:
            #Now we try to get the value of the row+col that was clicked.
            try: print 'single cell:', self.table.model.getValueAt(clicks[0], clicks[1])
            except: print 'No record at:', clicks

            #This is how you can get the entire contents of a row.
            try: print 'entire record:', self.table.model.getRecordAtRow(clicks[0])
            except: print 'No record at:', clicks

root = Tk()
root.title('Table Test')
app = Application(master=root)
print 'Starting mainloop()'
app.mainloop()

就其他事情而言,你应该能够从维基上获取信息:

http://code.google.com/p/tkintertable/wiki/Usage

有些事情很容易弄明白,但IMO值得。我仍然无法弄清楚如何以编程方式更改单元格的内容,而这正好在维基页面上,哈哈。