如何在Tkinter Label小部件中下划线文本?

19 投票
8 回答
49145 浏览
提问于 2025-04-16 03:47

我正在做一个项目,需要在Tkinter的Label控件中给一些文字加下划线。我知道可以使用下划线的方法,但我发现只能给控件中的一个字符加下划线,这个下划线是根据我传入的参数来决定的。比如:

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。

8 个回答

8

一行代码

mylabel = Label(frame, text = "my label", font="Verdana 15 underline")
15

对于那些在使用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)
24

要给标签里的所有文字加下划线,你需要创建一个新的字体,并把下划线的属性设置为真。下面是一个例子:

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()

撰写回答