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

前端 未结 4 746
后悔当初
后悔当初 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条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 08:59

    @Vaughn Cato gave an excellent answer here. However, he has accidentally included a bunch of extraneous code in his example. Here is a cleaned up and more organized full example doing exactly what his example does.

    from tkinter import *
    
    #Create & Configure root 
    root = Tk()
    Grid.rowconfigure(root, 0, weight=1)
    Grid.columnconfigure(root, 0, weight=1)
    
    #Create & Configure frame 
    frame=Frame(root)
    frame.grid(row=0, column=0, sticky=N+S+E+W)
    
    #Create a 5x10 (rows x columns) grid of buttons inside the frame
    for row_index in range(5):
        Grid.rowconfigure(frame, row_index, weight=1)
        for col_index in range(10):
            Grid.columnconfigure(frame, col_index, weight=1)
            btn = Button(frame) #create a button inside frame 
            btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)  
    
    root.mainloop()
    

    Screenshots:

    When it first opens (small):

    After you maximize the window:

提交回复
热议问题