aboutsummaryrefslogtreecommitdiff
path: root/test/fixratio.py
diff options
context:
space:
mode:
Diffstat (limited to 'test/fixratio.py')
-rw-r--r--test/fixratio.py33
1 files changed, 33 insertions, 0 deletions
diff --git a/test/fixratio.py b/test/fixratio.py
new file mode 100644
index 0000000..a9393cd
--- /dev/null
+++ b/test/fixratio.py
@@ -0,0 +1,33 @@
+import tkinter as tk
+WIDTH, HEIGHT = 400, 300 # Defines aspect ratio of window.
+
+def maintain_aspect_ratio(event, aspect_ratio):
+ """ Event handler to override root window resize events to maintain the
+ specified width to height aspect ratio.
+ """
+ if event.widget.master: # Not root window?
+ return # Ignore.
+
+ # <Configure> events contain the widget's new width and height in pixels.
+ new_aspect_ratio = event.width / event.height
+
+ # Decide which dimension controls.
+ if new_aspect_ratio > aspect_ratio:
+ # Use width as the controlling dimension.
+ desired_width = event.width
+ desired_height = int(event.width / aspect_ratio)
+ else:
+ # Use height as the controlling dimension.
+ desired_height = event.height
+ desired_width = int(event.height * aspect_ratio)
+
+ # Override if necessary.
+ if event.width != desired_width or event.height != desired_height:
+ # Manually give it the proper dimensions.
+ event.widget.geometry(f'{desired_width}x{desired_height}')
+ return "break" # Block further processing of this event.
+
+root = tk.Tk()
+root.geometry(f'{WIDTH}x{HEIGHT}')
+root.bind('<Configure>', lambda event: maintain_aspect_ratio(event, WIDTH/HEIGHT))
+root.mainloop()