Learning Kivy: Clipboard and Text Input

Hey everyone!

It's time for another cool Kivy tutorial. In this one I will explain how to use the Clipboard core module to copy text from a Text Input widget. The text thus copied will be applied to a Button, displayed in our layout.

Kivy provides a core class for accessing the Clipboard. It is used mainly to copy some data so that it can be used somewhere else. On the other hand, the Text Input widget provides a box of editable plain text. At present it supports unicode, multi line, cursor navigation, selection and clipboard features.

Usage of Clipboard:

>>> from kivy.core.clipboard import Clipboard
>>> Clipboard.get_types()
'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8',
>>> Clipboard.get('TEXT')
'Hello World'
>>> Clipboard.put('Great', 'UTF8_STRING')
>>> Clipboard.get_types()
>>> Clipboard.get('UTF8_STRING')

Usage of Text Input:

To create a multiline textinput (‘enter’ key adds a new line):

from kivy.uix.textinput import TextInput
textinput = TextInput(text='Hello world')

The textinput’s text is stored on its TextInput.text property. To run a callback when the text changes:

def on_text(instance, value):
    print('The widget', instance, 'have:', value)

textinput = TextInput()

Now, let's write a small program that will dynamically copy the value from the Text Input widget and apply it as text to a Button using the Kivy Clipboard!

Open Python IDLE and create a new Python script named clipboard.py


from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.core.clipboard import Clipboard
from kivy.uix.button import Button

button = Button(pos=(300,300),font_size=20)
textinput= TextInput(text='Hello world',multiline=False)
def on_text(self, *args):
        print ('new value is ', textinput.text)
        button.text= Clipboard.get('UTF8_STRING')
class MyClipBoardApp(App):
    def build(self):
        root= GridLayout()
        layout = FloatLayout(orientation='horizontal', size=(450,300), size_hint=(None, None))
        #call function when text changes inside TextInput
        print ('value is ', textinput.text)
        print Clipboard.put(textinput.text,'UTF8_STRING')
        print Clipboard.get('UTF8_STRING')
        #Use copied clipboard value as text for Button
        button.text= Clipboard.get('UTF8_STRING')
        return root
if __name__ == '__main__':

Run the above code by typing kivy clipboard.py inside command prompt. You should see the following output!

Before text changed


After text changed