我想根据节点订阅的主题消息更改标签的文本。但问题是标签中的文本没有随主题消息的变化而变化。我的部分代码如下:(我使用代码动态更改标签中的文本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()
答案 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()