Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_fit_text_to_canvas.py
- import math
- import tkinter as tk
- from tkinter import ttk, font
- root = tk.Tk()
- font_families = font.families()
- for font_family in font_families:
- print(font_family)
- width_target = 500
- # Define the initial font size
- font_size = 9
- # Create a canvas to measure the text width
- canvas = tk.Canvas(root)
- # Function to calculate the text width
- def calculate_text_width(text, font):
- bbox = canvas.bbox(canvas.create_text(0, 0, text=text, font=font))
- return bbox[2] - bbox[0]
- # Adjust the font size to match the desired width
- while True:
- font = ('Verdana', font_size)
- text_width = calculate_text_width("Hello, World!", font)
- if text_width >= width_target:
- break
- else:
- font_size += 1
- # Create a label with the final font size
- label = ttk.Label(root, text="Hello, World!", font=font)
- label.pack()
- # Run the Tkinter event loop
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement