Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การใช้ Tkinter ใน Jupyter Notebook

Tkinter สามารถทำงานใน Jupyter Notebook ได้ แต่ต้องมีการติดตั้งและการตั้งค่าพิเศษ เพราะ Jupyter รันบน Server และ GUI ต้องการ Display Server (X11/Wayland)

การติดตั้ง


# ใน Terminal/Command Prompt (ไม่ใช่ใน Notebook cell)
pip install tkinter

# Linux (Ubuntu/Debian)
sudo apt-get install python3-tk

# macOS (Homebrew)
brew install python-tk

การรัน Tkinter ใน Jupyter

วิธี 1: ใช้ %matplotlib widget หรือ inline (ไม่ทำงานกับ Tkinter โดยตรง)

Tkinter ต้องการ Event Loop จริง ไม่เข้ากับ Jupyter's inline backend

วิธี 2: รันใน Cell แล้วโต้ตอบกับหน้าต่างที่โผล่ขึ้นมา (Windows/macOS Local)


# รันใน Cell เดียว (Shift+Enter)
from tkinter import *

win = Tk()
win.geometry("750x250")

def callback():
    Label(win, text="Hello World!", font=('Century 20 bold')).pack(pady=4)

btn = Button(win, text="Press Enter", command=callback)
btn.pack(ipadx=10)
win.bind('', lambda event: callback())
win.mainloop()

วิธี 3: ใช้ ipywidgets หรือ Voila สำหรับ GUI ใน Browser


pip install ipywidgets
# หรือใช้ Voila แปลง Notebook เป็น Web App

วิธี 4: Remote Server (Colab, Kaggle, binder) - ใช้ Xvfb


# Google Colab
!apt-get install -y xvfb python3-tk
import os
os.system("Xvfb :99 -screen 0 1024x768x24 &")
os.environ["DISPLAY"] = ":99"

from tkinter import *
win = Tk()
# ... สร้าง GUI
win.mainloop()  # จะบล็อก cell นี้

ข้อจำกัดใน Jupyter

  • mainloop() บล็อก Kernel - ไม่รัน Cell ถัดไปได้จนกว่าจะปิดหน้าต่าง
  • ไม่เหมาะสำหรับ Interactive Development ใน Notebook
  • Remote Server ต้องการ Virtual Display (Xvfb)
  • ไม่สามารถใช้ %matplotlib inline ควบคู่ได้

ทางเลือกที่ดีกว่าสำหรับ Jupyter

  • ipywidgets - Interactive widgets ทำงานใน Browser
  • Panel / HoloViz - Dashboarding
  • Streamlit - Web apps จาก Scripts
  • Gradio - ML Demo interfaces
  • Voila - แปลง Notebook เป็น Web App

สรุป

Tkinter ใน Jupyter ใช้ได้เฉพาะ Local Machine ที่มี Display Server สำหรับการพัฒนาจริงใน Notebook ควรใช้ ipywidgets หรือ Web-based frameworks แทน