1

On PySimpleGUI, how can I bold only a letter in a word with sg.Text(), like Hello?

I can only bold the entire word or with space between "H" and "ello" when I do [sg.Text("H", font=("bold")), sg.Text("ello").] Thanks.

jsmith0910
  • 111
  • 1

1 Answers1

1

Credit to Jason Yang (in comments); here is how you can use a Multiline element to bold a particular part of your text:

import PySimpleGUI as sg

# Note that the layout includes a Multiline element with a key to reference it, and it is disabled to keep users from editing the text
layout = [
    [sg.Multiline("", key='-VARIEDTEXT-', disabled=True)]
]

window = sg.Window("Test", layout, finalize=True)

# Use the .print function to add segments of text with specified font types
window["-VARIEDTEXT-"].print("H", font='bold', end='')
window["-VARIEDTEXT-"].print("ello", end='')

# This is just the regular window settings
while True:
    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

In order for the .print function to work, you must set the window to finalize=True. Also, by default, end='\n' which will create a new line. This is why you must set end='' to keep it all on the same line.

TeigeC
  • 86
  • 8
  • Nice . You can also "reroute cprint" in your Multiline `reroute_cprint=True` and then call `sg.cprint` instead of looking up multiline every time you want to print. `sg.cprint("H", font='bold', end='')` – Mike from PSG Jun 09 '23 at 09:56
  • If you want your `Multiline` to look the same as `Text` element would look, you could do something like: `sg.Multiline(key='-VARIEDTEXT-', disabled=True, reroute_cprint=True, no_scrollbar=True, border_width=0, background_color=sg.theme_background_color(), text_color=sg.theme_text_color())` – Mike from PSG Jun 09 '23 at 10:22