Skip to main content

Build a CSV viewer desktop app in Python, without HTML or JavaScript

A walk through a 77-line example: a window, the file dialog of the system, the csv module and a table that stays fast with 100,000 rows.

Updated 9 min readMarkdown

I'm Buğra Özden, and I made OzdenUI, a small Python library for desktop windows. In this post I walk through one of its examples, a CSV viewer, step by step. You write only Python: no HTML, no JavaScript, no server.

First, what it is not yet: OzdenUI is v0.1 and experimental. I test it on macOS and Windows; Linux is not tested yet. It is new and has one author. If that rules it out for you, read "When Tkinter is still the better choice" near the end.

Who this is for

You write Python scripts for yourself, your office or your lab: a file tool, a report, a small in-house app. When a script needs a window, you reach for Tkinter, CustomTkinter or FreeSimpleGUI. I wanted ready parts with a modern look (tables, dialogs, charts) without learning the web.

How it works: the window is the web view of the system (WebKit on macOS, WebView2 on Windows), opened by pywebview. The page inside it holds my UI kit, basic.js and its components; the package carries them (about 3 MB, no internet needed). You never touch that page. Every object you make in Python sends commands to it.

What we build

The CSV viewer window: a title, the buttons

It opens with a sample of eight cities. "Open a CSV" shows the file dialog of your system. "100000 rows" fills the table with 100,000 rows made in Python. A click on a row writes that row under the table. The whole program is 77 lines: examples/csv_viewer.py in the repository.

Step 1: install

pip install ozdenui

It needs Python 3.9 or newer, and its only dependency is pywebview. On a Mac with the Python of the system, upgrade pip first (python3 -m pip install --upgrade pip): its old pip fails to build a part of pywebview. On Windows the window needs the WebView2 runtime, which most computers have.

Step 2: the window

The program starts at its last two lines:

if __name__ == "__main__":
    App(start, title="CSV viewer", size=(900, 640)).run()

App is the window. When it is ready, it calls start(page), which makes the objects. .run() opens the window and returns when it is closed.

The top of the file has the imports and a few named numbers. csv is the standard library:

import csv

from ozdenui import App, Box, HGroup, Label, SmartButton, SmartTable, Toast, VGroup, open_file

PAGE_COLOR = "#F4F5F7"
TEXT_SOFT = "#5A6270"
TABLE_WIDTH = 820
TABLE_HEIGHT = 400
COLUMN_WIDTH = 170
MANY_ROWS = 100000

Under them, SAMPLE is a list of eight dicts, and view = {} keeps the objects that the functions need later.

Step 3: the layout

def start(page):
    page.color = PAGE_COLOR
    with VGroup(gap=14, padding=30, align="left top"):
        with HGroup(hug=True, gap=14, align="left center"):
            Label(text="CSV viewer", font_size=24, bold=True)
            SmartButton(text="Open a CSV", tone="cyan", on_click=open_csv)
            SmartButton(text=f"{MANY_ROWS} rows", on_click=show_many_rows)
        view["file"] = Label(text="A sample: some cities", font_size=14, text_color=TEXT_SOFT)
        view["holder"] = Box(width=TABLE_WIDTH, height=TABLE_HEIGHT, color="transparent")
        view["detail"] = Label(text="Click a row.", font_size=15)
    show_rows(SAMPLE)
  • with VGroup(...) opens a group: the objects made inside the block go one under the other, 14 px apart, 30 px from the edges.
  • The HGroup puts the title and the two buttons side by side. hug=True makes it only as large as its content.
  • SmartButton is a button of the kit; tone="cyan" marks the main action. on_click takes a plain Python function.
  • The Box holds the place of the table, so a new table always goes to the same place, above the last line.

No object has an x or a y: the groups place them.

Step 4: a table from a list of dicts

def show_rows(records):
    """A new table for the rows (a new file has other columns)."""
    if "table" in view:
        view["table"].remove()
    names = list(records[0].keys()) if records else []
    columns = [{"key": name, "title": name, "width": COLUMN_WIDTH} for name in names]
    with view["holder"]:
        view["table"] = SmartTable(columns=columns, rows=records, width="100%", height="100%", on_select=show_row)

A new file has other columns, so this makes a new table each time; remove() takes the old one away. The columns come from the keys of the first row. with view["holder"]: makes the table inside the box, and "100%" makes it fill it. on_select=show_row runs when a row is chosen.

SmartTable makes only the rows that are seen. It has a filter box and sorting on its titles, with no code of yours. It starts sorted by its first column: that is why Ankara comes before İstanbul in the picture.

The table shows its values as text, so format numbers in Python (f"{price:,.2f}").

Step 5: the file dialog and the csv module

def open_csv():
    path = open_file(file_types=("CSV files (*.csv)", "All files (*.*)"))
    if not path:
        return
    try:
        with open(path, newline="", encoding="utf-8-sig") as file:
            records = list(csv.DictReader(file))
    except (OSError, UnicodeDecodeError, csv.Error) as error:
        Toast.error(str(error), title="Could not read it")
        return
    view["file"].text = path
    show_rows(records)

open_file() shows the open dialog of macOS or Windows. It returns the path of the chosen file, or None when the user cancels. It is the dialog of the computer, so the path is real: plain open() reads it.

