所以我目前正在编写一段代码,稍后将集成到其他东西中以充当设置配置器。目前,我想要一个像下面这样布局的窗口:
其中每个彩色框都是一个框架。这个窗口是不是 可调整大小并始终为 480x720 像素。因此,我希望我使用的 3 个框架、sideBar(黄色)、容器(蓝色)和静态(红色)始终保持相同的大小并以大致相同的比例填充如上图所示的窗口(不需要是精确的)。
此窗口的代码如下
self.window = tk.Tk()
self.windowHeight = 480
self.windowLength = 720
self.windowDimensions = str(self.windowLength)+"x"+str(self.windowHeight) #make diemnsions string; dimensions are set as a single string
self.window.geometry(self.windowDimensions)
self.window.resizable(width=False, height=False)
self.container = tk.Frame(self.window, relief="sunken", borderwidth=2) #instantiate new window
self.sideBar = tk.Frame(self.window, relief="sunken", borderwidth=2)
self.static = tk.Frame(self.window, relief="sunken", borderwidth=2)
self.sideBar.grid_propagate(False)
self.sideBar.grid(row=0, column=0)
self.container.grid(row=0,column=1)
self.static.grid(row=5, column=1)
self.configuratorObject = configuratorObject
audioButton = tk.Button(self.sideBar, text="Audio Page", command=lambda: self.raisePage("audioPage"))
colourButton = tk.Button(self.sideBar, text="Colours", command=lambda: self.raisePage("coloursPage"))
saveButton = tk.Button(self.static, text = "Save", state="disabled")
applyButton = tk.Button(self.static, text = "Apply", state="disabled")
audioButton.pack()
colourButton.pack()
saveButton.pack()
applyButton.pack()
我试图改变
height
和 width
网格的参数,但它们似乎真的没有做任何事情。那么我该如何明确定义框架的布局和大小呢?任何帮助表示赞赏
最佳答案
在你写的评论中
If theres a way of getting tkinter to do it then that'd be great
这绝对是首选方式,而不是强制小部件具有特定大小。
我们将从使用
pack
开始而不是 grid
对于三帧。对于这样的基本布局,它需要的代码行数少于 grid
.self.sideBar.pack(side="left", fill="y")
self.static.pack(side="bottom", fill="x")
self.container.pack(side="top", fill="both", expand=True)
接下来,添加左侧的按钮。这将导致左侧框架的宽度缩小以适合按钮。因为我们使用了
fill="y"
,高度将被强制保持为窗口的完整高度。audioButton.pack(side="top", fill="x")
colourButton.pack(side="top", fill="x")
最后,添加底部的按钮。您的原始代码显示它们从上到下堆叠,但您的插图将它们显示在一个水平行中。此示例与插图一致。
applyButton.pack(side="right", padx=10)
saveButton.pack(side="right", padx=10)
这样我们最终会得到一个如下所示的窗口,并且当您调整窗口大小时,比例和方向保持完全相同:
注意:您可以使用
grid
来执行此操作也是,但它需要多几行代码来对行和列应用权重。我个人更喜欢pack
当布局自然不适合网格时,因为它需要更少的代码行。
关于python - 如何在 tkinter 中显式调整帧大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62067726/