'How can I add widgets in variable number of rows? (Grid) [closed]
Solution 1:[1]
I don't understand what is the problem.
Standard rule: if you have list/dictionary then use for
-loop (or while
-loop).
Minimal working example
import tkinter as tk
data = [
['A', 'X1', 'Y1'],
['B', 'X2', 'Y2'],
['C', 'X3', 'Y3'],
['D', 'X4', 'Y4'],
['E', 'X5', 'Y5'],
['F', 'X6', 'Y6'],
]
root = tk.Tk()
for item in data:
frame = tk.Frame(root)
tk.Label( frame, text=f'Row: {item[0]}' ).pack(side='left')
tk.Button(frame, text=f'Button: {item[1]}').pack(side='left')
tk.Button(frame, text=f'Button: {item[2]}').pack(side='left')
frame.pack()
root.mainloop()
Result:
BTW:
If you have similar objects then you could use tk.Frame
to create own widget
import tkinter as tk
# --- classes ---
class Row(tk.Frame):
def __init__(self, master, label, button1, button2):
super().__init__(master)
tk.Label( self, text=f'Row: {label}' ).pack(side='left')
tk.Button(self, text=f'Button: {button1}').pack(side='left')
tk.Button(self, text=f'Button: {button2}').pack(side='left')
# --- main ---
data = [
['A', 'X1', 'Y1'],
['B', 'X2', 'Y2'],
['C', 'X3', 'Y3'],
['D', 'X4', 'Y4'],
['E', 'X5', 'Y5'],
['F', 'X6', 'Y6'],
]
root = tk.Tk()
for item in data:
#row = Row(root, item[0], item[1], item[2])
row = Row(root, *item)
row.pack()
root.mainloop()
If you want to keep objects (labels, buttons) in the same columns then you would have to use directly .grid()
without Frame
import tkinter as tk
data = [
['A', 'X1', 'Y1'],
['B-longer', 'X2', 'Y2'],
['C', 'X3', 'Y3'],
['D', 'X4', 'Y4'],
['E', 'X5-longer', 'Y5'],
['F', 'X6', 'Y6-longer'],
]
root = tk.Tk()
for number, item in enumerate(data):
tk.Label( root, text=f'Row: {item[0]}' ).grid(column=0, row=number, sticky='we')
tk.Button(root, text=f'Button: {item[1]}').grid(column=1, row=number, sticky='we')
tk.Button(root, text=f'Button: {item[2]}').grid(column=2, row=number, sticky='we')
root.mainloop()
Result:
Without .grid()
you would get
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |