Home > OS >  How to set a maximum limit for dragging in tkinter PanedWindow?
How to set a maximum limit for dragging in tkinter PanedWindow?

Time:09-22

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

In the above code, I don't want the frame1 to expand too much when dragged. How can I set a limit for this?

CodePudding user response:

There are no straightforward ways to do this. You can achieve this either by setting minsize for frame2.

Something like this:

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

Another way is to return "break" when the sash position is greater than the max-width so it no longer can be moved.

minimal example:

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