简体   繁体   中英

Using ROS message and python to update text input field in kivy GUI

I try to design a GUI to handle stepper motors via ROS, kivy and python. You can find a minimal version of the GUI below. Actually I want to use a ROS message to update a kivy text input field (read only). In the minimal example, pressing the button should transfer the data of the first input field over a local ROS node to the second input field. Actually it seems, that the Callback within the rospy.Subscriber() doesn't enter the Test class.

Thank You for any suggestions!

main.py

import kivy
kivy.require('1.7.2')

import rospy
from std_msgs.msg import String

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout

class Test(BoxLayout):
    text_is = 'text before button press'

    def Pub(self):
        publish = self.ids.test_text_pub.text
        try:
            ROSNode.new_text_is.publish(publish)
        except rospy.ROSInterruptException: pass

class ROSNode(Widget):

    def Callback(publish):
        print(publish.data) #check if Callback has been called
        test.text_is = publish.data

    new_text_is = rospy.Publisher('new_text_is', String, queue_size=10)
    rospy.Subscriber('new_text_is', String, Callback)

    rospy.init_node('talker', anonymous=True)

class TestApp(App):

    def build(self):
        return Test()

if __name__ == '__main__':
    TestApp().run()

test.kv

#:kivy 1.0

<Test>:
    BoxLayout:
        orientation: 'vertical'

        Button:
            id: test_button
            text: 'publish'
            on_press: root.Pub()

        TextInput:
            id: test_text_pub
            text: 'text after button press'

        TextInput:
            id: test_text_sub
            text: root.text_is

If you want your text to automatically update, you need to use Kivy properties .

from kivy.properties import StringProperty
class Test(BoxLayout):
    text_is = StringProperty('text before button press')

Kivy properties support data binding, so any updates to the property will propagate through to any bound widget. Binding happens automatically in kv, so when you do this:

text: root.text_is

..you're telling Kivy that when root.text_is is updated, update my text also.

So I found the solution:

I had to add an on_release event to the button.

on_release: test_text_sub.text = root.text_is

那么最终的代码是什么?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM