简体   繁体   中英

Tkinter: Frame does not expand to fill remaining space inside root widget with grid()

I've been looking into similar threads, the only ones that I could understand were suggesting to use expand option of pack() method, I was wondering if it is possible to expand a frame to fill parent widget's available space with .grid() method?

import tkinter as tk

root = tk.Tk()
root.title('MSIV Preferences')
root.geometry('850x450')

frame = tk.Frame(root, bg='black')
frame.grid(column=0, row=0)
root.mainloop()

There are two things you need to do. First, you need to tell grid to have your frame fill the space that was allocated to it, and second, you need to tell grid to allocate all extra space to the row and column that contains your frame. The second step is only necessary if you want the widget to continue to fill the space as you resize the window.

The first is done with the documented sticky parameter, which tells a widget to "stick" to one or more sides of the space that was allocated to it. It takes a string of compass directions. For example, "nsew" stands for "north south east west". With that, the frame will stick to all four sides of the space allocated to it.

frame.grid(column=0, row=0, sticky="nsew")

The second step is to tell grid to allocate any extra space it has to the row and column that contains your frame. You do that by assigning a weight to one or more rows and columns. grid will allocate extra space relative to the weight . For example, with one column of weight 2, one of weight 1, and one of weight 0 (the default), for every three pixels of extra space, two will go one column and one will go to the other.

As a rule of thumb, when using grid you should always give at least one row and one column a positive weight.

In your case it would be like this:

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

Here is the complete program:

import tkinter as tk

root = tk.Tk()
root.title('MSIV Preferences')
root.geometry('850x450')

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

frame = tk.Frame(root, bg='black')
frame.grid(column=0, row=0, sticky="nsew")

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM