How to get input box content in kivy application

Viewed 27

I'm writing a kivy app that lets the user enter and store content, but I've searched the web and can't find a solution

This is the python program

from kivy.app import App
from kivy.graphics import Line, Color
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.config import Config
Config.set('graphics', 'resizable', False)
from kivy.core.window import Window
Window.size = (450, 800)

class DrawCanvasWidget(Widget):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

class PaintApp(App):
    def build(self):
        self.draw_canvas_widget = DrawCanvasWidget()
    
        return self.draw_canvas_widget  # 返回root控件

if __name__ == "__main__":
    PaintApp().run()

This is the kv program

<DrawCanvasWidget>
orientation: "vertical"
canvas.before:
    Color:
        rgba: [1,1,1,1]
    Rectangle:  
        pos: self.pos
        size: self.size
TextInput:
    multiline:False
    font_size:20
    pos:75,450
    size:300,40
    allow_copy:False
    cursor_color:[0,1,0,1]
Button:
    text:'ok'
    bold:10
    size_hint:None,None
    size:100,50
    pos:180,380

I want to let the user save the content of the input box after pressing the button

1 Answers

This is the basic idea. Create a function in the draw canvas widget and pass the text of the text input by using the id tag.

<DrawCanvasWidget>
      orientation: "vertical"
          canvas.before:
              Color:
                  rgba: [1,1,1,1]
              Rectangle:  
                  pos: self.pos
                  size: self.size
          TextInput:
              id: text_input                
              multiline:False
              font_size:20
              pos:75,450
              size:300,40
              allow_copy:False
              cursor_color:[0,1,0,1]
          Button:
              text:'ok'
              bold:10
              size_hint:None,None
              size:100,50
              pos:180,380
              on_release: root.submit(text_input.text)   


class DrawCanvasWidget(Widget):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

    def submit(self, text_input):
        print(text_input)
        # Should print whatever is in the textinput to the terminal
        # Here you can save it to your database or do anything with the input.

Related