Search code examples
pythonpython-3.xtkintertkinter-layouttkinter-text

Adjusting text in tkinter Label to occupy all available space


Hy, I hope you are all doing well. I am building a Eye chart software in python tkinter which consists of Opto Charts. In Opto Charts all alphabet comes directly below each other. But when I try to add labels in tkinter, it forms V shape as with each row font size is decreasing. I want to occupy the label all the available space.

I managed to do that using mainFrame.rowconfigure(0, weight=1) but it only makes the label to full width not the text inside it. I have attached a screenshot for how it looks. enter image description here In the screenshot you can see the labels are set to full length of screen but text is in V shape as font size is decreasing from top to bottom. Is there a way to anchor the text to full width also. In others words each alphabet should come directly below the above one.

I hope I was clear, If you need to know anything else let me know.


Solution

  • If an image or bitmap is being displayed in the label then the value is in screen units; for text it is in characters.

    To occupy same space for different size of font, try to use image mode and use an empty image.

    import tkinter as tk
    from tkinter.font import Font
    
    texts = ('EDFHT', 'FPYUI', 'TOZQW', 'LPEDA', 'PECFD')
    sizes = (28, 24, 20, 16, 12)
    
    root = tk.Tk()
    
    factor = 2
    tkfont = Font(font=("Courier New", max(sizes), 'bold'))
    width, height = tkfont.measure("W")*factor, tkfont.metrics("linespace")*factor
    image = tk.PhotoImage(data='')
    
    for row, (text, size) in enumerate(zip(texts, sizes)):
        for column, t in enumerate(text):
            label = tk.Label(root, text=t, font=("Courier New", size, 'bold'), image=image, width=width, height=height, compound=tk.CENTER)
            label.grid(row=row, column=column)
    
    root.mainloop()
    

    enter image description here