Tkinter Online Compiler

Write, Run & Share Tkinter code online using OneCompiler's Tkinter online compiler for free. It's one of the robust, feature-rich online compilers for the Python tkinter library, running on Python 3.12. The window your code creates is streamed live into the browser — no setup, no Python install, no display server to configure. The editor shows sample boilerplate code when you choose language as Tkinter and start coding.

About Tkinter

Tkinter is Python's de-facto standard GUI library and ships with every CPython install. It's a thin Python layer over the Tcl/Tk toolkit, which has been around since 1991 and powers everything from the IDLE editor to thousands of small desktop tools. Tkinter is the easiest way to put a window, a button, and a callback together in a few lines of Python — no extra dependencies, no project scaffolding, no event-loop boilerplate beyond mainloop().

Syntax help

Creating a window

Every Tkinter program starts by creating a root Tk window, adding widgets to it, and calling mainloop() to start the event loop. mainloop() blocks until the user closes the window — anything after it only runs on shutdown.

import tkinter as tk

root = tk.Tk()
root.title("My App")
root.geometry("400x300")          # width x height
root.minsize(200, 150)            # don't allow shrinking past this
root.resizable(False, False)      # lock the size entirely

root.mainloop()

Widgets

Widgets are the building blocks of every Tkinter UI — labels, buttons, entries, checkboxes, text areas, listboxes, and more. Each widget is created with the parent window or frame as its first argument and made visible with a geometry manager (pack, grid, or place).

import tkinter as tk

root = tk.Tk()

# Static text
tk.Label(root, text="Name:", font=("Arial", 12)).pack()

# Single-line input
entry = tk.Entry(root, width=30)
entry.pack()

# Button with a callback
def greet():
    print(f"Hello, {entry.get()}!")

tk.Button(root, text="Greet", command=greet).pack()

# Checkbox bound to a variable
agree = tk.BooleanVar()
tk.Checkbutton(root, text="I agree", variable=agree).pack()

# Multi-line text
text = tk.Text(root, height=5, width=40)
text.pack()

root.mainloop()

Layout — pack, grid, place

Tkinter has three geometry managers. Pick one per container — mixing pack and grid inside the same parent will hang the program.

import tkinter as tk

root = tk.Tk()

# pack — stack widgets in one direction
tk.Label(root, text="Top").pack(side="top", fill="x")
tk.Label(root, text="Bottom").pack(side="bottom", fill="x")
tk.Label(root, text="Center", bg="lightblue").pack(expand=True, fill="both")

# grid — row/column layout (use in its own frame)
form = tk.Frame(root)
form.pack()
tk.Label(form, text="Email:").grid(row=0, column=0, sticky="e", padx=5, pady=4)
tk.Entry(form).grid(row=0, column=1)
tk.Label(form, text="Password:").grid(row=1, column=0, sticky="e", padx=5, pady=4)
tk.Entry(form, show="*").grid(row=1, column=1)

# place — absolute pixel positioning (rarely the right choice)
# tk.Label(root, text="Pinned").place(x=10, y=10)

root.mainloop()

Event handling

Buttons take a command callback for the simple case. For everything else — keypresses, mouse clicks on arbitrary widgets, resize events, focus changes — use bind() with a Tk event sequence.

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=200, bg="white")
canvas.pack()

def on_click(event):
    canvas.create_oval(event.x - 5, event.y - 5,
                       event.x + 5, event.y + 5, fill="red")

def on_key(event):
    print("Key pressed:", event.keysym)

canvas.bind("<Button-1>", on_click)        # left click
root.bind("<Key>", on_key)                 # any keypress
root.bind("<Escape>", lambda e: root.quit())

root.mainloop()

Common event sequences: <Button-1> (left click), <Button-3> (right click), <Double-Button-1>, <Motion>, <Enter> / <Leave>, <Key>, <Return>, <Configure> (resize).

Variables (StringVar, IntVar, BooleanVar)

Tk variables let you share state between widgets — set the variable, every widget bound to it updates automatically.

import tkinter as tk

root = tk.Tk()

name = tk.StringVar(value="World")

tk.Entry(root, textvariable=name).pack()
tk.Label(root, textvariable=name, font=("Arial", 20)).pack()
# The label updates live as the user types.

tk.Button(root, text="Reset", command=lambda: name.set("World")).pack()

root.mainloop()

Canvas — drawing and animation

Canvas is Tkinter's free-form drawing surface. Use after() to schedule the next animation frame — never use time.sleep() in a GUI app, it freezes the event loop.

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=300, bg="black")
canvas.pack()

ball = canvas.create_oval(180, 130, 220, 170, fill="cyan")
dx, dy = 4, 3

def step():
    global dx, dy
    canvas.move(ball, dx, dy)
    x1, y1, x2, y2 = canvas.coords(ball)
    if x1 <= 0 or x2 >= 400: dx = -dx
    if y1 <= 0 or y2 >= 300: dy = -dy
    root.after(16, step)   # ~60 fps

step()
root.mainloop()

ttk — themed widgets

tkinter.ttk gives you native-looking buttons, comboboxes, progress bars, treeviews, and notebooks. For anything more polished than a quick prototype, prefer ttk widgets.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
ttk.Style().theme_use("clam")   # 'clam', 'alt', 'default', 'classic'

ttk.Button(root, text="OK").pack(pady=4)
ttk.Combobox(root, values=["Python", "Go", "Rust"]).pack(pady=4)
ttk.Progressbar(root, length=200, mode="determinate", value=70).pack(pady=4)

# Notebook (tabs)
nb = ttk.Notebook(root)
nb.add(ttk.Frame(nb), text="Tab 1")
nb.add(ttk.Frame(nb), text="Tab 2")
nb.pack(expand=True, fill="both")

root.mainloop()

Dialogs

Tkinter ships with ready-made message and file dialogs — useful when you don't want to build a custom modal.

from tkinter import messagebox, filedialog, simpledialog

messagebox.showinfo("Title", "It worked!")
messagebox.askyesno("Confirm", "Delete this file?")

path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
save_to = filedialog.asksaveasfilename(defaultextension=".txt")

name = simpledialog.askstring("Name", "What's your name?")
age = simpledialog.askinteger("Age", "How old are you?", minvalue=0, maxvalue=120)