The rest is the standard library. newline="" is what the csv module asks for, and utf-8-sig also reads a file that starts with the BOM mark that Excel writes. csv.DictReader gives one dict per line, keyed by the header line: the shape show_rows takes.

When reading fails (the file is gone, another encoding, a broken line), Toast.error shows a short message in a corner, and the old table stays.

Step 6: a click on a row

def show_row(table, row):
    view["detail"].text = "   ".join(f"{key}: {value}" for key, value in row.items())

on_select calls this with the table and the row (a click, or Enter on a row). The row is the dict you gave. Setting .text changes the screen: there is no refresh call.

Step 7: 100,000 rows

def show_many_rows():
    view["file"].text = f"{MANY_ROWS} rows made in Python"
    show_rows([{"number": index, "square": index * index, "half": index / 2} for index in range(MANY_ROWS)])

The same show_rows shows 100,000 dicts. On my Mac they reach the table in about 2 seconds, and then it stays fast, because only the rows that are seen are made.

Run it

Save it as csv_viewer.py and run python csv_viewer.py. The tests of the repository open every example, this one too, in its real window on macOS and Windows.

The whole program

# Bismillah
"""A CSV file in a table: open one (a sample is shown first), filter it, click a row to see it. A SmartTable makes only
the rows that are seen: "100000 rows" shows that a big file stays fast."""

import csv

from ozdenui import App, Box, HGroup, Label, SmartButton, SmartTable, Toast, VGroup, open_file

PAGE_COLOR = "#F4F5F7"
TEXT_SOFT = "#5A6270"
TABLE_WIDTH = 820
TABLE_HEIGHT = 400
COLUMN_WIDTH = 170
MANY_ROWS = 100000

SAMPLE = [
    {"city": "İstanbul", "country": "Türkiye", "people": "15,655,924"},
    {"city": "Ankara", "country": "Türkiye", "people": "5,803,482"},
    {"city": "Berlin", "country": "Germany", "people": "3,878,100"},
    {"city": "Madrid", "country": "Spain", "people": "3,332,035"},
    {"city": "Rome", "country": "Italy", "people": "2,748,109"},
    {"city": "Paris", "country": "France", "people": "2,102,650"},
    {"city": "Vienna", "country": "Austria", "people": "2,005,760"},
    {"city": "Lisbon", "country": "Portugal", "people": "567,131"},
]

view = {}


def start(page):
    page.color = PAGE_COLOR
    with VGroup(gap=14, padding=30, align="left top"):
        with HGroup(hug=True, gap=14, align="left center"):
            Label(text="CSV viewer", font_size=24, bold=True)
            SmartButton(text="Open a CSV", tone="cyan", on_click=open_csv)
            SmartButton(text=f"{MANY_ROWS} rows", on_click=show_many_rows)
        view["file"] = Label(text="A sample: some cities", font_size=14, text_color=TEXT_SOFT)
        view["holder"] = Box(width=TABLE_WIDTH, height=TABLE_HEIGHT, color="transparent")
        view["detail"] = Label(text="Click a row.", font_size=15)
    show_rows(SAMPLE)


def show_rows(records):
    """A new table for the rows (a new file has other columns)."""
    if "table" in view:
        view["table"].remove()
    names = list(records[0].keys()) if records else []
    columns = [{"key": name, "title": name, "width": COLUMN_WIDTH} for name in names]
    with view["holder"]:
        view["table"] = SmartTable(columns=columns, rows=records, width="100%", height="100%", on_select=show_row)


def show_row(table, row):
    view["detail"].text = "   ".join(f"{key}: {value}" for key, value in row.items())


def show_many_rows():
    view["file"].text = f"{MANY_ROWS} rows made in Python"
    show_rows([{"number": index, "square": index * index, "half": index / 2} for index in range(MANY_ROWS)])


def open_csv():
    path = open_file(file_types=("CSV files (*.csv)", "All files (*.*)"))
    if not path:
        return
    try:
        with open(path, newline="", encoding="utf-8-sig") as file:
            records = list(csv.DictReader(file))
    except (OSError, UnicodeDecodeError, csv.Error) as error:
        Toast.error(str(error), title="Could not read it")
        return
    view["file"].text = path
    show_rows(records)


if __name__ == "__main__":
    App(start, title="CSV viewer", size=(900, 640)).run()

When Tkinter is still the better choice

  • Tkinter comes with Python: nothing to install, which matters on a locked computer or in a classroom.
  • It runs on Linux. OzdenUI is not tested there yet: it would need the GTK or Qt web view of pywebview.
  • It has decades of answers on the web. OzdenUI is new.
  • One app file with PyInstaller: the handbook says it needs --collect-data ozdenui, but I have not tried it yet.

If one of these matters to you today, Tkinter (or CustomTkinter, a modern skin on it) is the safer pick. If you are on macOS or Windows and want ready tables, dialogs and charts in plain Python, try OzdenUI on a small tool first.

What to try next

The repository: https://github.com/bug7a/ozdenui-python

The site: https://bug7a.github.io/ozdenui-python/

If you try it, I would like to hear what was hard or missing.


Written by me, the author of OzdenUI, with the help of Claude Code.

No comments yet. Be the first to comment.