Python GUI in the browser

Tkinter Online Compiler

Run Tkinter code online and use the window right here: click buttons, type in entries, draw on a Canvas, open dialogs. Python runs in your browser, so tk.Tk() works without the "no $DISPLAY" error of server-based compilers. Pick an example or paste your own program.

Run Tkinter code online

Ctrl+Enter runs the program. Explain and Fix are free to try without an account, sign in for more.

Press play or Run this code: the Tkinter window opens here.

Open in the advanced editor?

The advanced editor (the full Python compiler) has more room, saves your files and runs this code right away. Or keep working here, full screen.

Your first Tkinter window

Every Tkinter program has the same three steps: create the main window with tk.Tk(), add widgets and place them with a layout manager (pack, grid or place), then start the event loop with root.mainloop(). The loop waits for clicks and key presses and calls your functions.

This tip calculator uses ttk widgets (the themed versions that look native on Windows) laid out with grid. trace_add recalculates the result every time the bill or the slider changes. When you run it, the window shows Tip 15%: 7.28   Total: 55.77.

tip_calculator.py
Run this code →
tip_calculator.py
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Tip calculator")
root.resizable(False, False)

frame = ttk.Frame(root, padding=16)
frame.grid()

ttk.Label(frame, text="Bill amount:").grid(row=0, column=0, sticky="w")
bill = tk.StringVar(value="48.50")
ttk.Entry(frame, textvariable=bill, width=12).grid(row=0, column=1, pady=4)

ttk.Label(frame, text="Tip %:").grid(row=1, column=0, sticky="w")
tip = tk.IntVar(value=15)
ttk.Scale(frame, from_=0, to=30, variable=tip, length=160).grid(row=1, column=1, pady=4)

result = ttk.Label(frame, font=("Segoe UI", 12, "bold"))
result.grid(row=2, column=0, columnspan=2, pady=(10, 0))


def update(*args):
    try:
        amount = float(bill.get())
    except ValueError:
        result.config(text="Type a number")
        return
    t = round(tip.get())
    result.config(text=f"Tip {t}%: {amount * t / 100:.2f}   Total: {amount * (1 + t / 100):.2f}")


bill.trace_add("write", update)
tip.trace_add("write", update)
update()
root.mainloop()

Lists, buttons and dialogs

The to-do list combines an Entry, a Listbox and two Buttons. entry.bind("<Return>", add_task) makes the Enter key add a task too, and messagebox.showwarning opens a real dialog when the box is empty. curselection() returns the indexes of the selected rows.

todo.py
Run this code →
todo.py
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
root.title("To-do list")

entry = tk.Entry(root, width=30)
entry.grid(row=0, column=0, padx=8, pady=8)
tasks = tk.Listbox(root, width=40, height=8)
tasks.grid(row=1, column=0, columnspan=2, padx=8)


def add_task(event=None):
    text = entry.get().strip()
    if not text:
        messagebox.showwarning("Empty task", "Type a task first.")
        return
    tasks.insert(tk.END, text)
    entry.delete(0, tk.END)


def remove_task():
    selected = tasks.curselection()
    if selected:
        tasks.delete(selected[0])


tk.Button(root, text="Add", width=8, command=add_task).grid(row=0, column=1, padx=8)
tk.Button(root, text="Remove selected", command=remove_task).grid(row=2, column=0, columnspan=2, pady=8)
entry.bind("<Return>", add_task)
for task in ["Buy milk", "Finish homework", "Call grandma"]:
    tasks.insert(tk.END, task)
root.mainloop()

Draw with the mouse on a Canvas

<Button-1> fires when you press the left button and <B1-Motion> while you drag; each move adds a short line from the last point. Radiobuttons share one StringVar, so the selected color is always in color.get().

paint.py
Run this code →
paint.py
import tkinter as tk

root = tk.Tk()
root.title("Paint")
color = tk.StringVar(value="black")

canvas = tk.Canvas(root, width=420, height=280, bg="white")
canvas.pack()
last = {}


def start(event):
    last["xy"] = (event.x, event.y)


def draw(event):
    x0, y0 = last.get("xy", (event.x, event.y))
    canvas.create_line(x0, y0, event.x, event.y, fill=color.get(), width=4, capstyle=tk.ROUND)
    last["xy"] = (event.x, event.y)


canvas.bind("<Button-1>", start)
canvas.bind("<B1-Motion>", draw)

bar = tk.Frame(root)
bar.pack(fill=tk.X)
for name in ["black", "red", "green", "blue", "orange"]:
    tk.Radiobutton(bar, text=name, value=name, variable=color, fg=name).pack(side=tk.LEFT)
tk.Button(bar, text="Clear", command=lambda: canvas.delete("all")).pack(side=tk.RIGHT, padx=4)
root.mainloop()

Tables with ttk.Treeview

A Treeview with show="headings" is a table: heading sets the column titles, column the width and alignment, and insert("", END, values=...) adds a row. A read-only Combobox limits the grade to the listed values.

students.py
Run this code →
students.py
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Students")

form = ttk.Frame(root, padding=10)
form.pack(fill=tk.X)
name = ttk.Entry(form, width=18)
name.grid(row=0, column=0, padx=(0, 6))
grade = ttk.Combobox(form, values=["A", "B", "C", "D"], width=5, state="readonly")
grade.current(0)
grade.grid(row=0, column=1, padx=(0, 6))

table = ttk.Treeview(root, columns=("name", "grade"), show="headings", height=7)
table.heading("name", text="Name")
table.heading("grade", text="Grade")
table.column("grade", width=80, anchor="center")
table.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))


