GUI ของ Python ในเบราว์เซอร์

คอมไพเลอร์ Tkinter ออนไลน์

รันโค้ด Tkinter ออนไลน์และใช้หน้าต่างได้ที่หน้านี้เลย คลิกปุ่ม พิมพ์ในช่องกรอก วาดบน Canvas และเปิดกล่องโต้ตอบ Python ทำงานในเบราว์เซอร์ของคุณ tk.Tk() จึงใช้ได้โดยไม่เจอข้อผิดพลาด "no $DISPLAY" แบบคอมไพเลอร์ที่รันบนเซิร์ฟเวอร์ เลือกตัวอย่างหรือวางโปรแกรมของคุณเอง

รันโค้ด 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()

รายการ ปุ่ม และกล่องโต้ตอบ

รายการสิ่งที่ต้องทำประกอบด้วย Entry, Listbox และ 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 ใช้ 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

Treeview ที่ตั้ง show="headings" คือตาราง 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()

กราฟ Matplotlib ใน Tkinter

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. ใช้ time.sleep() ในโปรแกรม Tkinter

ระหว่างที่ 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 ให้ใช้ตัวจัดตำแหน่งเพียงตัวเดียวต่อคอนเทนเนอร์ ใส่ Frame ไว้ข้างในแล้วใช้อีกตัวใน Frame นั้น

4. ลืม root.mainloop()

ถ้าไม่มีคำสั่งนี้ สคริปต์ที่รันจากเทอร์มินัลจะเปิดหน้าต่างแล้วปิดทันที ให้เขียน mainloop() ไว้บรรทัดสุดท้าย หลังจากสร้างวิดเจ็ตครบแล้ว

คอมไพเลอร์ Tkinter ออนไลน์ทำงานอย่างไร

Python ทำงานในเบราว์เซอร์ของคุณด้วย WebAssembly Tk ตัวจริงต้องใช้หน้าจอเดสก์ท็อป หน้านี้จึงใช้ Tkinter ที่เขียนขึ้นสำหรับเบราว์เซอร์ API เหมือนกัน กฎการจัดวาง (pack, grid, place) เหมือนกัน และทุกหน้าต่างวาดด้วยหน้าตาแบบ Tk บน Windows โปรแกรมของโรงเรียนและงานอดิเรกส่วนใหญ่รันได้โดยไม่ต้องแก้ รวมถึง ttk, กล่องโต้ตอบ, customtkinter และกราฟ Matplotlib ใช้ได้ใน Chrome, Edge, Firefox และ Safari ครั้งแรกจะดาวน์โหลด Python ครั้งต่อไปเริ่มได้ในไม่กี่วินาที

ถ้าต้องการเก็บไฟล์ไว้ ให้ใช้ตัวแก้ไข 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 กราฟ Matplotlib ด้วย FigureCanvasTkAgg และ customtkinter ก็ใช้ได้

หน้าตาเหมือนหน้าต่าง Tkinter จริงไหม?

เหมือน การจัดวางใช้กฎ pack, grid และ place ของ Tk เอง ขนาดและตำแหน่งจึงตรงกับบนเดสก์ท็อป และวิดเจ็ตวาดด้วยหน้าตาแบบ Tk บน Windows (ttk ใช้ธีม Windows หรือ clam ถ้าโปรแกรมเลือก)

ทำไม Tkinter ใช้ไม่ได้ในคอมไพเลอร์ออนไลน์อื่น?

Tkinter ต้องมีหน้าจอเพื่อเปิดหน้าต่าง คอมไพเลอร์ออนไลน์รันโค้ดบนเซิร์ฟเวอร์ที่ไม่มีหน้าจอ tk.Tk() จึงล้มเหลวด้วย "no display name and no $DISPLAY environment variable" ที่นี่หน้าต่างถูกวาดในเบราว์เซอร์ของคุณ

โปรแกรมเปิดและบันทึกไฟล์ได้ไหม?

ได้ filedialog แสดงไฟล์ในพื้นที่ทำงานของคุณ และใน Chrome หรือ Edge คุณยังอัปโหลดไฟล์จากคอมพิวเตอร์ได้ด้วย ไฟล์ที่โปรแกรมเขียนจะถูกบันทึกลงพื้นที่ทำงานเมื่อรันจบ

อะไรที่ใช้ไม่ได้?

คำสั่ง Tcl โดยตรง (tk.call, eval), subprocess และไลบรารีที่ต้องใช้เดสก์ท็อป เช่น pyautogui เธรดใช้ได้ แต่จะผลัดกันทำงานกับหน้าต่างแทนที่จะทำงานพร้อมกัน