Python 从tkinter小部件获取字体对象

Python 从tkinter小部件获取字体对象,python,tkinter,fonts,Python,Tkinter,Fonts,如何从现有tkinter小部件获取字体对象?例如,我需要它来测量字符串。或者我可能想创建另一个具有相同字体的小部件,因此我将把这个字体对象传递给构造函数 我从中获取字体的小部件可能在程序中的其他地方明确设置了字体,也可能没有。无论哪种情况,解决方案都应该有效 这里有一个小的测试程序,显示我正在尝试做什么。我在Linux上用Python-3.4.3进行了尝试。如果解决方案是跨平台的,那就好了 import tkinter as tk import tkinter.font def test():

如何从现有tkinter小部件获取字体对象?例如,我需要它来测量字符串。或者我可能想创建另一个具有相同字体的小部件,因此我将把这个字体对象传递给构造函数

我从中获取字体的小部件可能在程序中的其他地方明确设置了字体,也可能没有。无论哪种情况,解决方案都应该有效

这里有一个小的测试程序,显示我正在尝试做什么。我在Linux上用Python-3.4.3进行了尝试。如果解决方案是跨平台的,那就好了

import tkinter as tk
import tkinter.font

def test():
    """ Demonstrate the ability to obtain font and use it. """
    font = myLabel.cget('font')
    print(font) # -misc-fixed-medium-r-normal--14-130-75-75-c-70-*-*
    print(type(font)) # <class 'str'>
    try:
        print(font.measure('My test text.')) # fail
    except Exception as e:
        print(e) # 'str' object has no attribute 'measure'
    try:
        # Try creating a new Font object from a string returned by cget('font').
        font = tkinter.font.Font(myLabel.cget('font')) # fail
        print(font.measure('My test text.'))
    except Exception as e:
        print(e) # 'str' object has no attribute 'call'

root = tk.Tk()
myLabel = tk.Label(root, text='My Label')
myLabel.pack(side=tk.TOP, padx=20, pady=20)
root.after(1000, test)
root.mainloop()  
将tkinter作为tk导入
导入tkinter.font
def test():
“”“演示获取字体并使用它的能力。”“”
font=myLabel.cget('font'))
打印(字体)#-misc-fixed-medium-r-normal--14-130-75-75-c-70-*-*
打印(字体)
尝试:
打印(font.measure(“我的测试文本”)#失败
例外情况除外,如e:
print(e)#“str”对象没有属性“measure”
尝试:
#尝试从cget返回的字符串(“字体”)创建新的字体对象。
font=tkinter.font.font(myLabel.cget('font'))#失败
打印(font.measure('我的测试文本'))
例外情况除外,如e:
print(e)#“str”对象没有属性“call”
root=tk.tk()
myLabel=tk.Label(root,text='My Label')
myLabel.pack(侧面=tk.TOP,padx=20,pady=20)
根。之后(1000,测试)
root.mainloop()
带有:

与:


@管用的,我试过了。Stackoverflow不是免费的编码服务,也不是为您进行研究、设计或编码工作的地方。@mcu nametofont()返回一个标准字体对象,您可以像使用任何其他字体实例一样使用它。@martineau:我只是提出了一个建议来帮助改进答案。这在Windows中对我有效,但在Linux中不起作用,除非我先为小部件明确指定字体。正如我所怀疑的,
tkinter.font.nametofont()
未能解析Linux中
w.cget('font')
返回的神秘的
-misc-fixed-medium-r-normal--14-130-75-75-c-70-*-*
。这是错误:
\u tkinter.TclError:命名字体-misc-fixed-medium-r-normal--14-130-75-75-c-70-*-*不存在
。在Windows中,
w.cget('font')
返回
TkDefaultFont
@mcu:不知道你在说什么…@mcu:有效,我试过了。Stackoverflow不是免费的编码服务,也不是为您进行研究、设计或编码工作的地方。@mcu nametofont()返回一个标准字体对象,您可以像使用任何其他字体实例一样使用它。@martineau:我只是提出了一个建议来帮助改进答案。这在Windows中对我有效,但在Linux中不起作用,除非我先为小部件明确指定字体。正如我所怀疑的,
tkinter.font.nametofont()
未能解析Linux中
w.cget('font')
返回的神秘的
-misc-fixed-medium-r-normal--14-130-75-75-c-70-*-*
。这是错误:
\u tkinter.TclError:命名字体-misc-fixed-medium-r-normal--14-130-75-75-c-70-*-*不存在
。在Windows中,
w.cget('font')
返回
TkDefaultFont
@mcu:不知道你在说什么…
import tkinter as tk
from tkinter import font
root = tk.Tk()
w = tk.Button()
wfont = font.nametofont(w.cget('font'))