def add():
    if name.get().strip():
        table.insert("", tk.END, values=(name.get().strip(), grade.get()))
        name.delete(0, tk.END)


ttk.Button(form, text="Add student", command=add).grid(row=0, column=2)
for row in [("Ada", "A"), ("Linus", "B"), ("Grace", "A")]:
    table.insert("", tk.END, values=row)
root.mainloop()

Matplotlib charts inside Tkinter

FigureCanvasTkAgg puts a Matplotlib figure in the window and NavigationToolbar2Tk adds the zoom, pan and save buttons. Moving the Scale changes the frequency and draw_idle() redraws the chart.

chart.py
Run this code →
chart.py
import tkinter as tk
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

root = tk.Tk()
root.title("Sine wave")

fig = Figure(figsize=(5, 3), dpi=100)
ax = fig.add_subplot()
x = np.linspace(0, 4 * np.pi, 400)
(line,) = ax.plot(x, np.sin(x))
ax.set_ylim(-1.1, 1.1)

canvas = FigureCanvasTkAgg(fig, master=root)
NavigationToolbar2Tk(canvas, root)
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)


def set_frequency(value):
    line.set_ydata(np.sin(float(value) * x))
    canvas.draw_idle()


tk.Scale(root, from_=0.5, to=4, resolution=0.1, orient=tk.HORIZONTAL, label="Frequency",
         command=set_frequency).pack(fill=tk.X)
canvas.draw()
root.mainloop()

Common Tkinter mistakes

1. Calling the function in command=

command=clicked() runs the function once while the window is being built and gives the button its return value, so clicking does nothing. Pass the function without parentheses.

wrong.py
Run this code →
wrong.py
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="Not clicked yet")
label.pack(padx=20, pady=10)


def clicked():
    label.config(text="Clicked!")


# Wrong: clicked() runs once now, and the button gets its result (None)
tk.Button(root, text="Click me", command=clicked()).pack(pady=10)
root.mainloop()
right.py
Run this code →
right.py
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="Not clicked yet")
label.pack(padx=20, pady=10)


def clicked():
    label.config(text="Clicked!")


# Right: pass the function itself; use lambda when it needs arguments
tk.Button(root, text="Click me", command=clicked).pack(pady=10)
root.mainloop()

2. time.sleep() in a Tkinter program

While sleep runs, the event loop cannot redraw the window, so a countdown shows nothing until it is over. Schedule the next step with root.after(ms, function) instead.

wrong.py
Run this code →
wrong.py
import tkinter as tk
import time

root = tk.Tk()
label = tk.Label(root, text="5", font=("Arial", 40))
label.pack(padx=40, pady=20)

# Wrong: the window freezes, then jumps straight to 0
for n in range(5, -1, -1):
    label.config(text=str(n))
    time.sleep(1)
root.mainloop()
right.py
Run this code →
right.py
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="5", font=("Arial", 40))
label.pack(padx=40, pady=20)


def count(n):
    label.config(text=str(n))
    if n > 0:
        root.after(1000, count, n - 1)  # come back in 1 second, the window stays responsive


count(5)
root.mainloop()

3. pack and grid in the same container

Tkinter stops with TclError: cannot use geometry manager pack inside . which already has slaves managed by grid. Use one layout manager per container; put a Frame inside and use the other one there.

4. Forgetting root.mainloop()

Without it, a script run from a terminal opens the window and closes it right away. Make mainloop() the last line, after every widget is created.

How the online Tkinter compiler works

Python runs in your browser with WebAssembly. Real Tk needs a desktop screen, so this page uses a Tkinter written for the browser: it keeps the same API and the same layout rules (pack, grid, place), and draws each window with Tk's Windows look. Most school and hobby programs run unchanged, including ttk, dialogs, customtkinter and Matplotlib charts. It works in Chrome, Edge, Firefox and Safari; the first run downloads Python, later runs start in a few seconds.

To keep your files, use the Python editor: it saves your workspace, and Tkinter programs open their window there too.

Frequently asked questions

How do I run Tkinter online?

Paste your Tkinter code in the editor on this page and select Run this code. Python runs in your browser and the window opens right here, with buttons, entries, menus and dialogs you can click and type into. Nothing to install.

Which Tkinter features work?

The widgets programs use most: Tk, Toplevel, Frame, Label, Button, Entry, Text, Canvas, Listbox, Checkbutton, Radiobutton, Scale, Spinbox, Scrollbar, Menu and OptionMenu, plus ttk (Combobox, Treeview, Notebook, Progressbar and the others), pack, grid and place, StringVar and friends, bind, after, messagebox, simpledialog, filedialog and colorchooser. Matplotlib charts with FigureCanvasTkAgg and customtkinter work too.

Does it look like a real Tkinter window?

Yes. Layout follows Tk's own pack, grid and place rules, so sizes and positions match the desktop, and widgets are drawn with Tk's Windows look (ttk uses the Windows theme, or clam if your program picks it).

Why does Tkinter fail on other online compilers?

Tkinter needs a screen to open its window. Online compilers run your code on a server without one, so tk.Tk() fails with "no display name and no $DISPLAY environment variable". Here the window is drawn in your browser instead.

Can my program open and save files?

Yes. filedialog shows the files of your workspace, and in Chrome or Edge you can also upload a file from your computer. Files the program writes are saved back to your workspace when it ends.

What does not work?

Raw Tcl commands (tk.call, eval), subprocess, and libraries that need the desktop, such as pyautogui. Threads run, but take turns with the window instead of running in parallel.