Last active
August 30, 2024 04:06
-
-
Save thegamecracks/8f887d7438c711c31c8af12fdeecad7d to your computer and use it in GitHub Desktop.
Resizing Tkinter Text widgets by exact pixels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import contextlib | |
| from tkinter import IntVar, TclError, Text, Tk | |
| from tkinter.ttk import Entry, Frame | |
| app = Tk() | |
| app.title("Resizable Text") | |
| app.geometry("500x300") | |
| app.grid_columnconfigure(0, weight=1) | |
| app.grid_rowconfigure(0, weight=1) | |
| # This frame will be centered with above weights. | |
| # No sticky= needed; we will adjust the width/height as desired. | |
| text_frame = Frame(app, width=400, height=200) | |
| text_frame.grid() | |
| # This is the text widget we want to resize by pixels. | |
| text = Text(text_frame, font="TkDefaultFont") | |
| text.insert("1.0", "Hello world!") | |
| text.grid(sticky="nesw") | |
| # IMPORTANT: | |
| # Allow Text to expand, and disable the frame's grid propagation. | |
| # This makes the frame ignore the requested size of its children, | |
| # cropping them out of the frame if necessary. | |
| # | |
| # As a result, Text will always resize to fill its parent frame. | |
| # | |
| # This can also be done with pack using .pack_propagate(False). | |
| text_frame.grid_columnconfigure(0, weight=1) | |
| text_frame.grid_rowconfigure(0, weight=1) | |
| text_frame.grid_propagate(False) | |
| # Define our controls to set the text frame's size. | |
| size_controls = Frame(app) | |
| size_controls.grid(row=1, column=0, sticky="e") | |
| width_var = IntVar(app, value=text_frame["width"]) | |
| height_var = IntVar(app, value=text_frame["height"]) | |
| width_entry = Entry(size_controls, width=10, textvariable=width_var) | |
| width_entry.grid(row=0, column=0) | |
| height_entry = Entry(size_controls, width=10, textvariable=height_var) | |
| height_entry.grid(row=0, column=1) | |
| # A bit overly-engineered real-time resizing | |
| def on_width_write(name1: str, name2: str, op: str) -> None: | |
| with contextlib.suppress(TclError): | |
| width = width_var.get() | |
| width = min(max(width, 50), 1000) | |
| text_frame.configure(width=width) | |
| def on_height_write(name1: str, name2: str, op: str) -> None: | |
| with contextlib.suppress(TclError): | |
| height = height_var.get() | |
| height = min(max(height, 50), 1000) | |
| text_frame.configure(height=height) | |
| width_var.trace_add("write", on_width_write) | |
| height_var.trace_add("write", on_height_write) | |
| app.mainloop() |
Author
thegamecracks
commented
Aug 30, 2024

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment