2

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()
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144

1 Answers1

1

There are two ways you can do this.

1. Use a predefined column order.

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. 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)])}
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
  • I used your second suggestion and it works fine as for sorting the columns but when i try adding an element to a specific cell using 'table.model.data[row][col] = value' 'table.redrawTable()' the value goes to the right column but the wrong row. That is the case when data has more than 2 keys. I also tried making data an orderedDict but didn't work. – Lisien Semanjaku Dec 04 '15 at 20:11
  • @LisienSemanjaku You should ask that as a new question, and provide complete details such as what `row` and `col` are, and you expect to happen, and what actually happens. – Uyghur Lives Matter Dec 04 '15 at 21:31
  • Indeed. I have been checking Stack Overflow from some time now but since all the questions I have had, had already been discussed til now, I just registered recently. – Lisien Semanjaku Dec 04 '15 at 21:56