上圖
?
import os
import time
import threading
import requests
import subprocess
import importlib
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urljoinclass PackageInstallerApp:def __init__(self, root):self.root = rootself.root.title("Design By Tim")self.root.geometry("800x600")# 默認設置self.install_dir = r"C:\Users\AAA\Python_Package"self.default_packages = ["numpy", "opencv-python", "pyttsx3"]self.mirrors = ["https://pypi.tuna.tsinghua.edu.cn/simple/","https://mirrors.aliyun.com/pypi/simple/","https://pypi.mirrors.ustc.edu.cn/simple/","https://mirrors.bfsu.edu.cn/pypi/web/simple/","https://mirrors.cloud.tencent.com/pypi/simple/","https://mirrors.nju.edu.cn/pypi/web/simple/","https://mirrors.hit.edu.cn/pypi/web/simple/","https://mirror.sjtu.edu.cn/pypi/web/simple/","https://pypi.doubanio.com/simple/","https://mirrors.zju.edu.cn/pypi/web/simple/","https://mirrors.pku.edu.cn/pypi/simple/","https://mirrors.yun-idc.com/pypi/simple/","https://mirrors.neusoft.edu.cn/pypi/web/simple/","https://mirrors.xjtu.edu.cn/pypi/web/simple/","https://mirrors.huaweicloud.com/repository/pypi/simple/"]# UI控件引用self.start_button = Noneself.cancel_button = None# 創建UIself.create_widgets()def create_widgets(self):# 主框架main_frame = ttk.Frame(self.root, padding="10")main_frame.pack(fill=tk.BOTH, expand=True)# 包列表輸入ttk.Label(main_frame, text="要下載的包(逗號分隔):").grid(row=0, column=0, sticky=tk.W)self.pkg_entry = ttk.Entry(main_frame, width=50)self.pkg_entry.grid(row=0, column=1, sticky=tk.EW)self.pkg_entry.insert(0, ",".join(self.default_packages))# 安裝目錄ttk.Label(main_frame, text="安裝目錄:").grid(row=1, column=0, sticky=tk.W)self.dir_entry = ttk.Entry(main_frame, width=50)self.dir_entry.grid(row=1, column=1, sticky=tk.EW)self.dir_entry.insert(0, self.install_dir)# 按鈕框架btn_frame = ttk.Frame(main_frame)btn_frame.grid(row=2, column=0, columnspan=2, pady=10)# 開始按鈕self.start_button = ttk.Button(btn_frame, text="開始下載安裝", command=self.start_process)self.start_button.pack(side=tk.LEFT, padx=5)# 取消按鈕self.cancel_button = ttk.Button(btn_frame, text="取消", command=self.root.quit)self.cancel_button.pack(side=tk.LEFT, padx=5)# 進度條self.progress = ttk.Progressbar(main_frame, orient=tk.HORIZONTAL, length=500, mode='determinate')self.progress.grid(row=3, column=0, columnspan=2, pady=10)# 狀態標簽self.status_label = ttk.Label(main_frame, text="準備就緒")self.status_label.grid(row=4, column=0, columnspan=2)# 日志輸出ttk.Label(main_frame, text="進度日志:").grid(row=5, column=0, sticky=tk.W)self.log_text = scrolledtext.ScrolledText(main_frame, width=80, height=20, state='normal')self.log_text.grid(row=6, column=0, columnspan=2, sticky=tk.NSEW)# 配置網格權重main_frame.columnconfigure(1, weight=1)main_frame.rowconfigure(6, weight=1)def log_message(self, message):self.log_text.config(state='normal')self.log_text.insert(tk.END, message + "\n")self.log_text.config(state='disabled')self.log_text.see(tk.END)self.root.update()def update_progress(self, value):self.progress['value'] = valueself.root.update()def update_status(self, message):self.status_label.config(text=message)self.root.update()def set_ui_state(self, enabled):state = tk.NORMAL if enabled else tk.DISABLEDself.start_button.config(state=state)self.cancel_button.config(state=state)self.root.update()def start_process(self):# 獲取用戶輸入packages = [pkg.strip() for pkg in self.pkg_entry.get().split(",") if pkg.strip()]self.install_dir = self.dir_entry.get().strip()if not packages:messagebox.showerror("錯誤", "請輸入至少一個包名")returnos.makedirs(self.install_dir, exist_ok=True)# 禁用UIself.set_ui_state(False)self.log_text.config(state='normal')self.log_text.delete(1.0, tk.END)self.log_text.config(state='disabled')self.update_progress(0)# 開始下載安裝流程threading.Thread(target=self.download_and_install, args=(packages,), daemon=True).start()def download_and_install(self, packages):overall_success = True # 跟蹤整體成功狀態try:# 1. 測試鏡像源速度self.update_status("正在測試鏡像源速度...")self.log_message("="*50)self.log_message("開始測試鏡像源速度")fastest_mirrors = self.find_fastest_mirrors()# 2. 下載包self.update_status("開始下載包...")self.log_message("="*50)self.log_message("開始下載包")downloaded_files = []total_packages = len(packages)download_success = Truefor i, package in enumerate(packages):self.update_progress((i/total_packages)*50)mirror = fastest_mirrors[i % len(fastest_mirrors)]success, files = self.download_package(mirror, package)if not success:download_success = Falseoverall_success = Falseself.log_message(f"?? 包 {package} 下載失敗,將繼續嘗試其他包")else:downloaded_files.extend(files)if not download_success:self.log_message("警告: 部分包下載失敗")# 3. 安裝包self.update_status("開始安裝包...")self.log_message("="*50)self.log_message("開始安裝包")install_success = Truefor i, file in enumerate(downloaded_files):self.update_progress(50 + (i/len(downloaded_files))*40)if not self.install_package(file):install_success = Falseoverall_success = Falseself.log_message(f"?? 文件 {file} 安裝失敗")if not install_success:self.log_message("警告: 部分包安裝失敗")# 4. 驗證安裝self.update_status("驗證安裝...")self.log_message("="*50)self.log_message("開始驗證安裝")verify_success = Truefor i, package in enumerate(packages):self.update_progress(90 + (i/len(packages))*10)if not self.test_installation(package):verify_success = Falseoverall_success = Falseself.log_message(f"?? 包 {package} 驗證失敗")if not verify_success:self.log_message("警告: 部分包驗證失敗")self.update_progress(100)# 顯示最終結果if overall_success:self.update_status("所有操作成功完成!")self.log_message("="*50)self.log_message("? 所有包下載安裝完成并驗證成功!")messagebox.showinfo("完成", "所有包下載安裝完成并驗證成功!")else:self.update_status("操作完成,但有錯誤發生")self.log_message("="*50)self.log_message("?? 操作完成,但部分步驟失敗,請檢查日志")messagebox.showwarning("完成但有錯誤", "操作完成,但部分步驟失敗,請檢查日志了解詳情")except Exception as e:self.log_message(f"? 發生嚴重錯誤: {str(e)}")self.update_status("操作因錯誤中止")messagebox.showerror("錯誤", f"處理過程中發生嚴重錯誤: {str(e)}")overall_success = Falsefinally:# 重新啟用UIself.set_ui_state(True)def find_fastest_mirrors(self):"""找出最快的3個鏡像源"""with ThreadPoolExecutor(max_workers=15) as executor:futures = [executor.submit(self.test_mirror_speed, mirror) for mirror in self.mirrors]results = []for future in as_completed(futures):speed, mirror = future.result()if speed != float('inf'):results.append((speed, mirror))self.log_message(f"測試鏡像源 {mirror} 速度: {speed:.2f}秒")results.sort()fastest_mirrors = [mirror for speed, mirror in results[:3]]self.log_message(f"最快的3個鏡像源: {', '.join(fastest_mirrors)}")return fastest_mirrorsdef test_mirror_speed(self, mirror):"""測試鏡像源速度"""try:start = time.time()response = requests.get(urljoin(mirror, "simple/"), timeout=5)if response.status_code == 200:return time.time() - start, mirrorexcept:passreturn float('inf'), mirrordef download_package(self, mirror, package):"""下載單個包"""try:self.log_message(f"正在從 {mirror} 下載 {package}...")cmd = ["python", "-m", "pip", "download", package, "-d", self.install_dir, "-i", mirror, "--trusted-host", mirror.split('//')[1].split('/')[0]]process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)stdout, stderr = process.communicate()if process.returncode == 0:# 獲取下載的文件列表files = [f for f in os.listdir(self.install_dir) if f.startswith(package.replace("-", "_"))]self.log_message(f"? 成功下載 {package}: {', '.join(files)}")return True, fileselse:self.log_message(f"? 下載 {package} 失敗: {stderr.strip()}")return False, []except Exception as e:self.log_message(f"? 下載 {package} 時發生錯誤: {str(e)}")return False, []def install_package(self, filename):"""安裝單個包"""try:filepath = os.path.join(self.install_dir, filename)self.log_message(f"正在安裝 {filename}...")cmd = ["python", "-m", "pip", "install", filepath]process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)stdout, stderr = process.communicate()if process.returncode == 0:self.log_message(f"? 成功安裝 {filename}")return Trueelse:self.log_message(f"? 安裝 {filename} 失敗: {stderr.strip()}")return Falseexcept Exception as e:self.log_message(f"? 安裝 {filename} 時發生錯誤: {str(e)}")return Falsedef test_installation(self, package):"""測試包是否安裝成功"""try:# 轉換包名(如opencv-python -> opencv_python)import_name = package.replace("-", "_")self.log_message(f"正在驗證 {package} 是否可以導入...")module = importlib.import_module(import_name)version = getattr(module, "__version__", "未知版本")self.log_message(f"? 驗證成功: {package} (版本: {version})")return Trueexcept Exception as e:self.log_message(f"? 驗證失敗: 無法導入 {package} - {str(e)}")return Falseif __name__ == "__main__":root = tk.Tk()app = PackageInstallerApp(root)root.mainloop()
?