Skip to content

Instantly share code, notes, and snippets.

@mnesarco
Created September 24, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnesarco/df03075d8806ed72d784ccabc2d52f12 to your computer and use it in GitHub Desktop.
Save mnesarco/df03075d8806ed72d784ccabc2d52f12 to your computer and use it in GitHub Desktop.
Grid Layout Internal DSL for TKinter
from tkinter import W, Tk
from tkinter import ttk
from grid import Grid, Row, RowConfigure, ColumnConfigure, GridOptions, Dummy
window = Tk()
window.title("Grid Layout DSL")
window.geometry('400x400')
def on_click():
print("Hello from Grid layout")
layout = Grid(
parent = window,
row_configure = RowConfigure(pad = 10),
col_configure = ColumnConfigure(pad = 10),
grid_options = GridOptions(sticky=W),
rows = [
Row(
children=[
ttk.Label(window ,text = "First Name:"),
ttk.Entry(window)]),
Row(
children=[
ttk.Label(window ,text = "Last Name:"),
ttk.Entry(window)]),
Row(
children=[
ttk.Label(window ,text = "Email:"),
ttk.Entry(window)]),
Row(
children=[
ttk.Label(window ,text = "Number:"),
ttk.Entry(window)]),
Row(
children=[
Dummy(window),
ttk.Button(window ,text="Submit", command=on_click)]),
]
)
layout.layout()
window.mainloop()
from tkinter import ttk
class LayoutOptions:
def __init__(self, **kwds):
self.__dict__.update(kwds)
def as_dict(self):
return self.__dict__
class GridOptions(LayoutOptions):
def __init__(self, **kwds):
super().__init__(**kwds)
class RowConfigure(LayoutOptions):
def __init__(self, **kwds):
super().__init__(**kwds)
class ColumnConfigure(LayoutOptions):
def __init__(self, **kwds):
super().__init__(**kwds)
class Widget:
def __init__(self, **kwds):
self.__dict__.update(kwds)
class Grid(Widget):
row_configure = RowConfigure()
column_configure = ColumnConfigure()
grid_options = GridOptions()
def __init__(self, **kwds):
super().__init__(**kwds)
self._column_layout_last = 0
def layout(self):
index = 0
for row in self.rows:
max_col = row.layout(index, self.grid_options)
for layout_col in range(self._column_layout_last, max_col):
self.parent.columnconfigure(layout_col, **self.column_configure.as_dict())
self.parent.rowconfigure(index, **self.row_configure.as_dict())
index += 1
class Row(Widget):
grid_options = GridOptions()
def __init__(self, **kwds):
super().__init__(**kwds)
def layout(self, row, parent_grid_options):
col = 0
for child in self.children:
if isinstance(child, Grid):
child.layout()
else:
child.grid(row=row, column=col, **parent_grid_options.as_dict())
child.grid(row=row, column=col, **self.grid_options.as_dict())
col += 1
return col
class Dummy(ttk.Label):
def __init__(self, parent):
super().__init__(parent, text="")
@mnesarco
Copy link
Author

License is: Do whatever you want with it. Attribution is welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment