Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Tkinter PandasTable Examples [GB]

It is few examples how to use pandastable to create table in tkinter with data from pandas dataframe.

Installation

pip install pandastable

Dependencies

  • numpy
  • pandas
  • matplotlib
  • numexpr

Optional dependencies

  • statsmodels
  • seaborn (requires scipy)

Doc: https://pandastable.readthedocs.io/

Standard Examples

In documentation you can find few examples

Minimal Example

It puts pandastable.Table in tk.Frame. It can't be root (Tk() or Toplevel())

python pandastable
import tkinter as tk
from pandastable import Table

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

pt = Table(frame
pt.show()

root.mainloop()

Right click on header shows context menu.

python pandastable

Right click on cell shows different context menu.

python pandastable

Doc: Table

Table with Toolbar and Statusbar

python pandastable
pt = Table(frame, showtoolbar=True, showstatusbar=True)
import tkinter as tk
from pandastable import Table

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, showtoolbar=True, showstatusbar=True)
pt.show()

root.mainloop()

Sample Data

It has two functions to generate random data.

from pandastable import TableModel

pt.model.df = TableModel.getSampleData()

pt.model.df = TableModel.getStackedData()
import tkinter as tk
from pandastable import Table, TableModel
import pandas as pd

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()
pt.model.df = TableModel.getSampleData()
#pt.model.df = TableModel.getStackedData()

root.mainloop()

Doc: getSampleData, getStackedData,

Source code: getSampleData, getStackedData,

Read Iris Data

There is function to load Iris data but it has bug. It tries to read iris.data but file has extension .cvs

pt.model.df = TableModel.getIrisData()  # doesn't work
import tkinter as tk
from pandastable import Table, TableModel
import pandas as pd

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()
pt.model.df = TableModel.getIrisData() # doesn't work

root.mainloop()

To read it needs own code

import os
import pandastable

fullpath = os.path.join(os.path.dirname(pandastable.__file__), 'datasets', 'iris.csv')
cols = ['sepal length','sepal width','petal length','petal width','class']
pt.model.df = pd.read_csv(fullpath, names=cols)
import os
import tkinter as tk
import pandastable
from pandastable import Table, TableModel
import pandas as pd

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

fullpath = os.path.join(os.path.dirname(pandastable.__file__), 'datasets', 'iris.csv')
cols = ['sepal length','sepal width','petal length','petal width','class']
pt.model.df = pd.read_csv(fullpath, names=cols)

root.mainloop()

There are other CSV file installed with pandastable but they don't have special function to load

Doc: getIrisData

Source code: getIrisData

Using existing DataFrame

python pandastable

Assign DataFrame when table is created

pt = Table(frame, dataframe=df)

Assign DataFrame when table already exists.

pt.model.df = df

It can be used to replace data in table. Often it may need pt.redraw() to redraw Table in window.

import tkinter as tk
from pandastable import Table
import pandas as pd

df = pd.DataFrame({
    'A': [1,2,3,4,5,6,],
    'B': [1,1,2,2,3,3,],
    'C': [1,2,3,1,2,3,],
    'D': [1,1,1,2,2,2,],
})

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, dataframe=df)
pt.show()

root.mainloop()

Read CSV file

To read CSV file *.csv, *.tsv, *.txt

pt.importCSV('path/input.csv')
pt.importCSV(filename='path/input.csv')

You can also display dialog window to set values before import

pt.importCSV('path/input.csv', True)
pt.importCSV(filename='path/input.csv', dialog=True)

it uses kwargs to set values in pandas.read_csv() - ie sep

pt.importCSV('path/input.csv', sep='.')
import tkinter as tk
from pandastable import Table

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

pt.importCSV(filename='path/input.csv', dialog=True)

root.mainloop()

Ask for CSV file name - show FileDialog

Using importCSV() without arguments it opens FileDialog which let you select from *.csv, *.tsv, *.txt

pt.importCSV()
import tkinter as tk
from pandastable import Table

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, dataframe=df)
pt.show()

pt.importCSV() # it will open FileDialog and ask for filename

root.mainloop()

Source Code: Table.importCSV

Load Excel file

Load Excel file *.xls, *.xls

pt.loadExcel('path/filename.xls')

Open FileDialog and ask for file *.xls, *.xls

pt.loadExcel()
import tkinter as tk
from pandastable import Table

def import_data():
    pt.loadExcel()

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

button = tk.Button(root, text='Load Excel', command=import_data)
button.pack()

root.mainloop()

Use different folder in FileDialog

To open FileDialog in different folder you can set pt.importpath

pt.importpath = 'path/to/folder/'
pt.importCSV()
import tkinter as tk
from pandastable import Table

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

pt.importpath = '/home/user/documents/'
pt.importCSV()

root.mainloop()

Load from other files

Loads from *.mpk (msgpack), *.pickle (pickle)

pt.load()

Export

Using standard Button to import CSV.

import tkinter as tk
from pandastable import Table

# --- functions ---

def import_csv():
    pt.importCSV()

# --- main ---

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

button = tk.Button(root, text='Import CSV', command=import_csv)
button.pack()

root.mainloop()

Doc: [Table.importCSV]( Source code: Table.importCSV

Images for Buttons

Images are avaliable in pandastable.images as functions which return tk.PhotoImage

from pandastable import images

img = images.importcsv()
button = tk.Button(root, image=img)
import tkinter as tk
from pandastable import Table
from pandastable import images

# --- functions ---

def import_csv():
    pt.importCSV()

# --- main ---

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

img = images.importcsv()
button = tk.Button(root, image=img, command=import_csv)
button.pack()

root.mainloop()

Every image has to be assigned to separated variable. Because it is use PhotoImage it may have problem with bug in PhotoImage and it has to be assigned to global variable.

import tkinter as tk
from pandastable import Table
from pandastable import images

# --- functions ---

def my_callback():
    print('callback')

# --- main ---

root = tk.Tk()
root.title('PandasTable Example')

# - toolbar -

toolbar = tk.Frame(root)
toolbar.pack()

img1 = images.importcsv()
button = tk.Button(toolbar, image=img1, command=my_callback)
button.pack(side='left', ipadx=3, ipady=3)

img2 = images.copy()
button = tk.Button(toolbar, image=img2, command=my_callback)
button.pack(side='left', ipadx=3, ipady=3)

img3 = images.accept()
button = tk.Button(toolbar, image=img3, command=my_callback)
button.pack(side='left', ipadx=3, ipady=3)

# - table -

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

root.mainloop()

Create buttons using pandastable.dialogs.addButton

It has method addButton to create button

import tkinter as tk
from pandastable import Table
from pandastable import images
from pandastable.dialogs import addButton

# --- functions ---

def my_callback():
    print('callback')

# --- main ---

root = tk.Tk()
root.title('PandasTable Example')

# - toolbar -

toolbar = tk.Frame(root)
toolbar.pack()

img1 = images.importcsv()
img2 = images.copy()
img3 = images.accept()
addButton(toolbar, 'Import CSV', my_callback, img1, side='left')
addButton(toolbar, 'Copy',       my_callback, img2, side='left')
addButton(toolbar, 'Accept',     my_callback, img3, side='left')

# - table -

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame)
pt.show()

root.mainloop()

Color Columns

import tkinter as tk
from pandastable import Table
import pandas as pd

df = pd.DataFrame({
    'A': [1,2,3,4,5,6,],
    'B': [1,1,2,2,3,3,],
    'C': [1,2,3,1,2,3,],
    'D': [1,1,1,2,2,2,],
})

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, dataframe=df)
pt.show()

pt.setColumnColors(cols=0, clr='red')
pt.setColumnColors(cols=[1, 2], clr='green')
pt.setColumnColors(cols=[-1], clr='#a0a0ff')

root.mainloop()
import tkinter as tk
from pandastable import Table
import pandas as pd

df = pd.DataFrame({
    'A': [1,2,3,4,5,6,],
    'B': [1,1,2,2,3,3,],
    'C': [1,2,3,1,2,3,],
    'D': [1,1,1,2,2,2,],
})

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, dataframe=df)
pt.show()

pt.setColorByMask(col='A', clr='yellow', mask=(df['B']==2))

root.mainloop()
import tkinter as tk
from pandastable import Table
import pandas as pd

df = pd.DataFrame({
    'A': [1,2,3,4,5,6,],
    'B': [1,1,2,2,3,3,],
    'C': [1,2,3,1,2,3,],
    'D': [1,1,1,2,2,2,],
})

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, dataframe=df)
pt.show()

pt.setRowColors(rows=2, clr='red', cols='all')
pt.setRowColors(rows=[3, 4], clr='green', cols=[0, 1])
pt.setRowColors(rows=[5], clr='blue', cols=[-3, -1])

root.mainloop()
import tkinter as tk
from pandastable import Table
import pandas as pd

df = pd.DataFrame({
    'A': [1,2,3,4,5,6,],
    'B': [1,1,2,2,3,3,],
    'C': [1,2,3,1,2,3,],
    'D': [1,1,1,2,2,2,],
})

root = tk.Tk()
root.title('PandasTable Example')

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

pt = Table(frame, dataframe=df)
pt.show()

pt.columncolors['A'] = 'red'
pt.columncolors['B'] = 'green'

root.mainloop()
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury