Welcome, guest | Sign In | My Account | Store | Cart
from Tkinter import *

class PannedGrid(PanedWindow):
		def __init__(self, master, tableOfWidgets, minsize='auto'):
			PanedWindow.__init__(self,master,orient=HORIZONTAL   )

			self.numberOfRows = len(tableOfWidgets)
			self.numberOfColumns = len(tableOfWidgets[0])
			RowHeightList = [0]*self.numberOfRows
			ColumnWidthList = [0]*self.numberOfColumns

			self.listOfColumnsFrames = []

			self.gridOfCellWidgets = \
				[[None for j in range(self.numberOfColumns)] for i in range(self.numberOfRows)]


			for j in range(self.numberOfColumns):

				columnFrame = Frame(self)
				columnFrame.pack(side=LEFT)
				columnFrame.pack_propagate(False)
				self.add(columnFrame, minsize=20)
				self.listOfColumnsFrames.append(columnFrame)

				for i in range(self.numberOfRows):
					cellFrame = Frame(columnFrame, bd=1, relief=SUNKEN)
					cellFrame.pack(expand=YES, fill=X)
					cellFrame.pack_propagate(False)
					widgetDefinition = tableOfWidgets[i][j]

					classObject, kwargs = widgetDefinition

					widget = classObject(cellFrame, **kwargs)
					widget.pack(expand=YES, fill=BOTH)
					widget.pack_propagate(False)

					RowHeightList[i] = max(RowHeightList[i],widget.winfo_reqheight())
					ColumnWidthList[j] = max(ColumnWidthList[j],widget.winfo_reqwidth())

					self.gridOfCellWidgets[i][j]= cellFrame


			tableHeight = sum(RowHeightList)

			for indexColumn, frameColumn in enumerate(self.listOfColumnsFrames):
				frameColumn.configure(width=ColumnWidthList[indexColumn], height=tableHeight)

				if minsize == 'auto':
					self.paneconfigure(frameColumn, minsize=ColumnWidthList[indexColumn])
				elif type(minsize) is int:
					self.paneconfigure(frameColumn, minsize=minsize)
				else:
					raise Exception("Minsize must be 'auto' or an integer.")


			for i in range(self.numberOfRows):
				for j in range(self.numberOfColumns):
					self.gridOfCellWidgets[i][j].configure(height=RowHeightList[i])


def test():
	import random

	root = Tk()

	numRows=4
	numColumns= 5

	tableGrid = []

	listOfColors = ['blue', 'red','green', 'yellow']
	listOfTexts = ['Something', 'Another thing', 'Word','This is still longer']

	tkinterWidgets = [ Label, Button, Checkbutton]

	for i in range(numRows):
		row = []
		for j in range(numColumns):
			row.append(
					[random.choice(tkinterWidgets),
						{   'bg':random.choice(listOfColors),
							'text':random.choice(listOfTexts)
						}
					]
				)
		tableGrid.append(row)


	PannedGrid(root, tableGrid,minsize=20).pack(expand=YES, fill=X, pady=2, padx='2m')

	root.mainloop()



if __name__ == '__main__':
	test()

History