Ask Your Question
1

rospy and Tkinter - spin() and mainloop()

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

ounsworth gravatar image

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

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 -0600

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

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 imageounsworth ( 2013-12-04 08:33:30 -0600 )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

2 followers

Stats

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

Seen: 4,512 times

Last updated: Dec 04 '13