Skip to content

Commit e42c32e

Browse files
Library: Port 'Text Colors' to Python (#735)
Co-authored-by: Marco Capypara Köpcke <[email protected]>
1 parent 2e2a8dd commit e42c32e

File tree

1 file changed

+59
-0
lines changed
  • src/Library/demos/Text Colors

1 file changed

+59
-0
lines changed

src/Library/demos/Text Colors/main.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Pango is a text layout library. It can e.g. be used for formatting text
2+
# https://gjs-docs.gnome.org/pango10~1.0/
3+
import gi
4+
5+
gi.require_version("Gtk", "4.0")
6+
gi.require_version("Pango", "1.0")
7+
from gi.repository import Gtk, Pango
8+
import workbench
9+
10+
label: Gtk.Label = workbench.builder.get_object("label")
11+
12+
13+
def update_attributes():
14+
# A Pango Attribute List is used to style the label
15+
label.set_attributes(rainbow_attributes(label.get_label()))
16+
17+
18+
# Generates an Attribute List that styles the label in rainbow colors.
19+
# The `text` parameter is needed to detect string length + position of spaces
20+
def rainbow_attributes(text):
21+
rainbow_colors = (
22+
"#D00",
23+
"#C50",
24+
"#E90",
25+
"#090",
26+
"#24E",
27+
"#55E",
28+
"#C3C",
29+
)
30+
31+
# Create a color array with the length needed to color all the letters
32+
color_array = []
33+
i = 0
34+
while i < len(text):
35+
color_array += rainbow_colors
36+
i = len(color_array)
37+
38+
# Independent variable from `i` in the following loop to avoid spaces "consuming" a color
39+
color_idx = 0
40+
41+
attr_list_string = ""
42+
for i in range(len(text)):
43+
# Skip space characters
44+
if text[i] != " ":
45+
start_idx = i
46+
end_idx = i + 1
47+
48+
color = color_array[color_idx]
49+
color_idx += 1
50+
# See comment below
51+
attr_list_string += f"{start_idx} {end_idx} foreground {color},"
52+
53+
# For more info about the syntax for this function, see:
54+
# https://docs.gtk.org/Pango/method.AttrList.to_string.html
55+
return Pango.attr_list_from_string(attr_list_string)
56+
57+
58+
label.connect("notify::label", lambda _, __: update_attributes())
59+
update_attributes()

0 commit comments

Comments
 (0)