How do I center a frame within a frame in Tkinter?

前端 未结 2 589
野的像风
野的像风 2021-01-12 08:05

I have a frame that I fixed the size of using the grid_propagate() method. I\'d like to center a frame within this frame. How do I go about this?

2条回答
  •  醉梦人生
    2021-01-12 08:53

    If you want to center a widget (like a frame) inside a frame, the easiest way to do it is via .grid(). If you use .pack(), you end up stuck along one of the edges, since pack() has the side keyword.

    If you use .place(), then you're stuck forcing the size of the outer frame (which normally you don't have to do, but you've already done it, so it's not an issue), because placed widgets aren't detected when the frame autosizes like with packed or gridded widgets. I'm not sure why, but that's the way it is.

    So, in general, the best way to center a widget inside a frame is to grid the widget into the frame. (The sticky option defaults to CENTER.) And then, if you want to be able to resize the outer frame and have the widget stay centered, you need to allow the outer frame's cell to expand/grow. You would do this via the .grid_rowconfigure() etc commands. So, an example might be:

            widget = Widget(frame, ...)
            widget.grid(row=0, column=0, sticky="")
            frame.grid_rowconfigure(0, weight=1)
            frame.grid_columnconfigure(0, weight=1)
    

提交回复
热议问题