本人是小白,根据高手的代码修改,在这里记录下来备查!不足之处请高手指导。
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.properties import ListProperty, StringProperty
from kivy.lang import Builder
Builder.load_string('''
<MainView>:
ComboEdit:
size_hint: .5, .3
pos_hint: {'center':(.5, .5)}
# `args` is the keyword for arguments passed to `on_text` in kv language
on_text: root.on_text(self, args[1])
''')
class ComboEdit(TextInput):
'''
This class defines a Editable Combo-Box in the traditional sense
that shows it's options
'''
options = ListProperty(('', ))
'''
:data:`options` defines the list of options that will be displayed when
touch is released from this widget.
'''
def __init__(self, **kw):
ddn = self.drop_down = DropDown()
ddn.bind(on_select=self.on_select)
super(ComboEdit, self).__init__(**kw)
def on_options(self, instance, value):
ddn = self.drop_down
# clear old options
ddn.clear_widgets()
for option in value:
# create a button for each option
but = Button(text=option,
size_hint_y=None,
height='36sp',
# and make sure the press of the button calls select
# will results in calling `self.on_select`
on_release=lambda btn: ddn.select(btn.text))
ddn.add_widget(but)
def on_select(self, instance, value):
# on selection of Drop down Item... do what you want here
# update text of selection to the edit box
print(value)
self.text = value
class MainView(FloatLayout):
rtsstr = ['ab','456','dfh','kfjd','rteop','frewr','rerew']
def on_text(self,instance, value):
if value == '':
instance.options=[]
else:
tmp = []
for v in self.rtsstr:
if value in v:
tmp.append(v)
instance.options = list(set(tmp))
try:
instance.drop_down.open(instance)
except:
print('找不到')
class TestApp(App):
def build(self):
return MainView()
if __name__ == '__main__':
TestApp().run()
不足之处:
try:
instance.drop_down.open(instance)
except:
print('找不到')
instance.drop_down.open(instance)这段代码老是提示已经有父级,导致不能运行,所以加了个try,请高手指导一下!