Home > Blockchain >  Tkinter Make Multiple Column/Single Row Grid Fit Frame Size
Tkinter Make Multiple Column/Single Row Grid Fit Frame Size

Time:12-09

I am trying to fit frame containing buttons to the grid. But I don't know how to recize the buttons depending on the grid cells size.

Below is my code :

def __init__(self, parent, controller):
    tk.Frame.__init__(self,parent)
    
    IWidth = self.winfo_width()
    FrmBtn= tk.Frame(self,bg='black',width = IWidth)
    FrmBtn.pack(expand=True, fill=BOTH,pady=10,padx=10)
    FrmBtn.grid_rowconfigure(0, weight=1)
    button = tk.Button(FrmBtn, text="Tab1",
                        command=lambda: controller.show_frame(TestPage1))
    button.grid(row=0,column=0,sticky="W")
    
    button1 = tk.Button(FrmBtn, text="Tab2",
                        command=lambda: controller.show_frame(TestPage1))
    button1.grid(row=0,column=1,sticky="W")
    
    button3 = tk.Button(FrmBtn, text="Tab3",
                        command=lambda: controller.show_frame(TestPage1))
    button3.grid(row=0,column=2,sticky="W")
    
    button4 = tk.Button(FrmBtn, text="Tab4",
                        command=lambda: controller.show_frame(TestPage1))
    button4.grid(row=0,column=3,sticky="W")
    FrmW= tk.Frame(self,bg='grey',width = IWidth)
    FrmW.pack(expand=True, fill=BOTH,pady=10,padx=10)

When I run the code I got :

enter image description here

but when I use cursor to resize the window I got :

enter image description here

or :

enter image description here

The Excepted Output would be stuff like :

enter image description here

or :

enter image description here

CodePudding user response:

I think you need to use Grid.rowconfigure() and Grid.rowconfigure().

In example code I commented the way yo can do it and what configure line do. Basicly it takes six buttons and place them in two columns (3 rows), and they resize with window. Example code:

import tkinter as tk
from tkinter import Grid, Button

root = tk.Tk()
root.title("resize button")
root.geometry("500x500")


# here you need to put on what do you want to use row configure, index(row) and weight
Grid.rowconfigure(root, 0, weight=1)  # we use on root, row=0 weight=1
Grid.columnconfigure(root, 0, weight=1)

#configure 2nd row
Grid.rowconfigure(root, 1, weight=1)


#configure 3rd row
Grid.rowconfigure(root, 2, weight=1)

#configure 2nd column
Grid.columnconfigure(root, 1, weight=1)

button1 = Button(root, text="Button1")
button2 = Button(root, text="Button2")
button3 = Button(root, text="Button3")

button1.grid(row=0, column=0, sticky="nsew")
button2.grid(row=1, column=0, sticky="nsew")
button3.grid(row=2, column=0, sticky="nsew")

button1_1 = Button(root, text="Button1_1")
button2_1 = Button(root, text="Button2_1")
button3_1 = Button(root, text="Button3_1")

button1_1.grid(row=0, column=1, sticky="nsew")
button2_1.grid(row=1, column=1, sticky="nsew")
button3_1.grid(row=2, column=1, sticky="nsew")

root.mainloop()
  • Related