App 5: Desktop App with Windows & Buttons / Build a calculator
Lesson 3 of 10
Building the button grid
Instead of writing 16 buttons by hand, store the labels in a list of rows and make the buttons in a loop.
Key points
- Nested loops for rows and columns
- lambda passes each button its own label
- Fewer lines, fewer bugs
rows = ["789/", "456*", "123-", "0.=+"]
for r, row in enumerate(rows, start=1):
for c, ch in enumerate(row):
tk.Button(root, text=ch, font=("Arial", 18),
command=lambda ch=ch: press(ch)).grid(row=r, column=c, sticky="nsew")Your turn
Build the full button grid with the loop.
Quiz · +10 XP
Why write lambda ch=ch: press(ch) instead of lambda: press(ch)?
Log in to save progress and earn XP.