如何设置框架的最小和最大高度或宽度?

2024-05-19 10:22:59 发布

您现在位置:Python中文网/ 问答频道 /正文

Tkinter窗口的大小可以通过以下方法控制:

.minsize()
.maxsize()
.resizable()

是否有等效的方法来控制Tkinter或ttk帧的大小?

@Bryan:我把你的frame1.pack代码改成了:

frame1.pack(fill='both', expand=True)
frame1.bind( '<Configure>', maxsize )

我添加了这个事件处理程序:

# attempt to prevent frame from growing past a certain size
def maxsize( event=None ):
    print frame1.winfo_width()
    if frame1.winfo_width() > 200:
        print 'frame1 wider than 200 pixels'
        frame1.pack_propagate(0)
        frame1.config( width=200 )
        return 'break'

上面的事件处理程序检测到帧的宽度太大,但无法阻止大小的增加。这是Tkinter的限制还是我误解了你的解释?


Tags: 方法代码处理程序tkinter事件bryanwidthpack
2条回答

解决方法-至少对于最小大小:可以使用grid来管理根目录中包含的帧,并通过设置sticky=“nsew”使它们遵循网格大小。然后可以使用root.grid_rowconfigure和root.grid_columnconfigure设置minsize的值,如下所示:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

但正如Brian在2010:D中所写,如果不限制窗口的最小值,您仍然可以将窗口大小调整为小于框架。

没有一个魔法函数能将一个帧强制到最小或固定的大小。但是,您当然可以通过为框架指定宽度和高度来强制框架的大小。然后,可能还需要做两件事:将此窗口放入容器中时,需要确保几何图形管理器不会收缩或展开窗口。第二,如果框架是其他小部件的容器,请关闭grid或pack传播,这样框架就不会收缩或展开以适合自己的内容。

但是,请注意,这不会阻止您将窗口大小调整为小于内部框架。那样的话,框架就被剪断了。

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

相关问题 更多 >

    热门问题