or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

color-drawing.mdcontainer-widgets.mdcore-widgets.mddisplay-widgets.mdevent-system.mdfile-dialogs.mdindex.mdinput-widgets.mdlayouts.mdmodel-view.mdtext-editing.mdutilities.md

color-drawing.mddocs/

0

# Color and Drawing

1

2

Advanced color support, drawing capabilities, and theming system with ANSI color support, gradients, and custom drawing operations.

3

4

## Capabilities

5

6

### Color System

7

8

TTkColor provides comprehensive color support for terminal applications with ANSI escape sequences.

9

10

```python { .api }

11

class TTkColor:

12

def __init__(self, fg=None, bg=None, **kwargs):

13

"""

14

Initialize a color object.

15

16

Parameters:

17

- fg: Foreground color (hex string, RGB tuple, or color name)

18

- bg: Background color (hex string, RGB tuple, or color name)

19

- bold (bool): Bold text style

20

- italic (bool): Italic text style

21

- underline (bool): Underline text style

22

"""

23

24

def foreground(self):

25

"""Get the foreground color."""

26

27

def setForeground(self, color):

28

"""Set the foreground color."""

29

30

def background(self):

31

"""Get the background color."""

32

33

def setBackground(self, color):

34

"""Set the background color."""

35

36

def isBold(self):

37

"""Check if bold style is enabled."""

38

39

def setBold(self, bold):

40

"""Enable/disable bold style."""

41

42

def isItalic(self):

43

"""Check if italic style is enabled."""

44

45

def setItalic(self, italic):

46

"""Enable/disable italic style."""

47

48

def isUnderline(self):

49

"""Check if underline style is enabled."""

50

51

def setUnderline(self, underline):

52

"""Enable/disable underline style."""

53

54

def isStrikeOut(self):

55

"""Check if strikeout style is enabled."""

56

57

def setStrikeOut(self, strikeOut):

58

"""Enable/disable strikeout style."""

59

60

def copy(self):

61

"""Create a copy of this color."""

62

63

def lighter(self, factor=150):

64

"""Return a lighter version of this color."""

65

66

def darker(self, factor=150):

67

"""Return a darker version of this color."""

68

69

def toAnsi(self):

70

"""Convert to ANSI escape sequence."""

71

72

# Class methods for predefined colors

73

@classmethod

74

def RST(cls):

75

"""Reset color."""

76

77

@classmethod

78

def BLACK(cls):

79

"""Black color."""

80

81

@classmethod

82

def RED(cls):

83

"""Red color."""

84

85

@classmethod

86

def GREEN(cls):

87

"""Green color."""

88

89

@classmethod

90

def YELLOW(cls):

91

"""Yellow color."""

92

93

@classmethod

94

def BLUE(cls):

95

"""Blue color."""

96

97

@classmethod

98

def MAGENTA(cls):

99

"""Magenta color."""

100

101

@classmethod

102

def CYAN(cls):

103

"""Cyan color."""

104

105

@classmethod

106

def WHITE(cls):

107

"""White color."""

108

```

109

110

### Color Modifiers

111

112

TTkColorModifier provides color manipulation utilities.

113

114

```python { .api }

115

class TTkColorModifier:

116

def __init__(self, color):

117

"""Initialize with base color."""

118

119

def lighten(self, amount):

120

"""Lighten the color by amount."""

121

122

def darken(self, amount):

123

"""Darken the color by amount."""

124

125

def saturate(self, amount):

126

"""Increase saturation."""

127

128

def desaturate(self, amount):

129

"""Decrease saturation."""

130

131

def adjust_hue(self, degrees):

132

"""Adjust hue by degrees."""

133

134

def complement(self):

135

"""Get complementary color."""

136

137

def analogous(self, count=3):

138

"""Get analogous colors."""

139

140

def triadic(self):

141

"""Get triadic color scheme."""

142

```

143

144

### Gradient Colors

145

146

TTkColorGradient and TTkLinearGradient provide gradient color support.

147

148

```python { .api }

149

class TTkColorGradient:

150

def __init__(self):

151

"""Initialize a color gradient."""

152

153

def addColorStop(self, position, color):

154

"""

155

Add a color stop to the gradient.

156

157

Parameters:

158

- position (float): Position from 0.0 to 1.0

159

- color (TTkColor): Color at this position

160

"""

161

162

def colorAt(self, position):

163

"""Get interpolated color at position."""

164

165

def colorStops(self):

166

"""Get list of color stops."""

167

168

def setColorStops(self, stops):

169

"""Set color stops from list."""

170

171

class TTkLinearGradient(TTkColorGradient):

172

def __init__(self, start, stop):

173

"""

174

Initialize a linear gradient.

175

176

Parameters:

177

- start (TTkPoint): Start point

178

- stop (TTkPoint): End point

179

"""

180

181

def setStart(self, point):

182

"""Set gradient start point."""

183

184

def start(self):

185

"""Get gradient start point."""

186

187

def setStop(self, point):

188

"""Set gradient end point."""

189

190

def stop(self):

191

"""Get gradient end point."""

192

```

193

194

### String with Color Support

195

196

TTkString extends string functionality with color and formatting support.

197

198

```python { .api }

199

class TTkString:

200

def __init__(self, text="", color=None):

201

"""

202

Initialize a colored string.

203

204

Parameters:

205

- text (str): Text content

206

- color (TTkColor): Text color

207

"""

208

209

def __str__(self):

210

"""Convert to string representation."""

211

212

def __len__(self):

213

"""Get string length (excluding color codes)."""

214

215

def __add__(self, other):

216

"""Concatenate with another string or TTkString."""

217

218

def setText(self, text):

219

"""Set the text content."""

220

221

def text(self):

222

"""Get the text content."""

223

224

def setColor(self, color):

225

"""Set the text color."""

226

227

def color(self):

228

"""Get the text color."""

229

230

def copy(self):

231

"""Create a copy of this string."""

232

233

def substring(self, start, length=None):

234

"""Get substring with preserved formatting."""

235

236

def split(self, separator):

237

"""Split string while preserving colors."""

238

239

def replace(self, old, new):

240

"""Replace text while preserving colors."""

241

242

def strip(self):

243

"""Strip whitespace while preserving colors."""

244

245

def coloredLength(self):

246

"""Get length including color escape sequences."""

247

248

def plainText(self):

249

"""Get text without color formatting."""

250

251

def toAnsi(self):

252

"""Convert to ANSI-formatted string."""

253

254

# Class methods for formatting

255

@classmethod

256

def fromAnsi(cls, ansi_string):

257

"""Create TTkString from ANSI-formatted string."""

258

259

@classmethod

260

def join(cls, strings, separator=""):

261

"""Join multiple TTkStrings."""

262

```

263

264

### Canvas Drawing System

265

266

TTkCanvas provides drawing operations for widgets.

267

268

```python { .api }

269

class TTkCanvas:

270

def __init__(self, width=0, height=0):

271

"""

272

Initialize a canvas.

273

274

Parameters:

275

- width (int): Canvas width in characters

276

- height (int): Canvas height in characters

277

"""

278

279

def size(self):

280

"""Get canvas size as (width, height)."""

281

282

def width(self):

283

"""Get canvas width."""

284

285

def height(self):

286

"""Get canvas height."""

287

288

def resize(self, width, height):

289

"""Resize the canvas."""

290

291

def clear(self):

292

"""Clear the canvas."""

293

294

def fill(self, char=' ', color=None):

295

"""Fill canvas with character and color."""

296

297

def drawChar(self, x, y, char, color=None):

298

"""

299

Draw a single character.

300

301

Parameters:

302

- x (int): X coordinate

303

- y (int): Y coordinate

304

- char (str): Character to draw

305

- color (TTkColor): Character color

306

"""

307

308

def drawText(self, x, y, text, color=None):

309

"""

310

Draw text string.

311

312

Parameters:

313

- x (int): X coordinate

314

- y (int): Y coordinate

315

- text (str): Text to draw

316

- color (TTkColor): Text color

317

"""

318

319

def drawTTkString(self, x, y, ttkString):

320

"""Draw a TTkString with embedded colors."""

321

322

def drawHLine(self, x, y, width, char='-', color=None):

323

"""Draw horizontal line."""

324

325

def drawVLine(self, x, y, height, char='|', color=None):

326

"""Draw vertical line."""

327

328

def drawBox(self, x, y, width, height, color=None):

329

"""Draw a box outline."""

330

331

def fillBox(self, x, y, width, height, char=' ', color=None):

332

"""Draw a filled box."""

333

334

def drawBorder(self, x, y, width, height, border_chars=None, color=None):

335

"""

336

Draw border with custom characters.

337

338

Parameters:

339

- x, y: Position

340

- width, height: Dimensions

341

- border_chars: Dict with border character definitions

342

- color: Border color

343

"""

344

345

def copy(self):

346

"""Create a copy of the canvas."""

347

348

def paintCanvas(self, canvas, x=0, y=0):

349

"""Paint another canvas onto this one."""

350

351

def getChar(self, x, y):

352

"""Get character at position."""

353

354

def getColor(self, x, y):

355

"""Get color at position."""

356

357

def boundingRect(self, text):

358

"""Get bounding rectangle for text."""

359

```

360

361

### Theme System

362

363

TTkTheme provides theming capabilities for consistent visual styling.

364

365

```python { .api }

366

class TTkTheme:

367

def __init__(self):

368

"""Initialize the theme system."""

369

370

def setTheme(self, theme_name):

371

"""Set active theme by name."""

372

373

def theme(self):

374

"""Get current theme name."""

375

376

def availableThemes(self):

377

"""Get list of available themes."""

378

379

def addTheme(self, name, theme_data):

380

"""Add custom theme."""

381

382

def getColor(self, element, state="normal"):

383

"""

384

Get color for UI element.

385

386

Parameters:

387

- element (str): UI element name (e.g., "button", "window")

388

- state (str): Element state (e.g., "normal", "hover", "pressed")

389

"""

390

391

def getBorder(self, element):

392

"""Get border characters for element."""

393

394

def getIcon(self, icon_name):

395

"""Get icon character(s)."""

396

397

def setCustomColor(self, element, state, color):

398

"""Set custom color for element/state."""

399

400

def resetToDefault(self):

401

"""Reset to default theme."""

402

```

403

404

## Usage Examples

405

406

### Basic Color Usage

407

408

```python

409

import TermTk as ttk

410

411

root = ttk.TTk()

412

container = ttk.TTkContainer(parent=root)

413

layout = ttk.TTkVBoxLayout()

414

415

# Create colors

416

red_color = ttk.TTkColor(fg="#FF0000")

417

green_bg = ttk.TTkColor(bg="#00FF00")

418

bold_blue = ttk.TTkColor(fg="#0000FF", bold=True)

419

styled_color = ttk.TTkColor(fg="#FFFF00", bg="#800080", italic=True, underline=True)

420

421

# Create labels with different colors

422

label1 = ttk.TTkLabel(text="Red text", color=red_color)

423

label2 = ttk.TTkLabel(text="Green background", color=green_bg)

424

label3 = ttk.TTkLabel(text="Bold blue text", color=bold_blue)

425

label4 = ttk.TTkLabel(text="Styled text", color=styled_color)

426

427

# Predefined colors

428

label5 = ttk.TTkLabel(text="Predefined red", color=ttk.TTkColor.RED())

429

label6 = ttk.TTkLabel(text="Predefined cyan", color=ttk.TTkColor.CYAN())

430

431

layout.addWidget(label1)

432

layout.addWidget(label2)

433

layout.addWidget(label3)

434

layout.addWidget(label4)

435

layout.addWidget(label5)

436

layout.addWidget(label6)

437

438

container.setLayout(layout)

439

root.mainloop()

440

```

441

442

### TTkString with Colors

443

444

```python

445

import TermTk as ttk

446

447

root = ttk.TTk()

448

container = ttk.TTkContainer(parent=root)

449

layout = ttk.TTkVBoxLayout()

450

451

# Create colored strings

452

red_text = ttk.TTkString("Red text", ttk.TTkColor.RED())

453

blue_text = ttk.TTkString("Blue text", ttk.TTkColor.BLUE())

454

bold_text = ttk.TTkString("Bold text", ttk.TTkColor(bold=True))

455

456

# Combine strings

457

combined = red_text + " and " + blue_text + " and " + bold_text

458

459

# Create label with combined string

460

label = ttk.TTkLabel()

461

label.setText(combined)

462

463

# Create multi-colored sentence

464

sentence = ttk.TTkString()

465

sentence += ttk.TTkString("Hello ", ttk.TTkColor.GREEN())

466

sentence += ttk.TTkString("colorful ", ttk.TTkColor.YELLOW())

467

sentence += ttk.TTkString("world!", ttk.TTkColor(fg="#FF69B4", bold=True))

468

469

label2 = ttk.TTkLabel()

470

label2.setText(sentence)

471

472

layout.addWidget(label)

473

layout.addWidget(label2)

474

475

container.setLayout(layout)

476

root.mainloop()

477

```

478

479

### Custom Drawing Widget

480

481

```python

482

import TermTk as ttk

483

484

class CustomDrawWidget(ttk.TTkWidget):

485

def __init__(self, parent=None, **kwargs):

486

super().__init__(parent=parent, **kwargs)

487

self.setMinimumSize(40, 20)

488

489

def paintEvent(self, canvas):

490

# Clear canvas

491

canvas.clear()

492

493

# Get dimensions

494

width = canvas.width()

495

height = canvas.height()

496

497

# Draw border

498

border_color = ttk.TTkColor(fg="#FFFF00")

499

canvas.drawBox(0, 0, width, height, border_color)

500

501

# Draw title

502

title = "Custom Drawing"

503

title_color = ttk.TTkColor(fg="#00FFFF", bold=True)

504

title_x = (width - len(title)) // 2

505

canvas.drawText(title_x, 1, title, title_color)

506

507

# Draw diagonal lines

508

line_color = ttk.TTkColor(fg="#FF00FF")

509

for i in range(min(width-2, height-2)):

510

canvas.drawChar(i+1, i+2, '\\', line_color)

511

canvas.drawChar(width-2-i, i+2, '/', line_color)

512

513

# Draw filled rectangle

514

fill_color = ttk.TTkColor(bg="#800000")

515

canvas.fillBox(5, 5, 10, 5, ' ', fill_color)

516

517

# Draw text in rectangle

518

rect_text_color = ttk.TTkColor(fg="#FFFFFF", bg="#800000")

519

canvas.drawText(7, 7, "Filled", rect_text_color)

520

521

# Draw horizontal and vertical lines

522

h_line_color = ttk.TTkColor(fg="#00FF00")

523

v_line_color = ttk.TTkColor(fg="#0000FF")

524

525

canvas.drawHLine(1, height//2, width-2, '-', h_line_color)

526

canvas.drawVLine(width//2, 2, height-3, '|', v_line_color)

527

528

# Usage

529

root = ttk.TTk()

530

widget = CustomDrawWidget(parent=root)

531

root.mainloop()

532

```

533

534

### Gradient Background Widget

535

536

```python

537

import TermTk as ttk

538

539

class GradientWidget(ttk.TTkWidget):

540

def __init__(self, parent=None, **kwargs):

541

super().__init__(parent=parent, **kwargs)

542

self.setMinimumSize(50, 15)

543

544

# Create gradient

545

self.gradient = ttk.TTkLinearGradient((0, 0), (50, 0))

546

self.gradient.addColorStop(0.0, ttk.TTkColor(bg="#FF0000")) # Red

547

self.gradient.addColorStop(0.33, ttk.TTkColor(bg="#00FF00")) # Green

548

self.gradient.addColorStop(0.66, ttk.TTkColor(bg="#0000FF")) # Blue

549

self.gradient.addColorStop(1.0, ttk.TTkColor(bg="#FFFF00")) # Yellow

550

551

def paintEvent(self, canvas):

552

canvas.clear()

553

554

width = canvas.width()

555

height = canvas.height()

556

557

# Draw gradient background

558

for x in range(width):

559

position = x / (width - 1) if width > 1 else 0

560

color = self.gradient.colorAt(position)

561

562

for y in range(height):

563

canvas.drawChar(x, y, ' ', color)

564

565

# Draw title text

566

title = "Gradient Background"

567

title_color = ttk.TTkColor(fg="#FFFFFF", bold=True)

568

title_x = (width - len(title)) // 2

569

title_y = height // 2

570

canvas.drawText(title_x, title_y, title, title_color)

571

572

# Usage

573

root = ttk.TTk()

574

gradient_widget = GradientWidget(parent=root)

575

root.mainloop()

576

```

577

578

### Color Picker Widget

579

580

```python

581

import TermTk as ttk

582

583

class ColorPickerWidget(ttk.TTkWidget):

584

colorChanged = ttk.pyTTkSignal(ttk.TTkColor)

585

586

def __init__(self, parent=None, **kwargs):

587

super().__init__(parent=parent, **kwargs)

588

self.setMinimumSize(30, 10)

589

self.selected_color = ttk.TTkColor.WHITE()

590

self.colors = [

591

ttk.TTkColor.BLACK(), ttk.TTkColor.RED(), ttk.TTkColor.GREEN(),

592

ttk.TTkColor.YELLOW(), ttk.TTkColor.BLUE(), ttk.TTkColor.MAGENTA(),

593

ttk.TTkColor.CYAN(), ttk.TTkColor.WHITE()

594

]

595

596

def paintEvent(self, canvas):

597

canvas.clear()

598

599

# Draw color swatches

600

for i, color in enumerate(self.colors):

601

x = (i % 4) * 6 + 2

602

y = (i // 4) * 3 + 2

603

604

# Draw color swatch

605

swatch_color = ttk.TTkColor(bg=color.foreground())

606

canvas.fillBox(x, y, 4, 2, ' ', swatch_color)

607

608

# Draw border for selected color

609

if color == self.selected_color:

610

border_color = ttk.TTkColor(fg="#FFFFFF")

611

canvas.drawBox(x-1, y-1, 6, 4, border_color)

612

613

def mousePressEvent(self, evt):

614

# Determine which color was clicked

615

x = evt.x()

616

y = evt.y()

617

618

col = (x - 2) // 6

619

row = (y - 2) // 3

620

621

if 0 <= col < 4 and 0 <= row < 2:

622

index = row * 4 + col

623

if 0 <= index < len(self.colors):

624

self.selected_color = self.colors[index]

625

self.colorChanged.emit(self.selected_color)

626

self.update()

627

628

evt.accept()

629

630

# Usage

631

root = ttk.TTk()

632

container = ttk.TTkContainer(parent=root)

633

layout = ttk.TTkVBoxLayout()

634

635

color_picker = ColorPickerWidget()

636

sample_label = ttk.TTkLabel(text="Sample Text")

637

638

@ttk.pyTTkSlot(ttk.TTkColor)

639

def color_selected(color):

640

sample_label.setColor(color)

641

print(f"Selected color: {color.toAnsi()}")

642

643

color_picker.colorChanged.connect(color_selected)

644

645

layout.addWidget(ttk.TTkLabel(text="Select a color:"))

646

layout.addWidget(color_picker)

647

layout.addWidget(sample_label)

648

649

container.setLayout(layout)

650

root.mainloop()

651

```

652

653

### Theme Switching Example

654

655

```python

656

import TermTk as ttk

657

658

root = ttk.TTk()

659

container = ttk.TTkContainer(parent=root)

660

layout = ttk.TTkVBoxLayout()

661

662

# Get theme system

663

theme = ttk.TTkTheme()

664

665

# Create UI elements

666

title = ttk.TTkLabel(text="Theme Demo")

667

button1 = ttk.TTkButton(text="Button 1")

668

button2 = ttk.TTkButton(text="Button 2")

669

text_edit = ttk.TTkTextEdit()

670

text_edit.setText("Sample text in editor")

671

672

# Theme selector

673

theme_layout = ttk.TTkHBoxLayout()

674

theme_label = ttk.TTkLabel(text="Theme:")

675

theme_combo = ttk.TTkComboBox()

676

677

# Add available themes

678

available_themes = theme.availableThemes()

679

for theme_name in available_themes:

680

theme_combo.addItem(theme_name)

681

682

theme_layout.addWidget(theme_label)

683

theme_layout.addWidget(theme_combo)

684

685

# Theme change handler

686

@ttk.pyTTkSlot(str)

687

def change_theme(theme_name):

688

theme.setTheme(theme_name)

689

# Force UI update

690

root.update()

691

692

theme_combo.currentTextChanged.connect(change_theme)

693

694

# Add to layout

695

layout.addLayout(theme_layout)

696

layout.addWidget(title)

697

layout.addWidget(button1)

698

layout.addWidget(button2)

699

layout.addWidget(text_edit)

700

701

container.setLayout(layout)

702

root.mainloop()

703

```