如何在 Tkinter 中将框架置于框架中心?

发布于 2024-10-03 07:18:50 字数 75 浏览 1 评论 0原文

我有一个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笛声青案梦长安 2024-10-10 07:18:50

包装它以填充各个方向。根据需要添加填充。

或者,使用允许您使用相对或绝对定位的位置。您可以使用 0.5/.5 的相对 x/y 和“c”(中心)的锚点。

import Tkinter as tk

root=tk.Tk()
f1 = tk.Frame(width=200, height=200, background="red")
f2 = tk.Frame(width=100, height=100, background="blue")

f1.pack(fill="both", expand=True, padx=20, pady=20)
f2.place(in_=f1, anchor="c", relx=.5, rely=.5)

root.mainloop()

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).

import Tkinter as tk

root=tk.Tk()
f1 = tk.Frame(width=200, height=200, background="red")
f2 = tk.Frame(width=100, height=100, background="blue")

f1.pack(fill="both", expand=True, padx=20, pady=20)
f2.place(in_=f1, anchor="c", relx=.5, rely=.5)

root.mainloop()
作死小能手 2024-10-10 07:18:50

如果您想将小部件(如框架)置于框架内居中,最简单的方法是通过 .grid()。如果您使用 .pack(),您最终会卡在其中一条边上,因为 pack()side 关键字。

如果您使用 .place(),那么您将被迫强制外框的大小(通常您不必这样做,但您已经这样做了,所以它不是一个问题),因为当框架像 packedgridded 小部件一样自动调整大小时,不会检测到 placed 小部件。我不知道为什么,但事情就是这样。

因此,一般来说,将小部件置于框架内居中的最佳方法是将小部件网格化到框架中。 (sticky 选项默认为 CENTER。)然后,如果您希望能够调整外框的大小并使小部件保持居中,则需要允许外框的单元格展开/增长。您可以通过 .grid_rowconfigure() 等命令来执行此操作。因此,一个例子可能是:

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文