wxPython, Threads, and PostEvent between modules - python

I'm relatively new to wxPython (but not Python itself), so forgive me if I've missed something here.
I'm writing a GUI application, which at a very basic level consists of "Start" and "Stop" buttons that start and stop a thread. This thread is an infinite loop, which only ends when the thread is stopped. The loop generates messages, which at the moment are just output using print.
The GUI class and the infinite loop (using threading.Thread as a subclass) are held in separate files. What is the best way to get the thread to push an update to something like a TextCtrl in the GUI? I've been playing around with PostEvent and Queue, but without much luck.
Here's some bare bones code, with portions removed to keep it concise:
main_frame.py
import wx
from loop import Loop
class MainFrame(wx.Frame):
def __init__(self, parent, title):
# Initialise and show GUI
# Add two buttons, btnStart and btnStop
# Bind the two buttons to the following two methods
self.threads = []
def onStart(self):
x = Loop()
x.start()
self.threads.append(x)
def onStop(self):
for t in self.threads:
t.stop()
loop.py
class Loop(threading.Thread):
def __init__(self):
self._stop = threading.Event()
def run(self):
while not self._stop.isSet():
print datetime.date.today()
def stop(self):
self._stop.set()
I did, at one point, have it working by having the classes in the same file by using wx.lib.newevent.NewEvent() along these lines. If anyone could point me in the right direction, that'd be much appreciated.

The easiest solution would be to use wx.CallAfter
wx.CallAfter(text_control.SetValue, "some_text")
You can call CallAfter from any thread and the function that you pass it to be called will be called from the main thread.

Related

Stopping an infinite loop in a worker thread in PyQt5 the simplest way

I intend to have a GUI where one (later three) threads read live data from different sources with an adjustable interval (e.g. 10s) and plot these data in the main window.
I am using PyQt5 and python 3.6.
The reading is performed in an infinite loop in a worker thread as such:
class ReadingThread(QtCore.QObject):
output = QtCore.pyqtSignal(object)
def __init__(self, directory, interval):
QtCore.QObject.__init__(self)
self.directory=directory
self.stillrunning = True
self.refreshtime = interval
def run(self):
print('Entered run in worker thread')
self.stillrunning = True
while self.stillrunning:
outstring=self.read_last_from_logfile() # data reader function, not displayed
self.output.emit(outstring)
time.sleep(self.refreshtime)
#QtCore.pyqtSlot(int) # never called as loop is blocking?
def check_break(self, val):
if val:
self.stillrunning=False
else:
self.stillrunning = True
The main thread looks like this, start() and stop() are called via pushButtons:
class Window(QtWidgets.QMainWindow, MainWindow.Ui_MainWindow):
def __init__(self, directory, interval):
super(Window, self).__init__()
self.thread = QtCore.QThread()
self.worker = ReadingThread(directory, interval)
emit_stop=QtCore.pyqtSignal(int)
def start(self):
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.run)
self.worker.output.connect(self.print_new_value)
self.emit_stop.connect(self.worker.check_break)
self.thread.start()
def stop(self):
self.emit_stop.emit(1)
# time.sleep(11)
if self.thread.isRunning(): #did not work either
self.thread.quit()
if self.thread.isRunning(): #did also not work
self.thread.terminate()
return
def print_new_value(self, value): #test function for output of values read by worker thread, working well
print (value)
return
def main():
app = QtWidgets.QApplication(sys.argv)
interval=10 #read every 10s new data
directory="/home/mdt-user/logfiles/T_P_logs"
gui = Window(directory,interval)
gui.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
My problem is: How can I let the worker thread in the loop look for incoming signals issued by the main thread? Or differently phrased: How can I have a status variable like my self.stillrunning which can be set/accessed outside the worker thread but checked within the worker thread?
I want to avoid killing the thread with means like self.thread.terminate(), which I did unsuccessfully try.
Help would very much be appreciated. I did a search of course, but the answers given and/or problems stated were either too lengthy for what I assume has to be a simple solution, or not applicable.
I don’t see how above comment could have solved your issue. By design your worker will not be able to receive signals, as the while loop blocks the worker event loop until it breaks and the method finishes. Then all the (throughout the blockage) received signals will be worked. Well, technically your received signals aren’t blocked, they’re just not getting worked, until the event loop is being worked again...
I see two solutions, that work with your design pattern (utilizing move to thread).
Solution 1: QTimer (clean, more QT like solution)
The idea here is to use a QTimer. You provide a time period (in milliseconds) to this timer and every time this period is passed, said timer will perform a task (i.e. call a method/function). As you can even pass 0 ms as time period, you can emulate a while loop like behavior. The upside: The event loop won’t be blocked and after every timeout, received signals will be worked.
I modified your code realizing this solution via QTimer. I think with the code comments this example is somewhat self-explanatory.
class ReadingThread(QtCore.QObject):
output = QtCore.pyqtSignal(object)
def __init__(self, directory, interval):
#QtCore.QObject.__init__(self)
super(ReadingThread, self).__init__() # this way is more common to me
self.directory = directory
self.refreshtime = interval
# setting up a timer to substitute the need of a while loop for a
# repetitive task
self.poller = QTimer(self)
# this is the function the timer calls upon on every timeout
self.poller.timeout.connect(self._polling_routine)
def _polling_routine(self):
# this is what's inside of your while loop i.e. your repetitive task
outstring = self.read_last_from_logfile()
self.output.emit(outstring)
def polling_start(self):
# slot to call upon when timer should start the routine.
self.poller.start(self.refreshtime)
# the argument specifies the milliseconds the timer waits in between
# calls of the polling routine. If you want to emulate the polling
# routine in a while loop, you could pass 0 ms...
def polling_stop(self):
# This simply stops the timer. The timer is still "alive" after.
self.poller.stop()
# OR substitute polling_start and polling_stop by toggling like this:
def polling_toggle(self):
poller_active = self.poller.isActive()
if poller_active:
# stop polling
self.poller.stop()
else:
# start polling
self.poller.start(self.refreshtime)
class Window(QtWidgets.QMainWindow, MainWindow.Ui_MainWindow):
emit_start = QtCore.pyqtSignal()
emit_stop = QtCore.pyqtSignal()
def __init__(self, directory, interval):
super(Window, self).__init__()
self.init_worker()
def init_worker(self):
self.thread = QtCore.QThread()
self.worker = ReadingThread(directory, interval)
self.worker.moveToThread(self.thread)
self.worker.output.connect(self.print_new_value)
self.emit_start.connect(self.worker.polling_start)
self.emit_stop.connect(self.worker.polling_stop)
self.thread.start()
def start_polling(self):
self.emit_start.emit()
def stop_polling(self):
self.emit_stop.emit()
def finish_worker(self):
# for sake of completeness: call upon this method if you want the
# thread gone. E.g. before closing your application.
# You could emit a finished sig from your worker, that will run this.
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
def print_new_value(self, value):
print(value)
For a better look at how to do this cleanly with QThread (the complexity here is doing the threading right, the QTimer is relatively trivial): https://realpython.com/python-pyqt-qthread/#using-qthread-to-prevent-freezing-guis
EDIT: Make sure to check out the documentation of the QTimer. You can dynamically set the timeout period and so much more.
Solution 2: Passing a mutable as a control variable
You can e.g. pass a dictionary with a control variable into your worker class/thread and use it to break the loop. This works, as (oversimplified statements follow) threads share common memory and mutable objects in python share the same object in memory (this has been more than thoroughly discussed on SO).
I’ll illustrate this here in your modified code, also illustrated you'll find that the memory id is the same for your control dicts in the main and the worker thread:
class ReadingThread(QtCore.QObject):
output = QtCore.pyqtSignal(object)
def __init__(self, directory, interval, ctrl):
QtCore.QObject.__init__(self)
self.ctrl = ctrl # dict with your control var
self.directory = directory
self.refreshtime = interval
def run(self):
print('Entered run in worker thread')
print('id of ctrl in worker:', id(self.ctrl))
self.ctrl['break'] = False
while True:
outstring=self.read_last_from_logfile()
self.output.emit(outstring)
# checking our control variable
if self.ctrl['break']:
print('break because flag raised')
# might emit finished signal here for proper cleanup
break # or in this case: return
time.sleep(self.refreshtime)
class Window(QtWidgets.QMainWindow, MainWindow.Ui_MainWindow):
emit_stop=QtCore.pyqtSignal(int)
def __init__(self, directory, interval):
super(Window, self).__init__()
self.thread = QtCore.QThread()
self.ctrl = {'break': False} # dict with your control variable
print('id of ctrl in main:', id(self.ctrl))
# pass the dict with the control variable
self.worker = ReadingThread(directory, interval, self.ctrl)
def start(self):
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.run)
self.worker.output.connect(self.print_new_value)
self.thread.start()
def stop(self):
# we simply set the control variable (often refered to as raising a flag)
self.ctrl['break'] = True
This solution almost requires no changes to your code, and I would definitely consider it not QT like or even clean, but it is extremely convenient. And sometimes you don’t want to code your experiment/long running task around the fact that you’re using a GUI toolkit.
This is the only way I know of, that let’s you get around the blocked event loop. If somebody has a cleaner solution to this, please let the world know. Especially as this is the only way, to break out of your long running task in a controlled manner, from multiple points, as you can check for your control variable multiple times throughout your repetitive routine.

