How to get .grid_columnconfigure() working inside Frame?

你说的曾经没有我的故事 提交于 2019-12-11 08:03:47

问题


I want to create a GUI with tkinter in python using grid-Method and grid_columnconfigure/grid_rowconfigure. Unfortunately, this is not working inside a Frame. How can I get this work?

from tkinter import *

master = Tk()
master.state('zoomed')
f = Frame(master, width=800, height=400)

Label1 = Label(f, text='Label 1')
Label2 = Label(f, text='Label 2')

f.grid_columnconfigure(0, weight=1)
f.grid_columnconfigure(2, weight=1)
f.grid_columnconfigure(4, weight=1)

Label1.grid(row=0, column=1)
Label2.grid(row=0, column=3)

f.pack()

master.mainloop()

ADDITIONAL QUESTION: I got great answers, all is working fine with pack-Manager. But how could I do this if using grid-Manager?


回答1:


The grid_columnconfigure is working fine. The problem is that your frame will by default set its size to the smallest possible size to fit the labels. Since empty columns don't have a size, the frame will be just wide enough to hold the two labels.

This will be easy to visualize if you give frame a distinctive color during development. It also sometimes helps to give the frame a visual border so you can see its boundaries.

While I don't know what your ultimate goal is, you can see the spaces between the column if you have the frame fill the entire window:

f.pack(fill="both", expand=True)

If you want to use grid instead of pack, you have to do a bit more work. In short, put the frame in row 0 column 0, and give that row and column a non-zero weight so that grid will give all unused space to that row and column.

f.grid(row=0, column=0, sticky="nsew")
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)

If you want to force the window to be a specific size, you can use the geometry method of the master window:

master.geometry("800x400")


来源:https://stackoverflow.com/questions/57168146/how-to-get-grid-columnconfigure-working-inside-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!