[Tutor] Tables in Tkinter
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Mar 5 15:46:29 EST 2017
On 04/03/17 01:47, Alan Gauld via Tutor wrote:
>> Can you please guide me to an example related to this problem?
I had a play and here is a simple DisplayTable widget.
Its still not a scrollable frame (although i might get round
to that later...) But it takes a list of headings and a 2D
list of data values and creates a display grid.
You can tweak the colours somewhat. Its a long way from
polished but should serve as a starter...
########## displaytable.py ##########
try:
import Tkinter as tk # v2
except ImportError:
import tkinter as tk # v3
class DisplayTable(tk.Frame):
def __init__(self, parent, headings, data,
hdcolor='red', datacolor='black',
gridcolor= 'black', cellcolor='white'):
tk.Frame.__init__(self, parent, bg=gridcolor)
if len(headings) != len(data[0]): raise ValueError
self.headings = headings
for index,head in enumerate(headings):
width = len(str(head))
cell = tk.Label(self,text=str(head),
bg=cellcolor, fg=hdcolor, width=width)
cell.grid(row=0,column=index, padx=1, pady=1)
for index,row in enumerate(data):
self.addRow(index+1,row,datacolor,cellcolor)
def addRow(self, row, data, fg='black', bg='white'):
for index, item in enumerate(data):
width = len(str(self.headings[index]))
cell = tk.Label(self,text=str(item),
fg=fg, bg=bg, width=width)
cell.grid(row=row, column=index, padx=1,pady=1)
if __name__ == "__main__":
top = tk.Tk()
tab = DisplayTable(top,
["Left","Right"],
[[1,2],
[3,4],
[5,6]],
datacolor='green')
tab.pack()
top.mainloop()
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list