1

actually I am making a project with the help of tkinter in python so basically I want to shrink my font size of a label according to the width of the frame that it will be put in. I want that just i am giving a string and it will automatically adjust the size of the font according to the width. For an Example:- Let I am Giving a String that is " Hotel Raj Kundra and Family Resturant", let the width of the Frame/label is 500. so how it will automatically adjust in this size of window without wrapped the text. just fit in the window size

1
  • tkinter.font.Font class has a method measure() which returns the width of a message in pixels. You can use this method to calculate the required font size. Commented Apr 6, 2022 at 1:10

2 Answers 2

0

with .config you can adjust Attributes after you placed it. Now you can adjust the window size with the len() of your string. I hope it helps.

import tkinter as tk

def adjust_Window(canvas, text):

    canvas.config(width=len(text)*50)

def main():
    root = tk.Tk()

    canvas = tk.Canvas(root, width=500, height=500)
    canvas.pack()

    adjust_Window(canvas, "i hope it helps <3")

    root.mainloop()


if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

0

Easier way to do this:

from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

def update_width():
   l.configure(text='Hotel Raj Kundra and Family Resturant', background='blue', foreground='white', font=("Calibri,8,itlaic"))
   

# Create a frame
frame=Frame(win, background="skyblue3", width=700, height=250)
frame.pack()

# Add a button in the main window
ttk.Button(win, text="Update", command=update_width).pack()
l = ttk.Label(win, background='red', text="so how it will automatically adjust in this size of window without wrapped the text. just fit in the window siz" , font=("Calibri,32,Bold"))
l.pack()
          
win.mainloop()

Result widest:

enter image description here

Result to shrink:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.