Skip to content

Commit fe69c55

Browse files
committed
Library: Port 'Text Colors' to Python
1 parent 5486d70 commit fe69c55

File tree

1 file changed

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

1 file changed

+60
-0
lines changed

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

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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 updateAttributes():
14+
# A Pango Attribute List is used to style the label
15+
label.set_attributes(rainbowAttributes(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 rainbowAttributes(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+
colorArray = []
33+
i = 0
34+
while i < len(text):
35+
colorArray += RAINBOW_COLORS
36+
i = len(colorArray)
37+
38+
# Independent variable from `i` in the following loop to avoid spaces "consuming" a color
39+
colorIdx = 0
40+
41+
attrListString = ""
42+
for i in range(len(text)):
43+
# Skip space characters
44+
if text[i] != " ":
45+
startIdx = i
46+
endIdx = i + 1
47+
48+
color = colorArray[colorIdx]
49+
colorIdx += 1
50+
# See comment below
51+
attrListString += f"{startIdx} {endIdx} 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+
print(attrListString)
56+
return Pango.attr_list_from_string(attrListString)
57+
58+
59+
label.connect("notify::label", lambda _, __: updateAttributes())
60+
updateAttributes()

0 commit comments

Comments
 (0)