一些GUI工具箱包含事件,例如,on_change每次文本框中的文本更改时都会触发这些事件。
根据这样的:
https://kivy.org/docs/api-kivy.uix.textinput.html的on_text事件应该是平等的。因此,我创建了一个TextInput框,期望每次更改一个字母时,该框的内容就会显示在终端中。这是代码:
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
class LoginScreen(BoxLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.orientation = 'horizontal'
self.mytext = TextInput(text='500', multiline = False)
self.add_widget(self.mytext)
self.mytext.bind(on_text = self.calc)
#self.mytext.bind(on_text_validate = self.calc)
def calc(self, mytext):
print mytext.text
class MyApp(App):
def build(self):
return LoginScreen()
if __name__ == '__main__':
MyApp().run()
Run Code Online (Sandbox Code Playgroud)
但是,什么也没有发生,这显然意味着该calc功能根本没有被触发。请注意,该on_text_validate事件运行正常,因为当我按Enter键时,该框的内容已打印在终端中。
那么,我是否误解了on_text活动,如果是,我该如何实现自己的目标?
on_text不是TextInput事件。要在文本更改时运行回调,可以绑定text属性(存储textinput的文本的位置):
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
class LoginScreen(BoxLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.orientation = 'horizontal'
self.mytext = TextInput(text='500', multiline = False)
self.add_widget(self.mytext)
self.mytext.bind(text = self.calc)
def calc(self, instance, text):
print(text)
class MyApp(App):
def build(self):
return LoginScreen()
if __name__ == '__main__':
MyApp().run()
Run Code Online (Sandbox Code Playgroud)
您可以使用on_<property_name>sintax 创建在属性更改时自动调用的回调 :
Kivy Languaje:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''\
<LoginScreen>:
orientation: "horizontal"
TextInput:
text: "500"
on_text: root.calc(self.text)
''')
class LoginScreen(BoxLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
def calc(self, text):
print(text)
class MyApp(App):
def build(self):
return LoginScreen()
if __name__ == '__main__':
MyApp().run()
Run Code Online (Sandbox Code Playgroud)扩展小部件类:
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
class My_TextInput(TextInput):
def __init__(self, **kwargs):
super(My_TextInput, self).__init__(**kwargs)
def on_text(self, instance, text):
print(text)
class LoginScreen(BoxLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.mytext = My_TextInput(text='500', multiline = False)
self.add_widget(self.mytext)
class MyApp(App):
def build(self):
return LoginScreen()
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
2210 次 |
| 最近记录: |