使用 python 安装 PIP 依赖​​项(使用 OS 或 Subprocess 执行 CLI)并在 tkinter 的进度条中显示进度 [英] Install PIP dependencies using python (using OS or Subprocess for executing CLI) and show progress in progress bar in tkinter

查看:78
本文介绍了使用 python 安装 PIP 依赖​​项(使用 OS 或 Subprocess 执行 CLI)并在 tkinter 的进度条中显示进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to install Node and some pip dependencies using brew and pip in python subprocess(CLI) and also show the status or percent of the download using the tkinter progress bar so the user can see the progress.

有什么办法可以做到吗?

Is there any way I can do so?

例如:

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

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

I want to show the progress of these calls in the progress bar

推荐答案

试试这个:

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 毫秒更新一次.

It implements a progress bar that is inside the new thread. tkinter isn't going to crash as long as we don't use it inside the main thread. That is why I have a global variable progress that is incremented in the main thread and the progress bar is updated in the new thread. The new thread is updated every 100ms using a .after loop.

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

Note that all of the variables that start with t_ are only supposed to be accessed by the new thread and not the main thread.

变量progress超出100

这篇关于使用 python 安装 PIP 依赖​​项(使用 OS 或 Subprocess 执行 CLI)并在 tkinter 的进度条中显示进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