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

วิธีสร้างแอป GUI ข้ามแพลตฟอร์มที่รันได้โดยตรงด้วย Python (Tkinter)


Python เป็นภาษาโปรแกรมมิ่งที่ใช้สร้างแอปพลิเคชันข้ามแพลตฟอร์มรองรับ OS หลากหลาย เช่น Microsoft Windows, Mac OS, และ Linux

เพื่อสร้างแอปพลิเคชัน GUI ใช้ไลบรารี Tkinter อย่างไรก็ตาม Python มีโมดูลและส่วนขยายต่างๆ แปลงโปรแกรมเป็นแอปพลิเคชัน executable

  • สำหรับ Windows executables - PyInstaller, py2exe
  • สำหรับ Linux executables - Freeze
  • สำหรับ Mac executables - py2app

ตัวอย่าง

สำหรับตัวอย่างนี้ จะติดตั้งโมดูล PyInstaller ด้วย pip ใน Windows OS โมดูลติดตั้งได้ด้วยคำสั่ง:

pip install pyInstaller

ใช้โมดูลนี้แปลงแอปพลิเคชันเป็นไฟล์ executable

app.py

ในแอปพลิเคชันนี้ จะขอให้ผู้ใช้เลือกวันจากรายการ

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")

# Add a Label
Label(win, text="Select a Day from the Menu", font=('Aerial 13')).pack(pady=10)

# Create a Variable to store the selection
var = StringVar()

# Create an OptionMenu Widget and add choices to it
option = OptionMenu(win, var, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
option.config(bg="gray81", fg="white")
option['menu'].config(bg="green3")
option.pack(padx=20, pady=30)

win.mainloop()

ผลลัพธ์

วิธีสร้างแอป GUI ข้ามแพลตฟอร์มที่รันได้โดยตรงด้วย Python (Tkinter)

ขั้นตอนสร้าง Executable File ใน Python

  • เปิด command prompt ในไดเรกทอรีและพิมพ์คำสั่งสร้างไฟล์ executable:
pyinstaller app.py
  • จะสร้างโฟลเดอร์ที่มีไฟล์ executable app.exe เปิดไฟล์เพื่อรันแอปพลิเคชัน