Search code examples
pythontkintertextscalefont-size

Changing Font Size


I would like to know how can I resize text font in Text widget in Tkinter without resize text box.

Here is my code:

from tkinter import *

root = Tk() 

def font_size(value):
    text.configure(font =("Comic Sans MS", H_Scale.get())) 
    print(H_Scale.get())

text = Text(root, width=10, height=10)
text.pack()
H_Scale = Scale(root, from_=1, to=72,orient=HORIZONTAL,command=font_size)
H_Scale.place(x=1, y=100)
root.geometry("400x240") 
root.mainloop() 

While I change scale bar value I expect to change only font size but as you can see whole Text widget resize.

I appreciate if let me know what is the problem and show me the remedy.


Solution

  • Try the following. I think it will be more to your requirements.

    from tkinter import *
    root = Tk()
    
    def font_size(value):
        text.configure(font=("Comic Sans MS", int(value)))
    
    # Create a frame to hold the Text widget and prevent resizing
    frame = Frame(root, width=300, height=180)
    frame.pack_propagate(False)  # Prevent the frame from resizing based on the Text widget's size
    frame.pack()
    
    text = Text(frame) # Create a Text widget inside the frame
    text.pack(expand=True, fill='both')  # Make the Text widget fill the frame without resizing
    
    H_Scale = Scale(root, from_=1, to=72, orient="horizontal", command=font_size)
    H_Scale.place(x=1, y=190)
    root.geometry("400x240")
    root.mainloop()