Search code examples
pythontkintertkinter-scrolledtext

How to stop Tkinter ScrolledText widget resize on font change?


When I try to increase the font size the scrolledtext widget also increases and I want to keep the size of the scrolledtext widget unchanged no matter how I increase the size of the font.

When font size is 10
When font size is 15

as you look at the photo the scrolledtext widget change it's size when the font size changes and I want to stop my scrolledtext size from changing

# import GUI
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Spinbox

# create instance
win = tk.Tk()

# title name
win.title("Notepad ver.1.0")

# resizable option
win.resizable(True, True)

# geometry
win.geometry("1900x1000")


def click(e):
    GetFont = 'Arial, ' + str(FontSize.get())
    scr.configure(font=GetFont)

# frame 1
frame1 = ttk.LabelFrame(win, text='')
frame1.grid(column=0, row=0)

# font size
ttk.Label(frame1, text='Font Size:').grid(column=1, row=2)

# font spin box
FontSize = Spinbox(frame1, from_=10, to=60, width=4)
FontSize.grid(column=2, row=2)


# frame2
frame2 = ttk.LabelFrame(win, text='')
# set the width and height of your frame as desired using ipadx and ipady
frame2.grid(column=0, row=7, sticky=tk.S, ipadx=100, ipady=100)
# disable grid propagation to prevent resizing on font size changes
frame2.grid_propagate(False)

# scrolled text
ScrWidth = 150
ScrHight = 30
scr = scrolledtext.ScrolledText(frame2, width=ScrWidth, height=ScrHight)
scr.pack(fill="both", expand=True)
scr.config(font='Arial, 10')
scr.grid_propagate(False)

scr.insert(tk.INSERT, 'Sample Text')

win.bind("<ButtonRelease-1>", click)

# start GUI
win.mainloop()

I tried to google it and found some stackoverflow questions and I did what they suggested but it didn't work for my code.

Here is the link of the stackoverflow question: How to stop Tkinter Text widget resize on font change?


Solution

  • Since your ScrolledText widget is contained in a Frame, you'll want to disable grid_propagate for that Frame. Then you'll need to set the internal padding for the parent frame with ipadx and ipady, otherwise it will have 0 width and height

    # set the width and height of your frame as desired using ipadx and ipady
    frame2.grid(column=0, row=7, sticky=tk.S, ipadx=500, ipady=300)
    # disable grid propagation to prevent resizing on font size changes
    frame2.grid_propagate(False)