我们如何根据订阅主题消息的变化动态更改Tkinter标签小部件中的文本?

时间:2016-05-11 15:34:27

标签: python tkinter label ros

我想根据节点订阅的主题消息更改标签的文本。但问题是标签中的文本没有随主题消息的变化而变化。我的部分代码如下:(我使用代码动态更改标签中的文本https://bytes.com/topic/python/answers/629499-dynamically-displaying-time-using-tkinter-label

v = StringVar()
v.set(distance)
self.clock = Label(frame, font=('times', 20, 'bold'), bg='green', textvariable = v)
self.clock.pack(fill=BOTH, expand=1)
rate = rospy.Rate(2)

while not rospy.is_shutdown():
    rospy.Subscriber("distance", Float32, self.callback)
    v.set(distance)
    print("distance = %f", distance)
    frame.update_idletasks()
    rate.sleep()

1 个答案:

答案 0 :(得分:1)

嗯,你的代码(或者至少你发布的部分)似乎是一个混乱的代码。

ROS谈话,

  • define your subscriber in the initialization of the node(不在里面 while循环,将创建多个订阅者!)
  • create a callback to get the messages在该主题下交换了阅读消息
  • update your label相应的。

话虽如此,这里是代码应如何显示的示例:(填空)

#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32

def callback(data):
    distance = data.data
    rospy.loginfo(rospy.get_caller_id() + "distance = ", distance )
    #here update your label, I assume the following (maybe not correct)
    v = StringVar()
    v.set(distance)
    self.clock = Label(frame, font=('times', 20, 'bold'), bg='green', textvariable = v)
    self.clock.pack(fill=BOTH, expand=1)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("distance", Float32, self.callback)  
    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()


if __name__ == '__main__':
    listener()