ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
1

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 )
top.mainloop()

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) :
    mutex.aquire()
    _var = var
    mutex.release()
    # do processing on _var

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

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
1

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: https://code.google.com/p/wu-robotics/source/browse/trunk/missouri/missouri_telepresence/demogui.py

edit flag offensive delete link more

Comments

Amazing, that works. Thanks.

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

Can you please explain what you did instead? I can't manage to put Subscriber node on loop while using GUI.

Issey M gravatar image Issey M  ( 2022-09-19 22:32:34 -0500 )edit

Question Tools

2 followers

Stats

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

Seen: 6,819 times

Last updated: Dec 04 '13