How to create a self resizing grid of buttons in tkinter?

前端 未结 4 723
后悔当初
后悔当初 2020-12-04 08:44

I am trying to create a grid of buttons(in order to achieve the clickable cell effect) with Tkinter.

My main problem is that I cannot make the grid and

4条回答
  •  萌比男神i
    2020-12-04 09:22

    You need to configure the rows and columns to have a non-zero weight so that they will take up the extra space:

    for x in range(60):
        Grid.columnconfigure(grid, x, weight=1)
    
    for y in range(30):
        Grid.rowconfigure(grid, y, weight=1)
    

    You also need to configure your buttons so that they will expand to fill the cell:

    btn.grid(column=x, row=y, sticky=N+S+E+W)
    

    This has to be done all the way up, so here is a full example:

    from tkinter import *
    
    root = Tk()
    frame=Frame(root)
    Grid.rowconfigure(root, 0, weight=1)
    Grid.columnconfigure(root, 0, weight=1)
    frame.grid(row=0, column=0, sticky=N+S+E+W)
    grid=Frame(frame)
    grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2)
    Grid.rowconfigure(frame, 7, weight=1)
    Grid.columnconfigure(frame, 0, weight=1)
    
    #example values
    for x in range(10):
        for y in range(5):
            btn = Button(frame)
            btn.grid(column=x, row=y, sticky=N+S+E+W)
    
    for x in range(10):
      Grid.columnconfigure(frame, x, weight=1)
    
    for y in range(5):
      Grid.rowconfigure(frame, y, weight=1)
    
    root.mainloop()
    

提交回复
热议问题