Ask Your Question

rospy and Tkinter - spin() and mainloop()

asked 2013-12-03 14:47:43 -0500

ounsworth gravatar image

updated 2014-01-28 17:18:43 -0500

ngrennan gravatar image

I want to write a rospy node that uses Python's GUI toolkit Tkinter, problem is that rospy.spin() and top.mainloop() are both blocking calls.

I thought of starting one and setting an interrupt to start the other, like:

top.after(50, rospy.spin )

This successfully starts both loops, but once rospy.spin() starts it completely takes control from Tkinter (until I hit ctrl+c, then Tkinter resumes). What I really want is a rospy.spinOnce() that I can call on Tkinter's repaint cycle, but I gather there isn't such a thing.

Is there a good way to have both top.mainloop() and rospy.spin() running in the same thread? Or at least a work-a-round?

Edit: I found a work-a-round by forking rospy.spin() into it's own thread and protecting all my variables inside the ros callbacks with mutexes like so:

from threading import Thread, Lock

mutex = Lock()

def rosClbk(data) :
    _var = var
    # do processing on _var

def main() :
    t = Thread(target = rospy.spin )

This makes the program a bit hard to kill (since ros no longer responds to ctrl+c), but otherwise seems to work fine. Is this too dirty? Is there a better way?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2013-12-04 08:08:59 -0500

updated 2013-12-04 08:11:54 -0500

If there is another blocking call that keeps your program running, there is no need to call rospy.spin(). Unlike in C++ where spin() is needed to process all the threads, in python all it does is block.

Edit: Here's a Python/Tk node I wrote a while ago that might help:

edit flag offensive delete link more


Amazing, that works. Thanks.

ounsworth gravatar image ounsworth  ( 2013-12-04 08:33:30 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2013-12-03 14:47:43 -0500

Seen: 5,671 times

Last updated: Dec 04 '13