簡體   English   中英

Python,Tkinter-單獨線程中的ttk.Progressbar

[英]Python, Tkinter - ttk.Progressbar in a separate thread

我對此進行了很多搜索,但仍然找不到我想要的東西。 我想這是一個經典的問題,但我仍然無法弄清楚。

我有這個Python / Tkinter代碼。 該代碼通過使用os.system(cmd)進行os.system(cmd)調用來啟動一個os.system(cmd)大量CPU的進程。 我想要一個進度條(擺動一個,而不是漸進式),向用戶顯示實際發生的事情。 我想我只需要在調用os.system之前先啟動包含進度條的線程,然后在進度條線程運行時調用os.system ,關閉進度條線程並銷毀關聯的Toplevel()

我的意思是說,Python非常靈活,是否可以輕松完成此操作? 我知道從另一個線程中殺死一個線程是不安全的(由於數據共享),但是據我所知,這兩個線程不共享任何數據。

是否可以像這樣去:

progressbar_thread.start()
os.system(...)
progressbar_thread.kill()

如果那是不可能的,我仍然不明白如何在兩個線程之間傳遞“信號”變量。

謝謝,

安德里亞

在這種情況下,您不需要線程。 只需使用subprocess.Popen啟動子進程即可。

要在進程結束時通知GUI,可以使用widget.after()方法實現輪詢:

process = Popen(['/path/to/command', 'arg1', 'arg2', 'etc'])
progressbar.start()

def poller():
    if process.poll() is None: # process is still running
       progressbar.after(delay, poller)  # continue polling
    else:
       progressbar.stop() # process ended; stop progress bar

delay = 100  # milliseconds
progressbar.after(delay, poller) # call poller() in `delay` milliseconds

如果要手動停止該過程而不等待:

if process.poll() is None: # process is still running
   process.terminate()
   # kill process in a couple of seconds if it is not terminated
   progressbar.after(2000, kill_process, process)

def kill_process(process):
    if process.poll() is None:
        process.kill()
        process.wait()

這是一個完整的示例

這是您所追求的類型嗎?

from Tkinter import *
import ttk, threading

class progress():
    def __init__(self, parent):
            toplevel = Toplevel(tk)
            self.progressbar = ttk.Progressbar(toplevel, orient = HORIZONTAL, mode = 'indeterminate')
            self.progressbar.pack()
            self.t = threading.Thread()
            self.t.__init__(target = self.progressbar.start, args = ())
            self.t.start()
            #if self.t.isAlive() == True:
             #       print 'worked'

    def end(self):
            if self.t.isAlive() == False:
                    self.progressbar.stop()
                    self.t.join()


def printmsg():
    print 'proof a new thread is running'


tk = Tk()
new = progress(tk)
but1 = ttk.Button(tk, text= 'stop', command= new.end)
but2 = ttk.Button(tk, text = 'test', command= printmsg)
but1.pack()
but2.pack()
tk.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM