analitics

Pages

Friday, November 20, 2026

tkinter : the rich python package - demo reel.

Testing the rich python package on pydroid3 on phone ...
import io
import re
import tkinter as tk
from tkinter import font as tkfont
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

class RichTkConsole:

  def __init__(self, root):
    self.root = root
    self.root.title("Rich Console — Tkinter Terminal")
    self.root.geometry("820x540")
    self.root.configure(bg="#0d1117")

    # Fonts
    self.font_regular = tkfont.Font(family="Consolas", size=11)
    self.font_bold = tkfont.Font(family="Consolas", size=11, weight="bold")
    self.font_italic = tkfont.Font(family="Consolas", size=11, slant="italic")
    self.font_bold_italic = tkfont.Font(
        family="Consolas", size=11, weight="bold", slant="italic"
    )

    # Top bar
    header = tk.Frame(root, bg="#161b22", height=32)
    header.pack(fill=tk.X)
    tk.Label(
        header,
        text="  ● ● ●   RICH TERMINAL EMULATOR (c = Console())",
        fg="#8b949e",
        bg="#161b22",
        font=("Consolas", 10, "bold"),
    ).pack(side=tk.LEFT, pady=6)

    tk.Button(
        header,
        text="▶ Run Demo Reel",
        command=self.run_demo_reel,
        bg="#238636",
        fg="white",
        relief=tk.FLAT,
        font=("Consolas", 9, "bold"),
        padx=10,
        cursor="hand2",
    ).pack(side=tk.RIGHT, padx=8, pady=4)

    tk.Button(
        header,
        text="Clear",
        command=self.clear,
        bg="#30363d",
        fg="#c9d1d9",
        relief=tk.FLAT,
        font=("Consolas", 9),
        padx=10,
        cursor="hand2",
    ).pack(side=tk.RIGHT, padx=2, pady=4)

    # Output area
    self.output = tk.Text(
        root,
        bg="#0d1117",
        fg="#e6edf3",
        insertbackground="#58a6ff",
        font=self.font_regular,
        padx=14,
        pady=12,
        relief=tk.FLAT,
        wrap=tk.WORD,
        state=tk.DISABLED,
    )
    self.output.pack(fill=tk.BOTH, expand=True)

    # Interactive command bar at bottom
    input_frame = tk.Frame(root, bg="#161b22")
    input_frame.pack(fill=tk.X, side=tk.BOTTOM)

    tk.Label(
        input_frame,
        text=" >>> ",
        fg="#58a6ff",
        bg="#161b22",
        font=("Consolas", 11, "bold"),
    ).pack(side=tk.LEFT, pady=8)

    self.cmd_entry = tk.Entry(
        input_frame,
        bg="#0d1117",
        fg="#e6edf3",
        insertbackground="#58a6ff",
        font=self.font_regular,
        relief=tk.FLAT,
    )
    self.cmd_entry.pack(
        side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10), pady=8, ipady=4
    )
    self.cmd_entry.insert(
        0, "c.print('this is amazing', style='bold red on yellow')"
    )
    self.cmd_entry.bind("", self.execute_command)

    # ANSI color palette (modern terminal colors)
    self.ANSI_FG = {
        "30": "#484f58",
        "31": "#ff7b72",
        "32": "#3fb950",
        "33": "#d29922",
        "34": "#58a6ff",
        "35": "#bc8cff",
        "36": "#39c5cf",
        "37": "#e6edf3",
        "90": "#6e7681",
        "91": "#ffa198",
        "92": "#56d364",
        "93": "#e3b341",
        "94": "#79c0ff",
        "95": "#d2a8ff",
        "96": "#56d4dd",
        "97": "#ffffff",
    }
    self.ANSI_BG = {
        "40": "#161b22",
        "41": "#da3633",
        "42": "#238636",
        "43": "#d29922",
        "44": "#1f6feb",
        "45": "#8957e5",
        "46": "#1b7c83",
        "47": "#b1bac4",
        "100": "#484f58",
        "101": "#ff7b72",
        "102": "#3fb950",
        "103": "#e3b341",
        "104": "#58a6ff",
        "105": "#bc8cff",
        "106": "#39c5cf",
        "107": "#ffffff",
    }

  def _get_tag(self, state):
    tag = (
        f"t_{state['bold']}_{state['italic']}_{state['underline']}_"
        f"{state['fg']}_{state['bg']}"
    )
    if tag not in self.output.tag_names():
      if state["bold"] and state["italic"]:
        fnt = self.font_bold_italic
      elif state["bold"]:
        fnt = self.font_bold
      elif state["italic"]:
        fnt = self.font_italic
      else:
        fnt = self.font_regular

      cfg = {"font": fnt, "underline": state["underline"]}
      if state["fg"]:
        cfg["foreground"] = state["fg"]
      if state["bg"]:
        cfg["background"] = state["bg"]
      self.output.tag_configure(tag, **cfg)
    return tag

  def render_rich(self, render_fn):
    """Captures Rich Console output and renders ANSI styles into Tkinter."""
    buf = io.StringIO()
    console = Console(
        file=buf, force_terminal=True, color_system="standard", width=78
    )
    render_fn(console)
    ansi_text = buf.getvalue()

    self.output.config(state=tk.NORMAL)
    state = {
        "bold": False,
        "italic": False,
        "underline": False,
        "fg": None,
        "bg": None,
    }
    pattern = re.compile(r"\x1b\[([0-9;]*)m")
    pos = 0

    for match in pattern.finditer(ansi_text):
      chunk = ansi_text[pos : match.start()]
      if chunk:
        self.output.insert(tk.END, chunk, self._get_tag(state))

      codes = match.group(1).split(";") if match.group(1) else ["0"]
      for code in codes:
        if code in ("0", ""):
          state = {
              "bold": False,
              "italic": False,
              "underline": False,
              "fg": None,
              "bg": None,
          }
        elif code == "1":
          state["bold"] = True
        elif code == "3":
          state["italic"] = True
        elif code == "4":
          state["underline"] = True
        elif code == "22":
          state["bold"] = False
        elif code == "23":
          state["italic"] = False
        elif code == "24":
          state["underline"] = False
        elif code in self.ANSI_FG:
          state["fg"] = self.ANSI_FG[code]
        elif code in self.ANSI_BG:
          state["bg"] = self.ANSI_BG[code]
        elif code == "39":
          state["fg"] = None
        elif code == "49":
          state["bg"] = None
      pos = match.end()

    if pos < len(ansi_text):
      self.output.insert(tk.END, ansi_text[pos:], self._get_tag(state))

    self.output.see(tk.END)
    self.output.config(state=tk.DISABLED)

  def clear(self):
    self.output.config(state=tk.NORMAL)
    self.output.delete("1.0", tk.END)
    self.output.config(state=tk.DISABLED)

  def execute_command(self, event=None):
    cmd = self.cmd_entry.get().strip()
    if not cmd:
      return
    self.render_rich(lambda c: c.print(f"[dim]$ {cmd}[/dim]"))
    try:
      self.render_rich(
          lambda c: exec(cmd, {"c": c, "Panel": Panel, "Table": Table})
      )
    except Exception as exc:
      self.render_rich(lambda c: c.print(f"[bold red]Error:[/] {exc}"))
    self.cmd_entry.delete(0, tk.END)

  def run_demo_reel(self):
    self.clear()
    steps = [
        (
            200,
            lambda c: c.print(
                Panel.fit(
                    "[bold cyan]RICH + TKINTER DEMO REEL[/]\n"
                    "[dim]Rendering genuine Rich console styles inside a GUI"
                    " window[/]",
                    border_style="bright_blue",
                )
            ),
        ),
        (
            900,
            lambda c: c.print(
                "\n[bold white]1. Classic Styled Prints:[/]"
            ),
        ),
        (
            1300,
            lambda c: c.print(
                "this is amazing", style="bold red on yellow"
            ),
        ),
        (
            1800,
            lambda c: c.print(
                "this is amazing", style="italic blue on red"
            ),
        ),
        (
            2400,
            lambda c: c.print(
                "\n[bold white]2. Inline Markup & Typography:[/]"
            ),
        ),
        (
            2900,
            lambda c: c.print(
                "Supports [bold green]bold[/], [italic magenta]italic[/], "
                "[underline cyan]underlined[/], and [black on bright_green]"
                " highlighted badges [/] seamlessly."
            ),
        ),
        (
            3600,
            lambda c: c.print("\n[bold white]3. Structured Rich Tables:[/]"),
        ),
        (4100, self._demo_table),
        (
            5000,
            lambda c: c.print(
                "\n[bold bright_green]✔ Demo complete.[/] "
                "[dim]Type any Python/Rich command below and press Enter![/]\n"
            ),
        ),
    ]
    for delay, fn in steps:
      self.root.after(delay, lambda f=fn: self.render_rich(f))

  @staticmethod
  def _demo_table(c):
    table = Table(title="Live System Telemetry", border_style="cyan")
    table.add_column("Module", style="bold cyan")
    table.add_column("Status", style="bold green")
    table.add_column("Latency", justify="right", style="yellow")
    table.add_row("Rich Engine", "ONLINE", "1.2 ms")
    table.add_row("ANSI Parser", "ACTIVE", "0.4 ms")
    table.add_row("Tkinter Canvas", "RENDERED", "2.1 ms")
    c.print(table)

if __name__ == "__main__":
  root = tk.Tk()
  app = RichTkConsole(root)
  app.run_demo_reel()
  root.mainloop()