开发者

When programming a GUI, is it possible to have a loop running in the background all the time?

I am self teaching myself some python OOP, and I have created a simple GUI that starts a number of scripts in the background using Popen. I need to determine at all times whether these scripts are active or not, which I was going to use a loop for.

But how can I have a loop running in the background at 开发者_如何学Pythonall times, without disrupting the user's ability to use the GUI?


You must run a thread in the background. A thread is simply a set of code that runs at the same time as anyother thread. A python program for example is one thread, only one action can occur at any one time, which is why you will see a lag with a infinite loop and a gui. If you create a new thread though the gui will run in one thread, and the loop in a separate thread. This is in a perfect world.

Look further on google threading in python, but here are some links: http://www.prasannatech.net/2008/08/introduction-to-thread-programming.html http://www.wellho.net/solutions/python-python-threads-a-first-example.html http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/

Good luck


To have your program do more than one thing at a time use the threading module. For communication between threads use the queue module. But first google "python threading tutorial" so you can understand how threads work.


Be mindful that python doesn't support muliple execution threading. When python is running only 1 thread is running at any given time. However, you still have to ensure that you're data is secured against multiples accesses (i.e one thread starts to do something, is interupting, another thread gets to execute and starts doing something else, hilarity ensues)

When coding in a gui you shouldn't(and probalby won't since it often leads to crashes) manipulate your widgets from more than one thread. Most GUIs supply a means of posting 'tasks' to the thread that is running the GUI) That can be tedious, but it's the only way it will work. For example: wxPython supplies a wx.CallAfter function.

As much as is possible try to allocate your locks(to prevent threads from touching on shared data at the same time) and condition objects(that are used for signaling to one thread to proceed with something from another thread) in your constructor(s) BEFORE you crank up your threads:

import threading

class(object):
    def __init__(self):
        self._lock = threading.Lock()
        self._cond = threading.Condition(self._lock) # conditions are associated with locks

And be prepared to see this construct alot:

 def myMethod(self):
    self._lock.acquire()
    try:    # or with if you prefer
       # do my stuff
       # pack up my data
       def myFunc():
          # post updates to widgets

    finally:
       self._lock.release()

       wx.CallAfter(myFunc)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