[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Improve the DragFrame class in tkinter and Python

[This version repositions its frame if necessary when you resize it]

The post Make a frame that lets you drag its contents in tkinter and Python builds a DragFrame class that lets you use the mouse to drag the items in the frame's scrolling area. One feature that I was too lazy to implement was to make the class rearrange its frame if you resized it. For example, if you made the form small, dragged the scrolling area up and to the left, and then enlarged the form, the class's canvas widgets might show empty area to the right and below its contents.

This example fixes that. It requires only two changes.

First, after creating its canvas widget, the new version's constructor uses the following code to watch for configure events.

self.canvas.bind('<Configure>', self.resize)

Second, when the canvas is configured (its size, position, or border width changes), the following code executes.

def resize(self, event): '''Make sure the frame is properly positioned.''' # Make sure the frame is correctly positioned. # Calculate maximum X and Y coordinates. self.min_x = self.canvas.winfo_width() - self.frame.winfo_width() self.min_y = self.canvas.winfo_height() - self.frame.winfo_height() x = old_x = self.frame.winfo_x() y = old_y = self.frame.winfo_y() if x < self.min_x: x = self.min_x if y < self.min_y: y = self.min_y if x > 0: x = 0 if y > 0: y = 0 if x != old_x or y != old_y: self.frame.place(x=x, y=y)

This code calculates the minimum X and Y values that the frame should use as described in the previous post. It then adjusts the x and y values accordingly (again, as in the previous post).

If the modified X and Y coordinates are different from the frame's current coordinates, the code moves the frame there.

Now if you resize the program, it ensures that its frame remains in a valid position.

Download the example to see addition details and to experiment with it.

© 2024 - 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.