使用 python 安装 PIP 依赖​​项(使用 OS 或子进程执行 CLI)并在 tkinter 的进度条中显示进度

Install PIP dependencies using python (using OS or Subprocess for executing CLI) and show progress in progress bar in tkinter

我想在 python 子进程 (CLI) 中使用 brew 和 pip 安装 Node 和一些 pip 依赖项,并使用 tkinter 进度条显示下载状态或百分比,以便用户可以看到进度.

有什么办法吗?

例如:

    Subprocess.call("brew install node")
    Subprocess.call("pip install tensorflow")
    Subprocess.call("pip install pytorch")
    Subprocess.call("pip install django")

我想在进度条中显示这些调用的进度

试试这个:

from threading import Thread
from tkinter import ttk
import tkinter as tk
import time


progress = 0


def t_create_progress_bar():
    # Don't use a `tk.Toplevel` here
    root = tk.Tk()
    root.resizable(False, False)
    progress_bar = ttk.Progressbar(root, orient="horizontal", length=400)
    progress_bar.pack()

    progress_bar.after(1, t_loop_progress_bar, progress_bar)

    root.mainloop()

def t_loop_progress_bar(progress_bar):
    progress_bar["value"] = progress
    # Update it again in 100ms
    progress_bar.after(100, t_loop_progress_bar, progress_bar)



# Start the new thread
thread = Thread(target=t_create_progress_bar, daemon=True)
thread.start()

progress = 0 # 0% done
Subprocess.call("brew install node")
progress = 25 # 25% done
Subprocess.call("pip install tensorflow")
progress = 50 # 50% done
Subprocess.call("pip install pytorch")
progress = 75 # 75% done
Subprocess.call("pip install django")

它在新线程中实现了一个进度条。 tkinter 只要我们不在主线程中使用它就不会崩溃。这就是为什么我有一个全局变量 progress 在主线程中递增并且进度条在新线程中更新。新线程使用 .after 循环每 100 毫秒更新一次。

请注意,所有以 t_ 开头的变量只能由新线程而不是主线程访问。

编辑:变量progress满分100