Tkinter 标签小部件中的下划线文本?

新手上路,请多包涵

我正在开展一个项目,该项目要求我在 Tkinter 标签小部件中为某些文本添加下划线。我知道可以使用下划线方法,但根据参数,我似乎只能让它在小部件的 1 个字符下划线。 IE

 p = Label(root, text=" Test Label", bg='blue', fg='white', underline=0)

change underline to 0, and it underlines the first character, 1 the second etc

我需要能够在小部件中的所有文本下划线,我确信这是可能的,但是如何呢?

我在 Windows 7 上使用 Python 2.6。

原文由 Zac Brown 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

要为标签小部件中的所有文本添加下划线,您需要创建一种新字体,将下划线属性设置为 True。这是一个例子:

 try:
    import Tkinter as tk
    import tkFont
except ModuleNotFoundError:  # Python 3
    import tkinter as tk
    import tkinter.font as tkFont

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.count = 0
        l = tk.Label(text="Hello, world")
        l.pack()
        # clone the font, set the underline attribute,
        # and assign it to our widget
        f = tkFont.Font(l, l.cget("font"))
        f.configure(underline = True)
        l.configure(font=f)
        self.root.mainloop()

if __name__ == "__main__":
    app = App()

原文由 Bryan Oakley 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于那些在 Python 3 上工作但无法让下划线工作的人,这里是使其工作的示例代码。

 from tkinter import font

# Create the text within a frame
pref = Label(checkFrame, text = "Select Preferences")
# Pack or use grid to place the frame
pref.grid(row = 0, sticky = W)
# font.Font instead of tkFont.Fon
f = font.Font(pref, pref.cget("font"))
f.configure(underline=True)
pref.configure(font=f)

原文由 drewkiimon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题