Window freezes after clicking of button in python

2019-05-19 04:09发布

问题:

Hello I have some command, which runs for average 30 min, when I click on button created by GTK3, python starts to executing command but my all application freezes. My python code for button clicked is:

def on_next2_clicked(self,button):
    cmd = "My Command"
    proc = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
    while True:
            line = proc.stdout.read(2)
            if not line:
                break
            self.fper = float(line)/100.0
            self.ui.progressbar1.set_fraction(self.fper)
    print "Done"

I also have to set output of command to progress bar in my window. Can any one help to solve my problem ? I also tried with Threading in python, but it also falls useless...

回答1:

Run a main loop iteration from within your loop:

def on_next2_clicked(self,button):
    cmd = "My Command"
    proc = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
    while True:
        line = proc.stdout.read(2)
        if not line:
            break
        self.fper = float(line)/100.0
        self.ui.progressbar1.set_fraction(self.fper)
        while Gtk.events_pending():
            Gtk.main_iteration()  # runs the GTK main loop as needed
    print "Done"


回答2:

You are busy-waiting, not letting the UI main event loop run. Put the loop in a separate thread so the main thread can continue its own event loop.

Edit: Adding example code

import threading

def on_next2_clicked(self,button):
    def my_thread(obj):
        cmd = "My Command"
        proc = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
        while True:
                line = proc.stdout.read(2)
                if not line:
                    break
                obj.fper = float(line)/100.0
                obj.ui.progressbar1.set_fraction(obj.fper)
        print "Done"

    threading.Thread(target=my_thread, args=(self,)).start()

The above modification to your function will start a new thread that will run in parallel with your main thread. It will let the main event loop continue while the new thread does the busy waiting.



标签: python gtk3