在 Kivy 中使用按钮释放清除 inputText

Clearing inputText with a button release in Kivy

假设我们有一个表单,用户在输入中写了一些东西但需要将它们全部清除,我在 Kivy 中该怎么做?

我试过了,但没用:

main.py:

class CreateUra(GridLayout):

    def clear_inputs(self, *args):
            for item in args:
                item = ''


class UraApp(App):

    def build(self):
        return CreateUra()

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

Ura.kv:

<CreateUra>:
    cols: 1
    padding: 10
    spacing: 10
    row_force_default: True
    row_default_height: '32dp'

      BoxLayout:
            Label: 
                text: 'Contexto:'
                TextInput: 
                hint_text: "Contexto da ura"
                focus: True
                multiline: False
                cursor_color: (0, 0, 0, 0.8)
                id: context_input

        BoxLayout:
            Label: 
                text: 'Nome da ura:'
                TextInput: 
                hint_text: "Nome do arquivo da ura"
                multiline: False
                cursor_color: (0, 0, 0, 0.8)
                id: ura_file_name

        Button:
            text: 'Create Ura'
            id: bt_create
            on_press: root.uraConfig()
            on_release: root.clear_inputs(context_input.text, ura_file_name.text)

*忽略 on_press

上的 uraConfig

我试过这种方法并且有效:

Button:
    text: 'Create Ura'
    id: bt_create
    on_press: root.uraConfig()
    on_release: context_input.text = ''

我对 kivy 和 Python 很陌生,所以我不确定这是否是清除文本的最佳方法,但我做错了什么?或者,如果你们可以提供一些最好的方法。

你的问题是传递文本,而不是文本 属性 而是文本的副本,所以即使你将它设置为空也不会反映在文本输入中。您必须将文本输入作为列表传递,迭代并使用空字符串设置 属性:

*.kv

Button:
    text: 'Create Ura'
    id: bt_create
    on_press: root.uraConfig()
    on_release: root.clear_inputs([context_input, ura_file_name]) # <-- add brackets

*.py

class CreateUra(GridLayout):
    def clear_inputs(self, text_inputs):
        for text_input in text_inputs:
            text_input.text = ""