Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get textinput value in Kivy app

Tags:

python

kivy

New to Python/Kivy trying to build a test app with an input box, an ok button and a label that should change text when the ok button is clicked. But instead I get 'NameError: global name 'txt1' is not defined'. What am I doing wrong?

# import Kivy
import kivy
import random

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput

# my app
class MyApp(App):
# layout
    def build(self):
        layout = BoxLayout(padding=10, orientation='vertical')
        btn1 = Button(text="OK")
        btn1.bind(on_press=self.buttonClicked)
        layout.add_widget(btn1)
        lbl1 = Label(text="test")
        layout.add_widget(lbl1)
        txt1 = TextInput(text='', multiline=False)
        layout.add_widget(txt1)
        return layout

# button click function
    def buttonClicked(self,btn):
        lbl1.text = "You wrote " + txt1.text

# run app
if __name__ == "__main__":
    MyApp().run()
like image 480
Fred Avatar asked Oct 11 '14 12:10

Fred


People also ask

What is KIVY TextInput?

The TextInput widget provides a box for editable plain text. Unicode, multiline, cursor navigation, selection and clipboard features are supported. The TextInput uses two different coordinate systems: (x, y) - coordinates in pixels, mostly used for rendering on screen.

What is KIVY and KivyMD?

KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI.


1 Answers

Use self.txt1, self.lbl1 etc..

class MyApp(App):
# layout
    def build(self):
        layout = BoxLayout(padding=10, orientation='vertical')
        btn1 = Button(text="OK")
        btn1.bind(on_press=self.buttonClicked)
        layout.add_widget(btn1)
        self.lbl1 = Label(text="test")
        layout.add_widget(self.lbl1)
        self.txt1 = TextInput(text='', multiline=False)
        layout.add_widget(self.txt1)
        return layout

# button click function
    def buttonClicked(self,btn):
        self.lbl1.text = "You wrote " + self.txt1.text

# run app
if __name__ == "__main__":
    MyApp().run()
 # join all items in a list into 1 big string

Using:

def buttonClicked(self,btn):
        lbl1.text = "You wrote " + txt1.text <- only exists in the build method
like image 169
Padraic Cunningham Avatar answered Sep 28 '22 03:09

Padraic Cunningham