如何将tkintertable表的列按字典中的方式排序? [英] How can I have the tkintertable table's columns sorted the way they are in the dictionary?

查看:699
本文介绍了如何将tkintertable表的列按字典中的方式排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows上的 python 2.7 64位(使用Pycharm),并希望在我的项目的表中显示一些数据.我最初尝试使用pandastable,但由于它搜索python 3. has tkinter的名称而放弃了.我的问题是,给字典指定要导入的数据,例如:

I am working with python 2.7 64bit on Windows (using Pycharm) and want to display some data in a table for a project of mine. I tried using pandastable at first but gave up since it searches for the names python 3. has for tkinter. My problem is that, given the dictionary with the data to import for example:

data={'1': {'Klasa':'6A', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5},
      '2': {'Klasa':'', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5}}

我希望列名的排序顺序与字典中的顺序相同,但事实并非如此.它们实际上是排序的:

I expected that the columns names were sorted the same order they are in the dictionary but that is not the case. They are actually sorted:

'E Enjte', 'Klasa', 'E Premte', 'E Merkurre', 'E Hene', 'E Marte'

从左到右. 下面是我正在测试的代码.

from left to right. Below is the code I was testing.

from Tkinter import *
from tkintertable.Tables import TableCanvas
from tkintertable.TableModels import TableModel
master=Tk()
tframe = Frame(master)
tframe.pack(fill='both')
data={'1': {'Klasa':'6A', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5},
      '2': {'Klasa':'', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5}}
model = TableModel()
table = TableCanvas(tframe,model=model)
table.createTableFrame()
model = table.model
model.importDict(data) #can import from a dictionary to populate model
master.mainloop()

推荐答案

有两种方法可以做到这一点.

There are two ways you can do this.

model.importDict(data)之前,您应该在model上定义列:

Right before model.importDict(data), you should define the columns on model:

columns = ['Klasa', 'E Hene', 'E Marte', 'E Merkurre', 'E Enjte', 'E Premte']
for column in columns:
    model.addColumn(column)

2.使用 OrderedDict .

无论数据来自何处(例如CSV或数据库),都应使用collections.OrderedDict设置行字典:

2. Use OrderedDict.

Wherever your data comes from (e.g., a CSV or database), you should make your row dictionaries using collections.OrderedDict:

import collections

data = {'1': collections.OrderedDict([('Klasa', '6A'), ('E Hene', 1), ('E Marte', 2), ('E Merkurre', 3), ('E Enjte', 4), ('E Premte', 5)]),
        '2': collections.OrderedDict([('Klasa', ''), ('E Hene', 1), ('E Marte', 2), ('E Merkurre', 3), ('E Enjte', 4), ('E Premte', 5)])}

这篇关于如何将tkintertable表的列按字典中的方式排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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