Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure the height of a string in Tkinter Python?

I need the height in pixel of a string in a Tkiner widget. It is the text in a row of a Listbox.

I know I can measure the width of a string with tkinter.font.Font.measure. But how can I get the height? A similar question thematised only the width but not the height.

like image 653
buhtz Avatar asked Feb 11 '18 00:02

buhtz


People also ask

What does ttk do in tkinter?

The tkinter. ttk module provides access to the Tk themed widget set, introduced in Tk 8.5. If Python has not been compiled against Tk 8.5, this module can still be accessed if Tile has been installed.

How do I change height in tkinter?

However, tkinter has no height property to set the height of an Entry widget. To set the height, you can use the font('font_name', font-size) property. The font size of the text in an Entry widget always works as a height of the Entry widget.

What is Tk () in tkinter Python?

The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.)

What is tkinter default font size?

Output. Running the above code will set the default font as "lucida 20 bold italic" for all the widgets that uses textual information.


1 Answers

tkf.Font(font=widget['font']).metrics('linespace')

gives the height in pixels of a given widget's font:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
    import tkinter.font as tkf
except ImportError:
    import Tkinter as tk
    import tkFont as tkf


if __name__ == '__main__':
    root = tk.Tk()
    widget = tk.Label(root, text="My String")
    widget.pack()
    print(tkf.Font(font=widget['font']).metrics('linespace'))
    tk.mainloop()

Also note that the height of a one line string isn't dependent on its length, but only on its font in a particular environment.

like image 171
Nae Avatar answered Sep 27 '22 17:09

Nae