2017-05-07 96 views
2

到目前爲止,蝙蝠運行,但進度條沒有。我如何將兩者連接起來?這是輸出的圖像。 http://imgur.com/lKbHepSPython 3 - 如何在bat文件中使用tkinter progressbar?

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() 
+0

批處理文件是否顯示完成百分比? – anonymoose

+0

批處理文件不斷告訴我有多少百分比完成。 –

+0

百分比是什麼格式? – anonymoose

回答

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() 

基本上,有一個線程,從進程讀取數據並使其可於每隔一段時間更新進度條的功能。你沒有提及輸出的格式,所以我寫了它來使用正則表達式來搜索第一個數字並將其轉換。

+0

你可以幫忙解釋一下輸出文件嗎?感謝您的幫助。我真的很感激你的努力。進度條沒有更新,我不知道如何獲取適當的數據。我正在使用一個mp3轉換器。數據顯示完成了一個完整的mp3文件的時間。示例:完成1分鐘,完成2分鐘等。 –

+0

@BHok我在代碼中發現了一個小錯字。我修復了它。現在嘗試運行它。 – anonymoose

+0

進度條不更新,所以我仍然認爲這是因爲輸出。 –