Python - Run next thread when the previous one is finished

I'm writing a tkinter app.
I want to use Thread to avoid the tkinter window freezing but actually I did not find solution.
A quick part of my code (simplify):
from threading import Thread
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
search_button = tk.Button(self, text='Print', command=self.Running)
search_button.grid(row=0, column=0)
def funct1(self):
print('One')
def funct2(self):
print('Two')
def CreateThread(self, item):
self.item = item
t = Thread(target=self.item)
t.start()
def Running(self):
self.CreateThread(self.funct1)
# How to wait for the end of self.CreateThread(self.funct1) ?
self.CreateThread(self.funct2)
if __name__ == '__main__':
myGUI = App()
myGUI.mainloop()
How to wait for the self.CreateThread(self.funct1) ending before running self.CreateThread(self.funct2).
With a queue ?
With something else ?
I already have take a look to Thread.join() but it freez the tkinter window.
Hope you can help me :)
IMO you should think differently about what "Thread" means. A thread is not a thing that you run. A thread is a thing that runs your code. You have two tasks (i.e., things that need to be done), and you want those tasks to be performed sequentially (i.e., one after the other).
The best way to do things sequentially is to do them in the same thread. Instead of creating two separate threads, why not create a single thread that first calls funct1() and then calls funct2()?
def thread_main(self):
funct1()
funct2()
def Running(self):
Threead(target=self.thread_main).start()
P.S.: This could be a mistake:
def CreateThread(self, item):
self.item = item
t = Thread(target=self.item)
t.start()
The problem is, both of the threads are going to assign and use the same self.item attribute, and the value that is written by the first thread may be over-written by the second thread before the first thread gets to used it. Why not simply do this?
def CreateThread(self, item):
Thread(target=item).start()
Or, since the function body reduces to a single line that obviously creates and starts a thread, why even bother to define CreateThread(...) at all?
You can synchronize threads using locks. Hard to give a concrete answer without knowing what needs to be done with these threads. But, locks will probably solve your problem. Here's an article on synchronizing threads.

How to quit PyQT QThread automatically when it is done?

