Ayush Kumar
Ayush Kumar

Reputation: 75

Grid within frame in tkinter?

I am trying to build a grid structure in python tinker that is positioned aside each other without any free space in between, but I am somehow not able to achieve this.

Could anyone help in what am I doing wrong?

Here is the code.

import tkinter as tk


window = tk.Tk()

window.geometry("700x600")
frame1=tk.Frame(window,width=350,height=400,bg='black')
frame1.grid(row=0,column=0,rowspan=1,columnspan=1)


frame2=tk.Frame(window,width=350,height=600,bg='white')
frame2.grid(row=0,column=1)

frame3=tk.Frame(window,width=350,height=200,bg='red')
frame3.grid(row=1,column=0,rowspan=1,columnspan=1)


window.mainloop()

enter image description here

Here is the Output that I am getting, though what I want is that the black frame and red frame fit together without any gap in between, so that the overall height remains 600.

Upvotes: 1

Views: 682

Answers (2)

martineau
martineau

Reputation: 123463

The problem is because frame2 in the second column is taller than frame1 to the left of it. To workaround that, simply specify that it spans both rows that frame1 and frame3 occupy.

import tkinter as tk


window = tk.Tk()
window.geometry("700x600")

frame1=tk.Frame(window, width=350, height=400, bg='black')
frame1.grid(row=0, column=0, rowspan=1, columnspan=1)

frame2=tk.Frame(window, width=350, height=600, bg='white')
frame2.grid(row=0, column=1, rowspan=2)  # Added rowspan here.

frame3=tk.Frame(window, width=350, height=200, bg='red')
frame3.grid(row=1, column=0, rowspan=1, columnspan=1)

window.mainloop()

Result:

screenshot of result

Upvotes: 2

kesetovic
kesetovic

Reputation: 311

The problem is in the rowspan argument in frame2.

import tkinter as tk


window = tk.Tk()

window.geometry("700x600")
frame1 = tk.Frame(window, width=350, height=400, bg='black')
frame1.grid(row=0, column=0, rowspan=1, columnspan=1)

frame2 = tk.Frame(window, width=350, height=600, bg='white')
frame2.grid(row=0, column=1, rowspan=2) # here add rowspan = 2 argument

frame3 = tk.Frame(window, width=350, height=200, bg='red')
frame3.grid(row=1, column=0, rowspan=1, columnspan=1)


window.mainloop()

This is happening because you are having 2 frames on the left side both taking one row itself (2 rows total), and you need to span the right white frame to 2 rows to get the grid layout you want (to make them equal on right and left), otherwise it gets messed up because of difference between the number of frames in column 0 (2) and number of frames in column 1 (1).

Output you get after changing the code.

Upvotes: 1

Related Questions