Python 3 - 如何将tkinter进度条与bat文件一起使用?

时间:2017-05-07 21:24:57

标签: python-3.x tkinter tk ttk

到目前为止,蝙蝠正在运行,但进度条没有。如何将两者相互连接?这是输出的图像。 http://imgur.com/lKbHepS

from tkinter import *
from tkinter import ttk
from subprocess import call

def runBat():
    call("mp3.bat")

root = Tk()

photobutton3 = PhotoImage(file="smile.png")
button3 = Button(root, image=photobutton3, command=runBat)
button3.grid()

pbar = ttk.Progressbar(root, orient=HORIZONTAL, length=200, mode='determinate')
pbar.grid()

root.mainloop()

1 个答案:

答案 0 :(得分:0)

这个答案最终无效。问题仍然存在。

试试这个:

import subprocess
import threading
import ctypes
import re
from tkinter import *
from tkinter import ttk

class RunnerThread(threading.Thread):
    def __init__(self, command):
        super(RunnerThread, self).__init__()
        self.command = command
        self.percentage = 0
        self.process = None
        self.isRunning = False

    def run(self):
        self.isRunning = True
        self.process = process = subprocess.Popen(self.command, stdout = subprocess.PIPE, shell = True)
        while True:
            #Get one line at a time
            #When read() returns nothing, the process is dead
            line = b""
            while True:
                c = process.stdout.read(1)
                line += c
                if c == b"" or c == b"\r": #Either the process is dead or we're at the end of the line, quit the loop
                    break
            if line == b"": #Process dead
                break
            #Find a number
            match = re.search(r"Frame\=\s(\d+\.?(\d+)?)", line.decode("utf-8").strip())
            if match is not None:
                self.percentage = float(match.group(1))
        self.isRunning = False

    def kill(self): #Something I left in case you want to add a "Stop" button or something like that
        self.process.kill()


def updateProgress():
    progressVar.set(rt.percentage) #Update the progress bar
    if rt.isRunning: #Only run again if the process is still running.
        root.after(10, updateProgress)

def runBat():
    global rt
    rt = RunnerThread("mp3.bat")
    rt.start()
    updateProgress()

root = Tk()

photobutton3 = PhotoImage(file="smile.png")
button3 = Button(root, image=photobutton3, command=runBat)
button3.grid()

progressVar = DoubleVar()
pbar = ttk.Progressbar(root, orient=HORIZONTAL, length=200, mode='determinate', variable = progressVar)
pbar.grid()

root.mainloop()

基本上,有一个线程从进程中读取数据,并使其可用于每隔一段时间更新进度条的函数。你没有提到输出的格式,所以我把它写成使用正则表达式来搜索第一个数字并将其转换。