I want a sound to play when I click a button in PyQT5.
Playing a sound appears to be a blocking operation, so GUI is unresponsive. Thus I want to start a new thread, play sound, and delete the thread, all in a non-blocking manner.
I create a thread class
class playSoundThread(QtCore.QThread):
def __init__(self, soundpath):
QtCore.QThread.__init__(self)
self.soundpath = soundpath
def __del__(self):
self.wait()
print("Thread exited")
def run(self):
playsound(self.soundpath)
And run it as follows
class MainClass(...):
...
def playsound(self, soundKey):
self.thisSoundThread = playSoundThread(self.sounds[soundKey])
self.thisSoundThread.start()
Everything works fine and is non-blocking. The only problem is that the thread does not get deleted when the sound stops playing. I have tried calling del self.thisSoundThread, but this operation seems to be blocking, defeating the point.
What is the correct way to exit a thread after completion in a non-blocking way?
Why it should get deleted? I do not see any call of "del" and you assign it into instance so GC also doesnt because there is still existing reference.
If you want to delete it you have to do something like this:
class MainClass(...):
...
def playsound(self, soundKey):
self.thisSoundThread = playSoundThread(self.sounds[soundKey])
self.thisSoundThread.finished.connect(self.threadfinished)
self.thisSoundThread.start()
def threadfinished(self)
del self.thisSoundThread
# or set it to None

Qthread is still working when i close gui on python pyqt

