Python Tkinter Label 小部件中的下划线文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3655449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Underline Text in Tkinter Label widget?
提问by Zac Brown
I am working on a project that requires me to underline some text in a Tkinter Label widget. I know that the underline method can be used, but I can only seem to get it to underline 1 character of the widget, based on the argument. i.e.
我正在做一个项目,该项目要求我在 Tkinter Label 小部件中为一些文本加下划线。我知道可以使用下划线方法,但是根据参数,我似乎只能让它为小部件的 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
I need to be able to underline all the text in the widget, I'm sure this is possible, but how?
我需要能够在小部件中的所有文本下划线,我确定这是可能的,但是如何?
I am using Python 2.6 on Windows 7.
我在 Windows 7 上使用 Python 2.6。
采纳答案by Bryan Oakley
To underline all the text in a label widget you'll need to create a new font that has the underline attribute set to True. Here's an example:
要为标签小部件中的所有文本加下划线,您需要创建一种新字体,将下划线属性设置为 True。下面是一个例子:
import Tkinter as tk
import 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()
回答by drewkiimon
For those working on Python 3 and can't get the underline to work, here's example code to make it work.
对于那些在 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)
回答by mihai
mylabel = Label(frame, text = "my label")
mylabel.configure(font="Verdana 15 underline")

