Skip to content Skip to sidebar Skip to footer

Tkinter - Using Bind To Resize Frame Dynamically

I am trying to create a GUI front-end to display some data using python tkinter. I have a Frame which in-turn has other widgets like, button and list-box etc. I am trying to dynami

Solution 1:

You need to bind the following mouse events to perform frame resize:

  • <ButtonPress-1> (mouse left button pressed) to determine whether resize should be started based on mouse position
  • <ButtonRelease-1> (mouse left button released) to stop resize
  • <Motion> (mouse moving within frame) to perform resize if resize is started by mouse pressed

Below is a sample code:

from tkinter import *

HORIZONTAL = 1
VERTICAL   = 2classApp:
    def__init__(self, top):
        self.Frame1 = Frame(top, bd=5, relief='raised', width=100, height=100)
        self.Frame1.place(x=10, y=10)
        self.Frame1.bind("<ButtonPress-1>", self.start_resize)
        self.Frame1.bind("<ButtonRelease-1>", self.stop_resize)
        self.Frame1.bind("<Motion>", self.resize_frame)
        self.resize_mode = 0
        self.cursor = ''defcheck_resize_mode(self, x, y):
        width, height = self.Frame1.cget('width'), self.Frame1.cget('height')
        mode = 0if x > width-10: mode |= HORIZONTAL    
        if y > height-10: mode |= VERTICAL
        return mode

    defstart_resize(self, event):
        self.resize_mode = self.check_resize_mode(event.x, event.y)

    defresize_frame(self, event):
        if self.resize_mode:
            if self.resize_mode & HORIZONTAL:
                self.Frame1.config(width=event.x)
            if self.resize_mode & VERTICAL:
                self.Frame1.config(height=event.y)
        else:
            cursor = 'size'if self.check_resize_mode(event.x, event.y) else''if cursor != self.cursor:
                self.Frame1.config(cursor=cursor)
                self.cursor = cursor

    defstop_resize(self, event):
        self.resize_mode = 0

root = Tk()
root.geometry("800x600+400+50")
App(root)
root.mainloop()

Post a Comment for "Tkinter - Using Bind To Resize Frame Dynamically"