jakethefake
jakethefake

Reputation: 326

Tkinter using .grid() correctly

I'm creating a program that uses .grid(), and I'm having trouble placing two buttons next to each other (vertically). Here's my code:

canvas = Canvas(root, width=500, height=400, bg='green')
canvas.grid(row=1, column=2)

button1 = Button(root, text="Build Road")
button1.grid(row=1, column=0)
button2 = Button(root, text="Build Road")
button2.grid(row=2, column=0)

and here is the output: num

I want the two buttons to be vertically next to each other, like this:

num

And also, if possible, could I get a full line of these buttons, next to the canvas like this:

enter image description here

Is there something I'm doing wrong? Is it possible? If so, please tell me and give me an answer. Thanks

Upvotes: 0

Views: 156

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386342

What I recommend is to not use grid in this situation. You can more easily get what you want using pack. You clearly have two top-level elements: a canvas on the right and a stack of buttons on the left. So, create a frame for the buttons, and them pack them side-by-side:

button_frame = Frame(...)
canvas = Canvas(...)

button_frame.pack(side="left", fill="y")
canvas.pack(side="right", fill="both", expand=True)

With that, you can now create the button in the frame and lay them out independently of the canvas. Again, pack is the best choice since it is designed specifically to lay widgets out in a top-to-bottom and side-to-side manner:

button1 = Button(button_frame, ...)
button2 = Button(button_frame, ...)
...
button1.pack(side="top", fill="x")
button2.pack(side="top", fill="x")
...

If you really want to use grid, then the solution is to count how many buttons you have, and have the canvas span that many rows:

canvas.grid(row=1, column=2, rowspan=12)

Upvotes: 1

Vasilis G.
Vasilis G.

Reputation: 7859

You can set the rowspan parameter in grid method of canvas to be as the number of rows needed for the button of the desired output (12 in your case):

from tkinter import *

buttons = []

root = Tk()
canvas = Canvas(root, width=500, height=400, bg='green')
canvas.grid(row=1, rowspan=12, column=2) # Set the rowspan parameter

for i in range(1,13,1):
    button = Button(root, text="Build Road")
    button.grid(row=i, column=0)
    buttons.append(button)

root.mainloop()

I also used a list for your buttons, but this is just to demonstrate you how it works. You will propably not need it.

enter image description here

Upvotes: 1

Related Questions