In this Python Kivy article we want to learn How to Create TextInput with Python and Kivy, if you want to build a user interface for Python application, Kivy is a great choice. Kivy is an open source Python framework that allows you to create multi touch user interfaces. one of the common UI element in kivy is TextInput which allows users to add text. in this article i want to show you how to create TextInput with Kivy.
How to Create TextInput with Python and Kivy
First of all we need to install Python Kivy and you can use pip for that.
1 |
pip install kivy |
After installation we need to import the required modules
1 2 |
from kivy.app import App from kivy.uix.textinput import TextInput |
After that we need to define TextInput class. this is the place that we want to set properties of the input field such as its size, position and text color.
1 2 3 4 5 6 7 |
class MyTextInput(TextInput): def __init__(self, **kwargs): super(MyTextInput, self).__init__(**kwargs) self.size_hint = (.5, .2) self.pos_hint = {'center_x': .5, 'center_y': .5} self.foreground_color = (1, 1, 1, 1) |
In the above example we have defined a class called MyTextInput that extends from TextInput class. we have also set size_hint property to .5, .2 which means the input field will take up 50% of available width and 20% of the available height. pos_hint property sets position of the input field in the center of the screen, and foreground_color property sets color of the text to white.
Now let’s create our Kivy application. this is done by defining a new class that extends from the App class, in this example, we have defined a class called MyApp that extends from the App class. we have also defined build method that returns an instance of the MyTextInput class.
1 2 3 |
class MyApp(App): def build(self): return MyTextInput() |
And lastly we just need to run the application. this can be done by creating an instance of the MyApp class and calling its run method.
1 2 |
if __name__ == '__main__': MyApp().run() |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from kivy.app import App from kivy.uix.textinput import TextInput class MyTextInput(TextInput): def __init__(self, **kwargs): super(MyTextInput, self).__init__(**kwargs) self.size_hint = (.5, .2) self.pos_hint = {'center_x': .5, 'center_y': .5} self.foreground_color = (1, 0, 1, 1) class MyApp(App): def build(self): return MyTextInput() if __name__ == '__main__': MyApp().run() |
If you run the code this will be the result
