在Tkinter中,如何使一个框架在一个框架内居中?[英] How do I center a frame within a frame in Tkinter?

本文是小编为大家收集整理的关于在Tkinter中,如何使一个框架在一个框架内居中?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个框架,我固定了使用 grid_propagate()方法的大小.我想在此框架内将一个框架集中.我该怎么做?

推荐答案

打包它以填充所有方向.根据需要添加填充.

或使用可让您使用相对或绝对定位的位置.您可以使用.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()

其他推荐答案

如果要在框架内居中小部件(如框架),则最简单的方法是通过.grid().如果您使用.pack(),则最终沿其中一个边缘粘在其中一个边缘,因为pack()具有side关键字.

如果您使用.place(),那么您就卡住了强迫外帧的大小(通常您不必这样做,但是您已经做到了,所以这不是问题),因为<当帧自动使用packed或gridded窗口小部件时,C5>未检测到小部件.我不确定为什么,但是就是这样.

因此,通常,将小部件内部框架内部的最佳方法是grid将小部件置于框架中. (sticky选项默认为中心.)然后,如果您想能够调整外部帧大小并使小部件保持居中为中心,则需要允许外帧的单元格扩展/成长.您将通过.grid_rowconfigure()等命令来执行此操作.因此,一个例子可能是:

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

本文地址:https://www.itbaoku.cn/post/2091133.html

问题描述

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?

推荐答案

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

其他推荐答案

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)