如何打包 Tkinter 程式以便與他人共享?
Tkinter 是一個基於 Python 庫的跨平臺 tk GUI 工具包,用於建立和開發基於 GUI 的應用程式。Tkinter 應用程式可以打包成可執行檔案或可執行檔案,使應用程式無需使用 Python 直譯器或 IDLE 即可執行。當用戶希望與他人共享應用程式而不共享程式碼時,打包應用程式的需求就成為優先事項。
Python 擁有各種模組和擴充套件,允許使用者將正在執行的應用程式轉換為可執行的、可移植的檔案。每個檔案都在不同的平臺上執行;因此,為了使其能夠訪問所有作業系統,Python 為 Windows、MacOS 或基於 Linux 的作業系統提供了軟體包。
在這裡,我們將使用 Python 中的 **Pyinstaller** 軟體包將應用程式打包成可執行檔案。為了安裝 **Pyinstaller**,您可以使用以下命令:
pip install pyinstaller
安裝完成後,我們可以按照以下步驟將 Python 指令碼檔案(包含 Tkinter 應用程式檔案)轉換為可執行檔案。
在 Windows 作業系統中使用 **pip install pyinstaller** 安裝 **pyinstaller**。現在,鍵入以下命令並按 Enter 鍵。
pyinstaller --onefile -w filename
檢查檔案(指令碼檔案)的位置,您將找到一個 **dist** 資料夾,其中包含可執行檔案。
當我們執行該檔案時,它將顯示 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()輸出
現在,執行以下命令將給定的程式碼轉換為可執行檔案。
pyinstaller --onefile -w filename
這將影響目錄(**dist** 資料夾),所有可執行檔案將自動放置在此目錄中。
當我們執行 exe 檔案時,它將顯示一個包含 Entry 控制元件的視窗。如果我們點選“點選”按鈕,它將在螢幕上顯示一條問候訊息。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP