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
2 Answers
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()
Comments
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:
Result to shrink:


tkinter.font.Fontclass has a methodmeasure()which returns the width of a message in pixels. You can use this method to calculate the required font size.