Advertisements
Hello I am struggling with tkinter grid_columnconfigure
. I am creating window with 3 frame. I want to center second frame. I found grid_rowconfigure(0, weight=1)
and grid_columnconfigure(0, weight=1)
. They are working but when I add third frame, my second frame shifting to the right.
Here’s my code:
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
root.geometry('600x400+500+250')
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
frame1 = tk.Frame(root, bg='red', width=50, height=50)
frame2 = tk.Frame(root, bg='green', width=50, height=50)
frame3 = tk.Frame(root, bg='blue', width=50, height=50)
frame1.grid(row=0, column=0, sticky='NW')
frame2.grid(row=1, column=1, sticky='S')
frame3.grid(row=0, column=2, sticky='NE')
tk.mainloop()
This is the result:
But I want this:
Thanks in advance
>Solution :
There are a lot of way to accomplish this, here is the simplest, imho:
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
root.geometry('600x400+500+250')
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)
frame1 = tk.Frame(root, bg='red', width=50, height=50)
frame2 = tk.Frame(root, bg='green', width=50, height=50)
frame3 = tk.Frame(root, bg='blue', width=50, height=50)
frame1.grid(row=0, column=0, sticky='NW')
frame2.grid(row=1, column=0, columnspan=2, sticky='S')
frame3.grid(row=0, column=1, sticky='NE')
tk.mainloop()
In your code, you are using three columns – which is still possible, but then a columnspan=3
would be needed for the green square.
Thank you for such a well explained question!
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)
root.grid_columnconfigure(2, weight=1)
frame1 = tk.Frame(root, bg='red', width=50, height=50)
frame2 = tk.Frame(root, bg='green', width=50, height=50)
frame3 = tk.Frame(root, bg='blue', width=50, height=50)
frame1.grid(row=0, column=0, sticky='NW')
frame2.grid(row=1, column=0, columnspan=3, sticky='S')
frame3.grid(row=0, column=2, sticky='NE')
Is another solution for comparison.