I'm creating a simple Python UI via Tkinter, and I'd like use self.title to have the window title change when a callback event is generated.
If I bind the event to a button, or call the event handler directly within the Tk thread, the window title changes as expected. However, I intend this event to be invoked by a separate thread, and I've found that using title in the callback event handler causes the app to hang.
Other tasks that I have in the event handler (such as updating a label) work just fine, so I have to assume that the event is being invoked properly. I've tried wm_title instead of title, but didn't see a difference. I've dug around and found nothing odd about title's usage, just call it with a string to set the title.
Here's a stripped-down sample that replicates the problem (I'm running v2.7.1 on WinXP FYI); the app runs fine for 10 seconds (can move the window, resize, etc.), after which Timer generates the event and the app then freezes.
import Tkinter
import threading
class Gui(Tkinter.Tk):
def __init__(self, parent=None):
Tkinter.Tk.__init__(self, parent)
self.title('Original Title')
self.label = Tkinter.Label(self, text='Just a Label.',
width=30, anchor='center')
self.label.grid()
self.bind('<<change_title>>', self.change_title)
timer = threading.Timer(10, self.event_generate, ['<<change_title>>'])
timer.start()
def change_title(self, event=None):
self.title('New Title')
G = Gui(None)
G.mainloop()
I encountered the same problem, where the UI hangs when calling self.title() from a thread other than the main thread. Tkinter expects all UI stuff to be done in the same thread (the main thread).
My solution was to have the separate thread put functions in a queue. The queue is serviced periodically by the main thread, making use of the after(ms) function provided by Tkinter. Here's an example with your code:
import Tkinter
import threading
from Queue import Queue, Empty
class Gui(Tkinter.Tk):
def __init__(self, parent=None):
Tkinter.Tk.__init__(self, parent)
self.ui_queue = Queue()
self._handle_ui_request()
self.title('Original Title')
self.label = Tkinter.Label(self, text='Just a Label.',
width=30, anchor='center')
self.label.grid()
self.bind('<<change_title>>', self.change_title)
timer = threading.Timer(1, self.event_generate, ['<<change_title>>'])
timer.start()
def change_title(self, event=None):
# Separate the function name, it's args and keyword args,
# and put it in the queue as a tuple.
ui_function = (self.title, ('New Title',), {})
self.ui_queue.put(ui_function)
def _handle_ui_request(self):
'''
Periodically services the UI queue to handles UI requests in the main thread.
'''
try:
while True:
f, a, k = self.ui_queue.get_nowait()
f(*a, **k)
except Empty:
pass
self.after(200, self._handle_ui_request)
G = Gui(None)
G.mainloop()
Well, your code actually runs fine to me.
Except that, when interrupted before the ten secs, it says "RuntimeError: main thread is not in main loop"
I'm using python 2.6.6 under ubuntu 10.10
Hope this was of some help.
I tried it as well with 2.6.2 (Windows) and the caption/title didn't change. No runtime error though.
Related
I am posting this as informational for folks looking for a way to communicate thread progress back to a tkinter Frame or window. I have seen several approaches detailed in SO and other sites, but none really seemed adequate to me. So here is an approach that displays progress as both a message box update and advancing a Scale Widget. It uses the tkinter variable classes StringVar and DoubleVar rather than trying to use callbacks or continuously poll a queue in the main thread.
Comments are, of course, welcome, but it appears this approach works well.
`
import tkinter as tk
from tkinter import ttk, END, NW, GROOVE
import threading
import queue
import time
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.queue = queue.Queue()
self.msgCt=0
self.listbox = tk.Listbox(self, width=20, height=5)
self.scaleVal=tk.DoubleVar()
self.progressbar = ttk.Scale(self, orient='horizontal',
length=300,
from_=0.0, to=100.0,
variable=self.scaleVal)
self.scaleVal.set(0.0)
self.button = tk.Button(self, text="Start", command=self.spawnthread)
self.msgBtn = tk.Button(self,text="Set Msg", command=self.sendMessage)
self.msgTxt=tk.StringVar(self,"Messages Here...")
self.msgBox=tk.Message(self,textvariable=self.msgTxt,width=200,
anchor=NW,relief=GROOVE)
self.listbox.grid(row=0,column=0,columnspan=2)
self.msgBox.grid(row=1,column=0,columnspan=2)
self.progressbar.grid(row=2,column=0,columnspan=2)
self.button.grid(row=3,column=0)
self.msgBtn.grid(row=3,column=1)
def spawnthread(self):
self.button.config(state="disabled")
self.listbox.delete(0, END)
self.thread = ThreadedClient(self.queue,self.msgTxt,self.scaleVal)
self.thread.start()
self.periodiccall()
def sendMessage(self,msg=None):
if not msg==None:
self.msgTxt.set(msg)
else:
self.msgTxt.set("Message {}".format(self.msgCt))
self.msgCt+=1
def periodiccall(self):
self.checkqueue()
if self.thread.is_alive():
self.after(100, self.periodiccall)
else:
self.button.config(state="active")
def checkqueue(self):
while self.queue.qsize():
try:
msg = self.queue.get(0)
self.listbox.insert('end', msg)
# self.progressbar.step(25)
except queue.Empty:
pass
class ThreadedClient(threading.Thread):
def __init__(self, qu, mtxt,dvar):
threading.Thread.__init__(self)
self.queue = qu
self.msgTxt=mtxt
self.scaleVal=dvar
def run(self):
self.scaleVal.set(0.0)
for x in range(1, 10):
time.sleep(2)
msg = "Function %s finished..." % x
self.msgTxt.set(msg)
self.scaleVal.set(x*10)
self.queue.put(msg)
if __name__ == "__main__":
app = App()
app.mainloop()
`
In response to the several comments, here is a new version of the code:
import tkinter as tk
from tkinter import ttk, END, NW, GROOVE
import threading
import queue
import time
from pickle import FALSE
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.msgCt=0
self.thrdCt=0;
self.scaleVal=tk.DoubleVar()
self.doneSignal=tk.BooleanVar()
self.doneSignal.set(False)
self.doneSignal.trace("w",self.on_doneSignal_set)
self.progressbar = ttk.Progressbar(self, orient='horizontal',
length=300,
maximum=100.0,
variable=self.scaleVal)
self.scaleVal.set(0.0)
self.startBtn = tk.Button(self, text="Start", command=self.spawnthread)
self.stopBtn=tk.Button(self,text="Stop", command=self.stopthread)
self.stopBtn.config(state="disabled")
self.msgBtn = tk.Button(self,text="Set Msg", command=self.sendMessage)
self.msgTxt=tk.StringVar(self,"Messages Here...")
self.msgBox=tk.Message(self,textvariable=self.msgTxt,width=200,
anchor=NW,relief=GROOVE)
self.msgBox.grid(row=0,column=0,columnspan=3)
self.progressbar.grid(row=1,column=0,columnspan=3)
self.startBtn.grid(row=2,column=0)
self.stopBtn.grid(row=2,column=1)
self.msgBtn.grid(row=2,column=2)
def on_doneSignal_set(self,*kwargs):
self.sendMessage("Thread is DONE")
self.startBtn.config(state="active")
self.stopBtn.config(state="disabled")
def stopthread(self):
if self.thread.is_alive():
self.thread.stopNow()
def spawnthread(self):
self.thrdCt=0
self.startBtn.config(state="disabled")
self.stopBtn.config(state="active")
self.thread = ThreadedClient(self.msgTxt,self.scaleVal,self.doneSignal)
self.thread.start()
# self.periodiccall()
def sendMessage(self,msg=None):
if not msg==None:
self.msgTxt.set(msg)
else:
self.msgTxt.set("Message {}".format(self.msgCt))
self.msgCt+=1
class ThreadedClient(threading.Thread):
def __init__(self, mtxt,dvar,dsig):
threading.Thread.__init__(self)
self.msgTxt=mtxt
self.scaleVal=dvar
self._stopNow=False
self._doneSignal=dsig
self._lock=threading.Lock()
def run(self):
self._stopNow=False
self.scaleVal.set(0.0)
for x in range(1, 10):
if not self.checkStopNow():
time.sleep(2)
msg = "Function %s finished..." % x
self.msgTxt.set(msg)
self.scaleVal.set(x*10)
else:
break
self._doneSignal.set(True)
def stopNow(self):
with self._lock:
self._stopNow=True
def checkStopNow(self):
rtrn=False
with self._lock:
rtrn=self._stopNow
return rtrn
if __name__ == "__main__":
app = App()
app.mainloop()
First, the motivation for this exercise in the first place: I have a large python application that uses Scipy.optimize to find a solution to a modeling problem. This can often take a long time, so I wanted a way to have it run, but post messages to the user periodically to let them know things are happening, allow user to abort in the middle, and finally to post a message to the main thread that the modeling is now done. My original code was partly based on a threading example that assumed the producer/consumer model of threading, whereby a producer creates data (put into a Queue) and the consumer consumes it. This is the WRONG model for my problem, so this new code has no Queue. It just simulates a long modeling process using the run() method, in which there are calls to sleep() which could obviously be replaced by steps in the SciPy.minimize function calls.
This new example uses DoubleVar to allow the thread to update a progressBar (thanks to stovfl for that suggestion), a StringVar to update a message box in the main thread from the modeling thread, and finally a BooleanVar to signal the main thread that things are done. This version has no polling in the main thread. To me, that does not seem a very elegant solution!
How do I know the changes to the DoubleVar, StringVar and BooleanVar get through to the main thread? Only that this program works!! Note that the message box can be updated from either the modeling thread or using a button in the main GUI thread.
Again, comments welcome -- Give me reasons this should NOT work, then tell me why it does given those reasons! Does this violate some basic design of Python, or would there be a situation where this would not work for some reason??
I have a UI that I am wanting to use threading with inside of Maya. The reason for doing this is so I can run Maya.cmds without hanging/freezing the UI while updating the UI with progress bars, etc.
I have read a few examples from StackOverflow but my code is crashing every second time I run it. Examples I have followed are here and here
import maya.cmds as cmds
from PySide2 import QtWidgets, QtCore, QtGui, QtUiTools
import mainWindow #Main window just grabs the Maya main window and returns the object to use as parent.
class Tool(QtWidgets.QMainWindow):
def __init__(self, parent=mainWindow.getMayaMainWindow()):
super(Tool, self).__init__(parent)
UI = "pathToUI/UI.ui"
loader = QtUiTools.QUiLoader()
ui_file = QtCore.QFile(UI)
ui_file.open(QtCore.QFile.ReadOnly)
self.ui = loader.load(ui_file, self)
#Scans all window objects and if one is open with the same name as this tool then close it so we don't have two open.
mainWindow.closeUI("Tool")
###HERE'S WHERE THE THREADING STARTS###
#Create a thread
thread = QtCore.QThread()
#Create worker object
self.worker = Worker()
#Move worker object into thread (This creates an automatic queue if multiples of the same worker are called)
self.worker.moveToThread(thread)
#Connect buttons in the UI to trigger a method inside the worker which should run in a thread
self.ui.first_btn.clicked.connect(self.worker.do_something)
self.ui.second_btn.clicked.connect(self.worker.do_something_else)
self.ui.third_btn.clicked.connect(self.worker.and_so_fourth)
#Start the thread
thread.start()
#Show UI
self.ui.show()
class Worker(QtCore.QObject):
def __init__(self):
super(Worker, self).__init__() #This will immediately crash Maya on tool launch
#super(Worker).__init__() #This works to open the window but still gets an error '# TypeError: super() takes at least 1 argument (0 given)'
def do_something(self):
#Start long code here and update progress bar as needed in a still active UI.
myTool.ui.progressBar.setValue(0)
print "doing something!"
myTool.ui.progressBar.setValue(100)
def do_something_else(self):
#Start long code here and update progress bar as needed in a still active UI.
myTool.ui.progressBar.setValue(0)
print "doing something else!"
myTool.ui.progressBar.setValue(100)
def and_so_fourth(self):
#Start long code here and update progress bar as needed in a still active UI.
myTool.ui.progressBar.setValue(0)
print "and so fourth, all in the new thread in a queue of which method was called first!"
myTool.ui.progressBar.setValue(100)
#A Button inside Maya will import this code and run the 'launch' function to setup the tool
def launch():
global myTool
myTool = Tool()
I'm expecting the UI to stay active (not locked up) and the threads to be running Maya cmds without crashing Maya entirely while updating the UIs progress bars.
Any insight on this would be amazing!
From what I see it has the following errors:
thread is a local variable that is deleted when the constructor is finished executing causing what is executed to be done in the main thread which is not desired, the solution is to extend the life cycle and for this there are several solutions: 1) make class attribute, 2) pass a parent to the cycle of life they are managed by the parent. In this case use the second solution.
You should not modify the GUI from another thread, in your case you have modified the progressBar from another thread, in Qt you must use signals.
You must use the #Slot decorator in the methods that are executed in another thread.
You indicate that you want to modify myTool but you have not declared it, soglobal myTool will not work by making myTool a local variable to be deleted. The solution is to declare myTool:myTool = None
Considering the above, the solution is:
import maya.cmds as cmds
from PySide2 import QtWidgets, QtCore, QtGui, QtUiTools
import mainWindow # Main window just grabs the Maya main window and returns the object to use as parent.
class Tool(QtWidgets.QMainWindow):
def __init__(self, parent=mainWindow.getMayaMainWindow()):
super(Tool, self).__init__(parent)
UI = "pathToUI/UI.ui"
loader = QtUiTools.QUiLoader()
ui_file = QtCore.QFile(UI)
ui_file.open(QtCore.QFile.ReadOnly)
self.ui = loader.load(ui_file, self)
# Scans all window objects and if one is open with the same name as this tool then close it so we don't have two open.
mainWindow.closeUI("Tool")
# Create a thread
thread = QtCore.QThread(self)
# Create worker object
self.worker = Worker()
# Move worker object into thread (This creates an automatic queue if multiples of the same worker are called)
self.worker.moveToThread(thread)
# Connect buttons in the UI to trigger a method inside the worker which should run in a thread
self.ui.first_btn.clicked.connect(self.worker.do_something)
self.ui.second_btn.clicked.connect(self.worker.do_something_else)
self.ui.third_btn.clicked.connect(self.worker.and_so_fourth)
self.worker.valueChanged.connect(self.ui.progressBar.setValue)
# Start the thread
thread.start()
# Show UI
self.ui.show()
class Worker(QtCore.QObject):
valueChanged = QtCore.Signal(int)
#QtCore.Slot()
def do_something(self):
# Start long code here and update progress bar as needed in a still active UI.
self.valueChanged.emit(0)
print "doing something!"
self.valueChanged.emit(100)
#QtCore.Slot()
def do_something_else(self):
# Start long code here and update progress bar as needed in a still active UI.
self.valueChanged.emit(0)
print "doing something else!"
self.valueChanged.emit(100)
#QtCore.Slot()
def and_so_fourth(self):
# Start long code here and update progress bar as needed in a still active UI.
self.valueChanged.emit(0)
print "and so fourth, all in the new thread in a queue of which method was called first!"
self.valueChanged.emit(100)
myTool = None
def launch():
global myTool
myTool = Tool()
Is it possible to get Python to launch a PyQt5 GUI application using the main thread of execution, and then leave the thread open to do other things?
Here is the simplest example I can think of:
from PyQt5.QtWidgets import *
def infinite_useless_loop():
while True:
pass
app = QApplication([])
doodad = QMainWindow()
doodad.show()
infinite_useless_loop()
If you run this code, it freezes because the 'mainloop' is not activated as it normally would be if I didn't make a call to the useless infinite loop, and instead put a call to app.exec_(). The call to infinite_useless_loop is meant to substitute the main thread being used to do other useful work WHILE the GUI is running correctly.
To do this correctly, I'd have to imagine one would make a separate thread and use that to run the GUI, while launching that thread with the main thread, and just continuing on from there; able to communicate if necessary in the future.
EDIT
I wrote some code that gets the main event loop working in a seperate thread, but I am still not able to fully interact with the GUI object that is created in another thread. This code effectively solves half of my problem:
from PyQt5.QtWidgets import *
from threading import Thread
import sys
def makeGUI():
app = QApplication([])
doodad = QMainWindow()
doodad.show()
sys.exit(app.exec_())
def infinite_useless_loop():
while True:
pass
if __name__ == '__main__':
thread = Thread(target=makeGUI)
thread.start()
infinite_useless_loop()
This code spawns the blank window, able to be clicked on and resized correctly (because the event loop is working), but is on its own. Do I have to revert to signals and slots to communicate with the object, or can I somehow get the GUI object back into the main thread and use it's methods from there?
EDIT 2
I do not wish to do any actual GUI manipulation outside of the GUI's thread, just call methods on the GUI object that I HAVE MADE. The entire GUI structure would be made by the GUI object.
EDIT 3
This new code now makes it able to be communicated with, but only with raw bits of information, and not by one thread accessing another thread's GUI object's methods. This is close, but its still not what I want. Calling the GUI object's methods would have to be done by passing the raw information through the queue, and then being processed at the other side. Then an exec() function would have to be called. That is not acceptable. Here is the code:
from PyQt5.QtWidgets import *
import multiprocessing
import threading
import sys
import time
import queue
class Application(QMainWindow):
def __init__(self, comms):
super(Application, self).__init__()
self.comms = comms
self.fetchingThread = threading.Thread(target=self.fetchingLoop)
self.labelOne = QLabel(self)
self.layout = QVBoxLayout()
self.layout.addWidget(self.labelOne)
self.setLayout(self.layout)
self.fetchingThread.start()
def fetchingLoop(self):
while True:
try:
obj = self.comms.get()
self.processItem(obj)
except queue.Empty:
pass
def processItem(self, item):
self.labelOne.setText(str(item))
print(self.labelOne.text())
class Launcher(multiprocessing.Process):
def __init__(self, Application):
super(Launcher, self).__init__()
self.comms = multiprocessing.Queue()
self.Application = Application
def get_comms(self):
return self.comms
def run(self):
app = QApplication([])
window = self.Application(self.comms)
window.show()
sys.exit(app.exec_())
def no_thread():
app = QApplication([])
window = Application(False)
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
thread = Launcher(Application)
comms = thread.get_comms()
thread.start()
c = 0
while True:
c += 1
time.sleep(1)
comms.put(c)
I am not an experienced programmer. This is probably a simple problem to solve.
I have a function that is supposed to run every two minutes. This function is inside a simple wxPython system tray program. The problem is that I do not know how to run the function because wxPython never leave .MainLoop(). Where should I put the function?
Here is the code: (I have left out the function and import because it is not relevant.)
TRAY_TOOLTIP = 'System Tray Demo'
TRAY_ICON = 'star.png'
def create_menu_item(menu, label, func):
item = wx.MenuItem(menu, -1, label)
menu.Bind(wx.EVT_MENU, func, id=item.GetId())
menu.AppendItem(item)
return item
class TaskBarIcon(wx.TaskBarIcon):
def __init__(self):
super(TaskBarIcon, self).__init__()
self.set_icon(TRAY_ICON)
self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)
def CreatePopupMenu(self):
menu = wx.Menu()
create_menu_item(menu, 'Say Hello', self.on_hello)
menu.AppendSeparator()
create_menu_item(menu, 'Exit', self.on_exit)
return menu
def set_icon(self, path):
icon = wx.IconFromBitmap(wx.Bitmap(path))
self.SetIcon(icon, TRAY_TOOLTIP)
def on_left_down(self, event):
print 'Tray icon was left-clicked.'
MailCheck()
def on_hello(self, event):
print 'Hello, world!'
def on_exit(self, event):
wx.CallAfter(self.Destroy)
def main():
app = wx.PySimpleApp()
TaskBarIcon()
app.MainLoop()
#This is my function I want to run
#But MainLoop() never ends. Where should I put MainCheck() ?
MailCheck()
if __name__=='__main__':
main()
wxPython, as with most GUI frameworks, uses an event-driven programming model. That means that bits of your program are run in response to actions that may have originated from the user, (such as a key press, a menu selection, etc.) the system or perhaps from some other program. The rest of the time it sits in MainLoop waiting for one of those things to happen.
For situations like yours, there is the wx.Timer class which can trigger an event once or perhaps periodically after N milliseconds. If you bind an event handler for the timer event, then that handler will be called when the timer expires.
I've never used wxPython but you could use the threading-module of Python's standard library.
A minimal example:
import threading
def work():
threading.Timer(0.25, work).start()
print "stackoverflow"
work()
Look at this thread (example is from there): Periodically execute function in thread in real time, every N seconds
In this program I get an error when I use a while True loop in the thread. Without the loop I get no error. Of course in the real program I don't update a label continuously. Any idea what I'm doing wrong?
This is the program:
import wx
import thread
class Example(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self,parent)
self.InitUI()
def InitUI(self):
self.SetSize((250, 200))
self.Show(True)
self.text = wx.StaticText(self, label='',pos=(20,30))
thread.start_new_thread(self.watch,(self,None))
def watch(self,dummy,e):
while True:
self.text.SetLabel('Closed')
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
And this is the error:
Pango:ERROR:/build/pango1.0-LVHqeM/pango1.0-1.30.0/./pango/pango- layout.c:3801:pango_layout_check_lines: assertion failed: (!layout->log_attrs) Aborted
Any suggestions as to what I'm doing wrong? I'm (obviously) new to threading.
I am not exactly sure if that is what causes you problem, but... You should not interact with the GUI from another thread. You should use wx.CallAfter(). I would consider adding sleep inside the loop also.
wx.CallAfter() documentation says:
Call the specified function after the current and pending event handlers have been completed. This is also good for making GUI method calls from non-GUI threads. Any extra positional or keyword args are passed on to the callable when it is called.
Updated code would than be:
import wx
import thread
import time
class Example(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self,parent)
self.InitUI()
def InitUI(self):
self.SetSize((250, 200))
self.Show(True)
self.text = wx.StaticText(self, label='',pos=(20,30))
thread.start_new_thread(self.watch,(self,None))
def watch(self,dummy,e):
while True:
time.sleep(0.1)
wx.CallAfter(self.text.SetLabel, 'Closed')
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
Maybe you can also consider using wx.Timer.
BTW: Your code runs OK on my PC with Windows 7 and wxPython 2.8.
In addition to the no updates from background threads rule, I've found that in similar situations (high frequency update of UI objects) that it really helps to only update the value if it has changed from what is already displayed. That can greatly reduce the load on the application because if the value does not change then there will be no need for sending and processing paint events, moving pixels to the screen, etc. So in this example I would add a new method that is called via CallAfter that compares the current value in the widget with the requested value, and only calls SetLabel if they are different.