my code has thread, but when i close the gui, it still works on background. how can i stop threads? is there something stop(), close()?
i dont use signal, slots? Must i use this?
from PyQt4 import QtGui, QtCore
import sys
import time
import threading
class Main(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.kac_ders=QtGui.QComboBox()
self.bilgi_cek=QtGui.QPushButton("Save")
self.text=QtGui.QLineEdit()
self.widgetlayout=QtGui.QFormLayout()
self.widgetlar=QtGui.QWidget()
self.widgetlar.setLayout(self.widgetlayout)
self.bilgiler=QtGui.QTextBrowser()
self.bilgi_cek.clicked.connect(self.on_testLoop)
self.scrollArea = QtGui.QScrollArea()
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.widgetlar)
self.analayout=QtGui.QVBoxLayout()
self.analayout.addWidget(self.text)
self.analayout.addWidget(self.bilgi_cek)
self.analayout.addWidget(self.bilgiler)
self.centralWidget=QtGui.QWidget()
self.centralWidget.setLayout(self.analayout)
self.setCentralWidget(self.centralWidget)
def on_testLoop(self):
self.c_thread=threading.Thread(target=self.kontenjan_ara)
self.c_thread.start()
def kontenjan_ara(self):
while(1):
self.bilgiler.append(self.text.text())
time.sleep(10)
app = QtGui.QApplication(sys.argv)
myWidget = Main()
myWidget.show()
app.exec_()
A few things:
You shouldn't be calling GUI code from outside the main thread. GUI elements are not thread-safe. self.kontenjan_ara updates and reads from GUI elements, it shouldn't be the target of your thread.
In almost all cases, you should use QThreads instead of python threads. They integrate nicely with the event and signal system in Qt.
If you just want to run something every few seconds, you can use a QTimer
def __init__(self, parent=None):
...
self.timer = QTimer(self)
self.timer.timeout.connect(self.kontenjan_ara)
self.timer.start(10000)
def kontenjan_ara(self):
self.bilgiler.append(self.text.text())
If your thread operations are more computationally complex you can create a worker thread and pass data between the worker thread and the main GUI thread using signals.
class Worker(QObject):
work_finished = QtCore.pyqtSignal(object)
#QtCore.pyqtSlot()
def do_work(self):
data = 'Text'
while True:
# Do something with data and pass back to main thread
data = data + 'text'
self.work_finished.emit(data)
time.sleep(10)
class MyWidget(QtGui.QWidget):
def __init__(self, ...)
...
self.worker = Worker()
self.thread = QtCore.QThread(self)
self.worker.work_finished.connect(self.on_finished)
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.do_work)
self.thread.start()
#QtCore.pyqtSlot(object)
def on_finished(self, data):
self.bilgiler.append(data)
...
Qt will automatically kill all the subthreads when the main thread exits the event loop.
I chose to rewrite a bit this answer, because I had failed to properly look at the problem's context. As the other answers and comments tell, you code lacks thread-safety.
The best way to fix this is to try to really think "in threads", to restrict yourself to only use objects living in the same thread, or functions that are known as "threadsafe".
Throwing in some signals and slots will help, but maybe you want to think back a bit to your original problem. In your current code, each time a button is pressed, a new thread in launched, that will, every 10 seconds, do 2 things :
- Read some text from self.text
- Append it to self.bilgiler
Both of these operations are non-threadsafe, and must be called from the thread that owns these objects (the main thread). You want to make the worker threads "schedule & wait" the read & append oeprations, instead of simply "executing" them.
I recommend using the other answer (the thread halting problem is automatically fixed by using proper QThreads that integrate well with Qt's event loop), which would make you use a cleaner approach, more integrated with Qt.
You may also want to rethink your problem, because maybe there is a simpler approach to your problem, for example : not spawning threads each time bilgi_cek is clicked, or using Queue objects so that your worker is completely agnostic of your GUI, and only interact with it using threadsafe objects.
Good luck, sorry if I caused any confusion. My original answer is still available here. I think it would be wise to mark the other answer as the valid answer for this question.

Thread Finished Event in Python

I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.
The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread.
I could do it using one thread but the program halts.
I used to do it in C# using a BackgroundWorker which had an event for finishing.
Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit?
In the samples with PyQt-Py2.6-gpl-4.4.4-2.exe, there's the Mandelbrot app. In my install, the source is in C:\Python26\Lib\site-packages\PyQt4\examples\threads\mandelbrot.pyw. It uses a thread to render the pixmap and a signal (search the code for QtCore.SIGNAL) to tell the GUI thread its time to draw. Looks like what you want.
I had a similar issue with one of my projects, and used signals to tell my main GUI thread when to display results from the worker and update a progress bar.
Note that there are several examples to connect objects and signals in the PyQt reference guide. Not all of which apply to python (took me a while to realize this).
Here are the examples you want to look at for connecting a python signal to a python function.
QtCore.QObject.connect(a, QtCore.SIGNAL("PySig"), pyFunction)
a.emit(QtCore.SIGNAL("pySig"), "Hello", "World")
Also, don't forget to add __pyqtSignals__ = ( "PySig", ) to your worker class.
Here's a stripped down version of what I did:
class MyGui(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.worker = None
def makeWorker(self):
#create new thread
self.worker = Worker(work_to_do)
#connect thread to GUI function
QtCore.QObject.connect(self.worker, QtCore.SIGNAL('progressUpdated'), self.updateWorkerProgress)
QtCore.QObject.connect(self.worker, QtCore.SIGNAL('resultsReady'), self.updateResults)
#start thread
self.worker.start()
def updateResults(self):
results = self.worker.results
#display results in the GUI
def updateWorkerProgress(self, msg)
progress = self.worker.progress
#update progress bar and display msg in status bar
class Worker(QtCore.QThread):
__pyqtSignals__ = ( "resultsReady",
"progressUpdated" )
def __init__(self, work_queue):
self.progress = 0
self.results = []
self.work_queue = work_queue
QtCore.QThread.__init__(self, None)
def run(self):
#do whatever work
num_work_items = len(self.work_queue)
for i, work_item in enumerate(self.work_queue):
new_progress = int((float(i)/num_work_items)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.progress = new_progress
self.emit(QtCore.SIGNAL("progressUpdated"), 'Working...')
#process work item and update results
result = processWorkItem(work_item)
self.results.append(result)
self.emit(QtCore.SIGNAL("resultsReady"))
I believe that your drawing thread can send an event to the main thread using QApplication.postEvent. You just need to pick some object as the receiver of the event. More info
Expanding on Jeff's answer: the Qt documentation on thread support states that it's possible to make event handlers (slots in Qt parlance) execute in the thread that "owns" an object.
So in your case, you'd define a slot printImage(QImage) on the form, and a doneDrawing(QImage) signal on whatever is creating the image, and just connect them using a queued or auto connection.

Categories