ブラウザで Python GUI

Tkinter オンラインコンパイラ

Tkinter のコードをオンラインで実行し、このページでそのままウィンドウを操作できます。ボタンをクリックし、入力欄に文字を打ち、Canvas に絵を描き、ダイアログを開けます。Python はブラウザの中で動くので、サーバー型のコンパイラで出る「no $DISPLAY」エラーなしに tk.Tk() が動きます。サンプルを選ぶか、自分のプログラムを貼り付けてください。

Tkinter のコードをオンラインで実行

Ctrl+Enter でプログラムを実行します。解説と修正はアカウントなしで無料で試せます。もっと使うにはログインしてください。

再生ボタンか「このコードを実行」を押すと、ここに Tkinter のウィンドウが開きます。

高機能エディタで開きますか?

高機能エディタ (Python コンパイラ本体) は画面が広く、ファイルを保存でき、このコードをすぐに実行します。このページのまま全画面で使うこともできます。

はじめての Tkinter ウィンドウ

Tkinter のプログラムはどれも同じ 3 つの手順で書きます。tk.Tk() でメインウィンドウを作り、ウィジェットを追加してジオメトリマネージャ (pack、grid、place) で配置し、最後に root.mainloop() でイベントループを始めます。ループはクリックやキー入力を待ち、あなたの関数を呼び出します。

このチップ計算は ttk ウィジェット (Windows 風の見た目になるテーマ付き版) を grid で並べています。trace_add によって、金額やスライダーが変わるたびに結果が再計算されます。実行するとウィンドウに Tip 15%: 7.28   Total: 55.77 と表示されます。

tip_calculator.py
このコードを実行 →
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()

リスト、ボタン、ダイアログ

ToDo リストは Entry、Listbox、2 つの Button を組み合わせたものです。entry.bind("<Return>", add_task) により Enter キーでもタスクを追加でき、入力欄が空のときは messagebox.showwarning が本物のダイアログを開きます。curselection() は選択された行の番号を返します。

todo.py
このコードを実行 →
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()

Canvas にマウスで絵を描く

<Button-1> は左ボタンを押したとき、<B1-Motion> はドラッグ中に発生します。動くたびに直前の点から短い線を引きます。Radiobutton は 1 つの StringVar を共有しているので、選んだ色はいつでも color.get() で取れます。

paint.py
このコードを実行 →
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()

ttk.Treeview で表を作る

show="headings" を指定した Treeview は表になります。heading で列の見出し、column で幅と揃え方を決め、insert("", END, values=...) で行を追加します。読み取り専用の Combobox なら、成績をリストの値だけに制限できます。

students.py
このコードを実行 →
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()

Tkinter の中の Matplotlib グラフ

FigureCanvasTkAgg は Matplotlib の図をウィンドウに埋め込み、NavigationToolbar2Tk は拡大、移動、保存のボタンを追加します。Scale を動かすと周波数が変わり、draw_idle() がグラフを描き直します。

chart.py
このコードを実行 →
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()

Tkinter でよくある間違い

1. command= で関数を呼び出してしまう

command=clicked() はウィンドウを作るときに関数を一度実行し、その戻り値をボタンに渡すので、クリックしても何も起きません。関数は括弧を付けずに渡します。

wrong.py
このコードを実行 →
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
このコードを実行 →
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. Tkinter のプログラムで time.sleep() を使う

sleep の間はイベントループがウィンドウを描き直せないので、カウントダウンは最後まで何も表示されません。次の処理は root.after(ms, 関数) で予約します。

wrong.py
このコードを実行 →
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
このコードを実行 →
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 と grid を混ぜる

Tkinter は TclError: cannot use geometry manager pack inside . which already has slaves managed by grid で止まります。1 つのコンテナでは 1 つのマネージャだけを使い、もう一方は中に置いた Frame の中で使います。

4. root.mainloop() を忘れる

これがないと、ターミナルから実行したスクリプトはウィンドウを開いてすぐに閉じてしまいます。すべてのウィジェットを作ったあと、最後の行に mainloop() を書きます。

Tkinter オンラインコンパイラのしくみ

Python は WebAssembly でブラウザの中で動きます。本物の Tk はデスクトップの画面を必要とするため、このページではブラウザ用に書かれた Tkinter を使っています。API も配置のルール (pack、grid、place) も同じで、各ウィンドウは Windows 版 Tk の見た目で描かれます。学校や趣味のプログラムの多くは、ttk、ダイアログ、customtkinter、Matplotlib のグラフも含めてそのまま動きます。Chrome、Edge、Firefox、Safari に対応しています。初回は Python をダウンロードしますが、2 回目以降は数秒で起動します。

ファイルを残したいときは Python エディタを使ってください。ワークスペースが保存され、Tkinter のプログラムもそこでウィンドウを開きます。

よくある質問

Tkinter をオンラインで実行するには?

このページのエディタに Tkinter のコードを貼り付けて実行します。Python はブラウザの中で動き、ウィンドウがこのページに開くので、ボタン、入力欄、メニュー、ダイアログをそのまま操作できます。インストールは不要です。

Tkinter のどの機能が使えますか?

よく使われるウィジェットに対応しています。Tk、Toplevel、Frame、Label、Button、Entry、Text、Canvas、Listbox、Checkbutton、Radiobutton、Scale、Spinbox、Scrollbar、Menu、OptionMenu に加え、ttk (Combobox、Treeview、Notebook、Progressbar など)、pack、grid、place、StringVar、bind、after、messagebox、simpledialog、filedialog、colorchooser も使えます。FigureCanvasTkAgg を使った Matplotlib のグラフや customtkinter も動きます。

本物の Tkinter ウィンドウと同じ見た目ですか?

はい。配置は Tk 本体の pack、grid、place のルールに従うので、大きさや位置はデスクトップと同じになり、ウィジェットは Windows 版 Tk の見た目で描かれます (ttk は Windows テーマ、またはプログラムが選べば clam を使います)。

ほかのオンラインコンパイラで Tkinter が動かないのはなぜ?

Tkinter はウィンドウを開くために画面を必要とします。オンラインコンパイラは画面のないサーバーでコードを実行するので、tk.Tk() が「no display name and no $DISPLAY environment variable」で失敗します。ここではウィンドウをブラウザの中に描いています。

プログラムでファイルを開いたり保存したりできますか?

はい。filedialog はワークスペースのファイルを表示し、Chrome や Edge ではパソコンからファイルをアップロードすることもできます。プログラムが書き込んだファイルは、終了時にワークスペースに保存されます。

動かないものは?

Tcl を直接使う命令 (tk.call、eval)、subprocess、pyautogui のようにデスクトップが必要なライブラリです。スレッドは使えますが、並列ではなくウィンドウと交互に動きます。