Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underline Text in Tkinter Label widget?

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.

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.

like image 824
Zac Brown Avatar asked Sep 07 '10 02:09

Zac Brown


People also ask

How do you underline in tkinter?

Sometimes, we need to style the font property of Label Text such as fontfamily, font-style (Bold, strike, underline, etc.), font-size, and many more. If we want to make the label text underlined, then we can use the underline property in the font attribute.

How do you underline text in Python?

To Underline Text In Python, the Unicode character "\u0332" , acts as an underline on the character that precedes it in a string. So, if you put any string after this Unicode, the text will be printed underlined in Python.

Can you change the text of a label in tkinter?

A label can include any text, and a window can contain many labels (just like any widget can be displayed multiple times in a window). You can easily change/update the Python Tkinter label text with the label text property. Changing the label's text property is another way to change the Tkinter label text.

Which widget is used to display or enter a single line text?

Sr.No. Widget for displaying single line of text. Widget that is clickable and triggers an action.


1 Answers

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:

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()
like image 196
Bryan Oakley Avatar answered Oct 23 '22 11:10

Bryan Oakley