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

วิธี Bundle แอปพลิเคชัน Python Tkinter รวม Dependencies


ภาพรวม

สมมติสร้างแอป Tkinter แล้วต้องการ Bundle เป็น Standalone Executable ใช้ Package ต่างๆ ที่รองรับฟังก์ชันต่างๆ เพื่อ Bundle โค้ดทั้งหมดเป็น Executable Installer Package เหล่านี้บีบอัดโค้ดและแปลงเป็น Executable

สำหรับ Windows ใช้ py2exe Linux ใช้ Freeze Mac ใช้ py2app

ตัวอย่าง

สร้างแอป Windows พิมพ์ "Hello World" สร้าง setup.py ใน Directory เดียวกับ Main App แล้ว Extend ฟังก์ชันโดยส่ง Filename เป็นพารามิเตอร์ใน setup.py

setup.py

from distutils.core import setup
import py2exe
setup(console=['main_app.py'])

รัน setup.py ด้วย py2exe ใน Command Shell จะสร้าง Folder dist มี Executable main_app.exe

main_app.py

# Import the tkinter library
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the geometry
win.geometry("600x400")
def present():
    Label(win, text="Hello World", font=('Times New Roman bold', 30)).pack(pady=10)
Button(win, text="Click Me", command=present).pack(pady=20)
win.mainloop()

ผลลัพธ์

รัน main_app.exe จะเปิดหน้าต่างพร้อม Button และ Label

วิธี Bundle แอปพลิเคชัน Python Tkinter รวม Dependencies