如何在按Enter键后立即将Kivy输入文本分配给变量? [英] How to Assign the Kivy Input Text to a variable immediately on pressing Enter?

查看:67
本文介绍了如何在按Enter键后立即将Kivy输入文本分配给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为个人助理创建用户界面.
我希望用户输入文本,当他按Enter时,我想做点什么(说打印文本")并自动清除输入字段. 这是我的代码:

I'm trying to create a user-interface for a personal assistant.
I want the user to input a text and when he presses enter,i want to do something(' say print a text') and also automatically clear the input field. This is my code:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
class TetraApp(App):

    def build(self):
        Window.size=(875,600)
        Window.clearcolor = (0, 1, 1, 1)
        b = BoxLayout(orientation ='vertical')
        self.t = TextInput(hint_text='Say Something...', size_hint=(1,0.1), multiline=False)
#the multiline disables on enter. i want it to do a process on enter.
        b.add_widget(self.t)
        # code here to go to enterClicked() when enter is pressed and to clear input field
        Window.borderless=True
        return b
    def enterClicked(self):
        if 'hello' in self.t.text:
            print("hello user")
if __name__=='__main__':
    app=TetraApp()
    app.run()

我找不到与此有关的任何教程.

I couldnt find any tutorials for this.

推荐答案

您可以尝试将操作绑定到TextInput上,如下所示:

You can try to bind an action to your TextInput like this:

self.t = TextInput(hint_text='Say Something...', size_hint=(1,0.1),multiline=False)
self.t.bind(on_text_validate=self.enterClicked)
b.add_widget(self.t)
def enterClicked(self,t):
    if 'hello' in self.t.text:
        print("hello user")
    self.t.text=''

当用户点击"enter"时,仅在multiline = False模式下触发on_text_validate操作.

The on_text_validate action is triggered only in multiline=False mode when the user hits ‘enter’.

要清除输入字段,请尝试创建一种清除文本的方法(类似于您的enterClicked),并将此方法也绑定到具有on_text_validate的TextInput.让我知道它是否有效.

To clear the input field, try to make a method that clears the text (similar to your enterClicked) and bind this method as well to the TextInput with on_text_validate. Let me know if it worked.

这篇关于如何在按Enter键后立即将Kivy输入文本分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