Advertisement
here2share

# tk_fit_text_to_canvas.py

Nov 27th, 2023
665
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. # tk_fit_text_to_canvas.py
  2.  
  3. import math
  4. import tkinter as tk
  5. from tkinter import ttk, font
  6.  
  7. root = tk.Tk()
  8.  
  9. font_families = font.families()
  10. for font_family in font_families:
  11.     print(font_family)
  12.  
  13. width_target = 500
  14.  
  15. # Define the initial font size
  16. font_size = 9
  17.  
  18. # Create a canvas to measure the text width
  19. canvas = tk.Canvas(root)
  20.  
  21. # Function to calculate the text width
  22. def calculate_text_width(text, font):
  23.     bbox = canvas.bbox(canvas.create_text(0, 0, text=text, font=font))
  24.     return bbox[2] - bbox[0]
  25.  
  26. # Adjust the font size to match the desired width
  27. while True:
  28.     font = ('Verdana', font_size)
  29.     text_width = calculate_text_width("Hello, World!", font)
  30.  
  31.     if text_width >= width_target:
  32.         break
  33.     else:
  34.         font_size += 1
  35.  
  36. # Create a label with the final font size
  37. label = ttk.Label(root, text="Hello, World!", font=font)
  38. label.pack()
  39.  
  40. # Run the Tkinter event loop
  41. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement