如何在 Tkinter 中将框架置于框架中心?
我有一个使用 grid_propagate()
方法固定大小的框架。我想在这个框架内居中一个框架。我该怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
包装它以填充各个方向。根据需要添加填充。
或者,使用允许您使用相对或绝对定位的位置。您可以使用 0.5/.5 的相对 x/y 和“c”(中心)的锚点。
pack it to fill in all directions. Add padding as needed.
Or, use place which lets you use relative or absolute positioning. You can use a relative x/y of .5/.5 and an anchor of "c" (center).
如果您想将小部件(如框架)置于框架内居中,最简单的方法是通过
.grid()
。如果您使用.pack()
,您最终会卡在其中一条边上,因为pack()
有side
关键字。如果您使用
.place()
,那么您将被迫强制外框的大小(通常您不必这样做,但您已经这样做了,所以它不是一个问题),因为当框架像packed
或gridded
小部件一样自动调整大小时,不会检测到placed
小部件。我不知道为什么,但事情就是这样。因此,一般来说,将小部件置于框架内居中的最佳方法是将小部件网格化到框架中。 (
sticky
选项默认为 CENTER。)然后,如果您希望能够调整外框的大小并使小部件保持居中,则需要允许外框的单元格展开/增长。您可以通过.grid_rowconfigure()
等命令来执行此操作。因此,一个例子可能是: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, sincepack()
has theside
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), becauseplaced
widgets aren't detected when the frame autosizes like withpacked
orgridded
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. (Thesticky
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: