Measure the height of a string in Tkinter Python?

谁都会走 提交于 2021-01-02 17:07:31

问题


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.


回答1:


This would do the trick.

tkinter.font.Font(font='TkDefaultFont').metrics('linespace')



回答2:


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.



来源:https://stackoverflow.com/questions/48726956/measure-the-height-of-a-string-in-tkinter-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!