Tkinter เป็น tk GUI toolkit แบบข้ามแพลตฟอร์ม ที่พัฒนาจากไลบรารี Python ใช้สร้างแอปพลิเคชันแบบ GUI แอปพลิเคชัน Tkinter สามารถรวมเป็นไฟล์ executable หรือ runnable ได้ ซึ่งทำให้รันได้โดยไม่ต้องใช้ Python interpreter หรือ IDLE ความจำเป็นในการรวมแอปพลิเคชันเป็นเรื่องสำคัญเมื่อผู้ใช้ต้องการแชร์แอปพลิเคชันโดยไม่แชร์โค้ด
Python มีโมดูลและส่วนขยายหลากหลายที่เข้าถึงได้เพื่อแปลงแอปพลิเคชันที่ทำงานอยู่เป็นไฟล์ executable, portable แต่ละไฟล์รันบนแพลตฟอร์มต่างกัน ดังนั้นเพื่อให้เข้าถึงได้ทุก OS Python จัดเตรียมแพ็กเกจสำหรับ Windows, MacOS, หรือ Linux
ที่นี่เราจะใช้แพ็กเกจ PyInstaller ใน Python เพื่อรวมแอปพลิเคชันเป็นไฟล์ executable ติดตั้ง PyInstaller ด้วยคำสั่ง:
pip install pyinstaller
หลังติดตั้งแล้ว ทำตามขั้นตอนเพื่อแปลงไฟล์สคริปต์ Python (ที่มีแอปพลิเคชัน Tkinter) เป็นไฟล์ Executable:
- ติดตั้ง pyinstaller ด้วย pip install pyinstaller ใน Windows พิมพ์คำสั่งต่อไปนี้และกด Enter
pyinstaller --onefile -w filename
- ตรวจสอบตำแหน่งไฟล์ (script file) จะพบโฟลเดอร์ dist ซึ่งมีไฟล์ executable อยู่ภายใน
- เมื่อรันไฟล์ จะแสดงหน้าต่างของแอปพลิเคชัน Tkinter
ตัวอย่าง
ในตัวอย่างนี้ สร้างแอปพลิเคชันขอให้ผู้ใช้ป้อนชื่อ และทักทายด้วยชื่อของผู้ใช้
# Import the required Libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win =Tk()
# Set the geometry of tkinter frame
win.geometry("750x250")
# Define a function to show a message
def myclick():
message="Hello "+ entry.get()
label=Label(frame, text=message, font=('Times New Roman', 14, 'italic'))
entry.delete(0, 'end')
label.pack(pady=30)
# Creates a Frame
frame =LabelFrame(win, width=400, height=180, bd=5)
frame.pack()
# Stop the frame from propagating the widget to be shrink or fit
frame.pack_propagate(False)
# Create an Entry widget in the Frame
entry =ttk.Entry(frame, width=40)
entry.insert(INSERT, "Enter Your Name")
entry.pack()
# Create a Button
ttk.Button(win, text="Click", command=myclick).pack(pady=20)
win.mainloop()ผลลัพธ์
รันคำสั่งต่อไปนี้เพื่อแปลงโค้ดเป็นไฟล์ executable
pyinstaller --onefile -w filename
จะสร้างโฟลเดอร์ dist ที่มีไฟล์ executable วางไว้โดยอัตโนมัติ
เมื่อรันไฟล์ exe จะแสดงหน้าต่างที่มี Entry widget หากคลิกปุ่ม "Click" จะแสดงข้อความทักทายบนหน้าจอ
