【问题标题】:Expand one widget vertically while locking another with Tkinter/ttk垂直扩展一个小部件,同时使用 Tkinter/ttk 锁定另一个小部件
【发布时间】:2018-03-11 14:53:33
【问题描述】:

我在一个框架内有一个树视图,它位于另一个包含按钮的框架之上。我希望在调整窗口大小时展开顶部框架,但不要让按钮框架这样做。

Python 2.7.5 中的代码:

    class MyWindow(Tk.Toplevel, object):
      def __init__(self, master=None, other_stuff=None):
        super(MyWindow, self).__init__(master)
        self.other_stuff = other_stuff
        self.master = master
        self.resizable(True, True)
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        # Top Frame
        top_frame = ttk.Frame(self)
        top_frame.grid(row=0, column=0, sticky=Tk.NSEW)
        top_frame.grid_columnconfigure(0, weight=1)
        top_frame.grid_rowconfigure(0, weight=1)
        top_frame.grid_rowconfigure(1, weight=1)

        # Treeview
        self.tree = ttk.Treeview(top_frame, columns=('Value'))
        self.tree.grid(row=0, column=0, sticky=Tk.NSEW)
        self.tree.column("Value", width=100, anchor=Tk.CENTER)
        self.tree.heading("#0", text="Name")
        self.tree.heading("Value", text="Value")

        # Button Frame
        button_frame = ttk.Frame(self)
        button_frame.grid(row=1, column=0, sticky=Tk.NSEW)
        button_frame.grid_columnconfigure(0, weight=1)
        button_frame.grid_rowconfigure(0, weight=1)

        # Send Button
        send_button = ttk.Button(button_frame, text="Send", 
        command=self.on_send)
        send_button.grid(row=1, column=0, sticky=Tk.SW)
        send_button.grid_columnconfigure(0, weight=1)

        # Close Button
        close_button = ttk.Button(button_frame, text="Close", 
        command=self.on_close)
        close_button.grid(row=1, column=0, sticky=Tk.SE)
        close_button.grid_columnconfigure(0, weight=1)

我在其他地方这样创建实例:

    window = MyWindow(master=self, other_stuff=self._other_stuff)

我尝试过的: 尝试锁定可调整性,这只会使按钮消失。我也尝试过改变权重,但我当前的配置是所有内容都显示在屏幕上的唯一方式。

无论高度多长,它都应该是什么样子:

我想防止的:

提前致谢。

【问题讨论】:

    标签: python tkinter widget treeview ttk


    【解决方案1】:

    问题不在于按钮框架在增长,而在于顶部框架在增长但并未使用所有空间。这是因为您将top_frame 的第 1 行的权重设为 1,但您没有在第 1 行中放置任何内容。由于其权重,额外的空间被分配给第 1 行,但第 1 行是空的。

    一种简单的可视化方法是将top_frame 更改为 tk(而不是 ttk)框架,并临时为其赋予独特的背景颜色。您会看到,当您调整窗口大小时,top_frame 将整个窗口填满,但部分为空。

    像这样创建top_frame

    top_frame = Tk.Frame(self, background="pink")
    

    ... 当您调整窗口大小时,会产生如下图所示的屏幕。请注意,粉红色的top_frame 正在显示,button_frame 仍然是其首选大小。

    您可以通过简单地删除这一行代码来解决此问题:

    top_frame.grid_rowconfigure(1, weight=1)
    

    【讨论】:

    • 您无法更好地解释这一点。我现在对网格及其工作原理有了更好的了解,谢谢!
    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    相关资源
    最近更新 更多