首页 > 解决方案 > 如何设置在 tkinter PanedWindow 中拖动的最大限制?

问题描述

import tkinter as tk
root = tk.Tk()
my_paned_window = tk.PanedWindow(master=root)
frame1 = tk.Frame(master=my_paned_window, bg='snow')
frame2 = tk.Frame(master=my_paned_window)
tk.Label(master=frame1, text='frame1').pack()
tk.Label(master=frame2, text='frame2').pack()
my_paned_window.add(frame1)
my_paned_window.add(frame2)
my_paned_window.pack(fill=tk.BOTH)
root.mainloop()

在上面的代码中,我不希望frame1在拖动时展开太多。如何为此设置限制?

标签: pythontkinter

解决方案


没有直接的方法可以做到这一点。您可以通过设置minsizeframe2 来实现此目的。

像这样的东西:

...
my_paned_window.add(frame1)
my_paned_window.add(frame2, minsize=550)
...

另一种方法是return "break"当窗扇位置大于最大宽度时,它不再可以移动。

最小的例子:

import tkinter as tk

class PanedWindow(tk.PanedWindow):

    def __init__(self, *args, **kwargs):
        super(PanedWindow, self).__init__(*args, **kwargs)
        self.max_width = {}
        self.bind("<B1-Motion>", self.check_width)
        self.bind("<ButtonRelease-1>", self.set_width)

    def add(self, child, max_width=None, *args):
        super(PanedWindow, self).add(child, *args)
        self.max_width[child] = max_width

    def check_width(self, event):
        
        for widget, width in self.max_width.items():
            if width and widget.winfo_width() >= width:
                self.paneconfig(widget, width=width) 
                return "break"

    def set_width(self, event):
        for widget, width in self.max_width.items():
            if width and widget.winfo_width() >= width:
                self.paneconfig(widget, width=width-1) 
      

root = tk.Tk()
my_paned_window = PanedWindow(master=root, sashwidth=5)

max_width = 500

frame1 = tk.Frame(master=my_paned_window, bg='red')
frame2 = tk.Frame(master=my_paned_window, bg='blue')
frame3 = tk.Frame(master=my_paned_window, bg="green")

tk.Label(master=frame1, text='frame1').pack()
tk.Label(master=frame2, text='frame2').pack()

my_paned_window.add(frame1, max_width=500)
my_paned_window.add(frame2)
my_paned_window.pack(fill=tk.BOTH, expand=True)

root.mainloop()

推荐阅读