Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/wxPython: Doing work continuously in the background

I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.

When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.

How should I run the rendering function?

like image 747
Ram Rachum Avatar asked Apr 08 '09 15:04

Ram Rachum


People also ask

How to run Python programs in the background?

pythonw <nameOfFile.py> Here’s the background.py is the file: In Linux and mac, for running py files in the background you just need to add & sign after using command it will tell the interpreter to run the program in the background

Who created wxPython?

Since Robin Dunn is the creator of wxPython, I ended up going this route and here is what is the code I ended up with by using his advice: Here's an example screenshot using a fun butterfly picture I took over the summer for my background image:

Does wxPython's photoimage widget work with Tkinter?

After looking at Tkinter, I discovered that it's PhotoImage widget only supported two formats: gif and pgm (unless I installed the Python Imaging Library). Because of this, I decided to give wxPython a whirl.

How to connect to WX server from Python?

Another way to do it would be to create a socket server using Python's socket module and communicate with wx that way. This is called "threading". Use pythons threading module.


Video Answer


1 Answers

I would use a threading.Thread to run the code in the background and wx.CallAfter to post updates to my window thread to render them to the user.

thread = threading.Thread(target=self.do_work)
thread.setDaemon(True)
thread.start()

...

def do_work(self):
    # processing code here
    while processing:
        # do stuff
        wx.CallAfter(self.update_view, args, kwargs)

def update_view(self, args):
    # do stuff with args
    # since wx.CallAfter was used, it's safe to do GUI stuff here
like image 178
FogleBird Avatar answered Oct 05 '22 23:10

FogleBird