本文整理汇总了Python中kivy.uix.dropdown.DropDown.clear_widgets方法的典型用法代码示例。如果您正苦于以下问题:Python DropDown.clear_widgets方法的具体用法?Python DropDown.clear_widgets怎么用?Python DropDown.clear_widgets使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kivy.uix.dropdown.DropDown
的用法示例。
在下文中一共展示了DropDown.clear_widgets方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: NoteItem
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class NoteItem(BoxLayout):
def __init__(self, **kwargs):
super(NoteItem, self).__init__(**kwargs)
self.dropdown = DropDown()
def addNoteItem(self, w):
"""
inventoryitem = Inventarios()
inventoryitem.Clave = w.parent.txt_clave.text
inventoryitem.Producto = w.parent.txt_producto.text
inventoryitem.Existencias = w.parent.txt_existencias.text
inventoryitem.Minimo = w.parent.txt_minimo.text
inventoryitem.Maximo = w.parent.txt_maximo.text
inventoryitem.Precio = w.parent.txt_precio.text
inventoryitem.save()
"""
newitem = NoteItem()
w.text = "X"
table = app.root.ventas.lst_note
table.add_widget(newitem, index=len(table.layout.children))
app.root.ventas.txt_total.text = str(float(app.root.ventas.txt_total.text) + float(w.parent.txt_total.text))
def on_completeproduct(self, w):
print w.text
if len(w.text) > 2:
self.dropdown.clear_widgets()
# for item in app.root.inventarios:
for item in app.root.inventarios:
if w.text.upper() in item.Producto.upper():
but = WhiteButton(text=item.Producto, size_hint_y=None, height=40)
but.bind(on_press=self.fillProduct)
but.Item = item
self.dropdown.add_widget(but)
self.dropdown.open(w)
def fillProduct(self, w):
self.txt_producto.text = w.text
self.txt_precio.text = w.Item.Precio
if self.txt_cant.text != "":
self.txt_total.text = str(float(self.txt_cant.text) * float(self.txt_precio.text))
self.dropdown.dismiss()
示例2: ChoicePopup
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class ChoicePopup(Popup):
"""
Popup form for view schedule for group, teacher or room
"""
btn_text = StringProperty()
choices = ListProperty()
choice_input = ObjectProperty(None)
on_release = ObjectProperty(None)
dropdown = ObjectProperty(None)
def __init__(self, on_release, **kwargs):
self.on_release = on_release
super(ChoicePopup, self).__init__(**kwargs)
self.dropdown = DropDown()
self.choice_input.bind(text=self.make_dropdown, focus=self.on_focus)
self.dropdown.bind(
on_select=lambda instance, x: setattr(self.choice_input, 'text', x)
)
def make_dropdown(self, *args):
self.dropdown.clear_widgets()
for choice in self.choices:
if self.choice_input.text in choice or self.choice_input.text == '':
button = Button(
text=choice,
size_hint_y=None,
height=35
)
button.bind(
on_release=lambda btn: self.dropdown.select(btn.text)
)
self.dropdown.add_widget(button)
else:
pass
self.dropdown.open(self.choice_input)
@staticmethod
def on_focus(instance, value):
if value:
instance.text = ''
示例3: CompleteTextInput
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class CompleteTextInput(TextInput):
options = ListProperty([])
dd = ObjectProperty(None)
def __init__(self, **kwargs):
super(CompleteTextInput, self).__init__(**kwargs)
self.dd = DropDown(auto_dismiss=False)
self.dd.bind(on_select=self.setter('text'))
self.bind(text=self.update_complete,
focus=self.update_complete)
def update_complete(self, *args):
if self.focus:
self.dd.clear_widgets()
for x in app.settings.get('settings', 'servers').split(','):
url = x.split(';')[1].strip()
if self.text in url:
b = Factory.DDButton(text=url)
b.bind(on_release=lambda btn: self.dd.select(btn.text))
self.dd.add_widget(b)
self.dd.open(self)
else:
self.dd.dismiss()
示例4: QReader
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class QReader(FloatLayout):
login = ObjectProperty()
def signin(self):
try:
self.user = User.login(self.login.username.text, self.login.password.text)
self.remove_widget(self.login)
self.main = Main()
self.add_widget(self.main)
except:
MessageBoxTime(msg="Bad login").open()
def decoded(self, val):
self.message.text = val
def show_label(self):
labeldata = LabelData()
labelinfo = Warehouses.Query.get(objectId=self.message.text)
print labelinfo, labelinfo.ReceiptDate
for property, value in vars(labelinfo).iteritems():
print property, ": ", value
labeldata.content.add_widget(Label(text=str(property) ) )
labeldata.content.add_widget(Label(text=str(value) ) )
'''
labeldata.receipt.text = str(labelinfo.Receipt)
labeldata.status.text = labelinfo.Status
labeldata.receiptDate.text = str(labelinfo.ReceiptDate)
labeldata.agent.text = labelinfo.Agent
labeldata.shipper.text = labelinfo.Shipper.Name
labeldata.consignee.text = labelinfo.Consignee.Name
'''
labeldata.open()
def on_repack(self):
print "Repack !"
self.repack = Repack()
self.repack.open()
def repack_done(self):
self.repack.dismiss()
#open the repack dialog information
self.repackform = RepackForm()
self.repackform.open()
def repack_save(self):
self.repackform.dismiss()
wh = Warehouses()
wh.Agent = self.repackform.agent.text
#wh.Consignee.Name = self.repackform.consignee.text
wh.Zone = self.repackform.zone.text
wh.Transport = self.repackform.transport.text
wh.Content = self.repackform.contentnotes.text
wh.GeneralNotes = self.repackform.generalnotes.text
wh.InternalNotes = self.repackform.internalnotes.text
wh.save()
def do_clientcomplete(self, w):
print w.text
clients = Clients.Query.all()
#for the autocomplete
if not hasattr(self, "down"):
self.down = DropDown()
self.down.clear_widgets()
for client in clients:
if w.text.lower() in client.Name.lower():
print client.Name
but = Button(text=client.Name, size_hint_y=None, height=44, on_press=self.select_clientresult)
self.down.add_widget(but)
self.down.open(self.repackform.consignee)
def select_clientresult(self, w):
print w.text
示例5: CurrentPlayer
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class CurrentPlayer(BoxLayout):
players = ListProperty()
playername = StringProperty()
playerstatus = StringProperty()
currenttrack = StringProperty()
albumart = ObjectProperty()
def __init__(self, player, **kwargs):
BoxLayout.__init__(self, **kwargs)
self.queue = Queue()
self.activeslider = False
self.dropdown = DropDown()
self.stationdropdown = DropDown()
self.currentplayer = player
self.playerstatus = "Pending ...."
self.playername = self.currentplayer.group.label
self.rendering = self.currentplayer.renderingControl.subscribe(
event_queue=self.queue)
self.info = self.currentplayer.avTransport.subscribe(
event_queue=self.queue)
self.timer = Clock.schedule_interval(self.monitor, 0)
def teardown(self):
Clock.unschedule(self.timer)
if self.rendering:
try:
self.rendering.unsubscribe()
except:
pass
if self.info:
try:
self.info.unsubscribe()
except:
pass
def volumechanged(self, instance, value):
try:
if self.activeslider:
for p in self.currentplayer.group.members:
p.volume = int(value)
except:
pass
def play(self):
if (self.playerstatus == "PLAYING"):
self.currentplayer.pause()
else:
try:
self.currentplayer.play()
except:
pass
def radiostations(self, widget):
self.stationdropdown.clear_widgets()
for station in self.currentplayer.get_favorite_radio_stations()['favorites']: # noqa
btn = Button(text='%s' % (station['title'],),
size_hint_y=None, height=60,
halign="center", valign="middle")
btn.bind(size=btn.setter("text_size"))
btn.bind(on_release=partial(self.playradio, station))
self.stationdropdown.add_widget(btn)
self.stationdropdown.open(widget)
def playradio(self, station, widget):
self.currentplayer.play_uri(uri=station['uri'], #noqa
title=station['title'])
self.stationdropdown.select(station['title'])
def parserenderingevent(self, event):
if event.variables.get('output_fixed') == 1:
self.ids.playervolume.disabled = True
self.ids.playervolume.value = 100
return
else:
self.ids.playervolume.disabled = False
if not self.activeslider:
try:
self.ids.playervolume.value = int(event.volume['Master'])
except:
pass
def parseavevent(self, event):
playerstate = event.transport_state
if playerstate == "TRANSITIONING":
return
self.playerstatus = playerstate
try:
metadata = event.current_track_meta_data
except:
print event.variables
return
# This can happen if the the player becomes part of a group
if metadata == "" and event.enqueued_transport_uri_meta_data == "":
return
#.........这里部分代码省略.........
示例6: LSystemsView
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
#.........这里部分代码省略.........
self.labels_layout.add_widget(Label(text="[b]Number of iterations:[/b]",markup=True))
self.labels_layout.add_widget(self.iterations)
self.labels_layout.add_widget(Label(text="[b]Number of segments:[/b]",markup=True))
self.labels_layout.add_widget(self.segments)
self.main_layout.add_widget(self.image)
self.main_layout.add_widget(self.buttons_layout)
self.main_layout.add_widget(self.labels_layout)
self.file_chooser = LFileChooser()
self.file_chooser.bind(on_choose=self.choose_file)
self.popup = Popup(title='Load L-Systems', content=self.file_chooser,
size_hint=(None, None), size=(500, 500))
self.color_picker=BackgroundColorPicker()
self.color_picker.bind(on_choose=self.change_background_color)
self.color_picker_popup = Popup(title = "Pick color",
content = self.color_picker,
size_hint = (None,None),
size = (500,500))
self.add_widget(self.main_layout)
def choose_background_color(self,*args,**kwargs):
self.color_picker_popup.open()
def change_background_color(self,instance,color):
r,g,b,a = color
r=int(255*r)
g=int(255*g)
b=int(255*b)
self.image.set_background_color((r,g,b))
self.color_picker_popup.dismiss()
def on_edit(self,*args,**kwargs):
pass
def on_file_choose(self,*args):
self.popup.open()
def edit(self,instance,*args):
name=self.ls_name.text
if name: fractal = self.fractals[name][0]
else: fractal = '',{},0
self.dispatch("on_edit",(name,fractal))
def set_fractals(self):
self.fractal_choice.clear_widgets()
for k in sorted(self.fractals.keys()):
btn = Button(text = k,size_hint_y=None, height=44)
btn.bind(on_release = lambda btn: self.fractal_choice.select(btn.text))
self.fractal_choice.add_widget(btn)
def choose_file(self,instance,text):
self.cur_file.text = basename(text)
self.popup.dismiss()
self.fractals=l_parser(open(l_file_path(text)))
self.set_fractals()
self.choose_fractal(None,sorted(self.fractals.keys())[0])
def choose_width(self,instance,text):
self.image.set_width(int(text))
def choose_fractal(self,instance,text):
self.ls_name.text = text
self.image.set_lsystem(self.fractals[text][0])
self.image.set_iterations(1)
self.iterations.text = str(self.image.get_iterations())
def image_update(self,instance,num):
self.segments.text = str(num)
def next(self,*args):
cur_name = self.ls_name.text
if not cur_name: return
lst = self.fractals.keys()
i = lst.index(cur_name)
i+=1
if i==len(self.fractals): i=0
self.choose_fractal(None,lst[i])
def plus(self,*args):
self.image.set_iterations(self.image.get_iterations()+1)
self.iterations.text = str(self.image.get_iterations())
def minus(self,*args):
self.image.set_iterations(self.image.get_iterations()-1)
if self.iterations.text!="0":
self.iterations.text = str(self.image.get_iterations())
示例7: MainScreen
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class MainScreen(ScrollView):
nextReload = None
showall = False
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
Window.bind(on_keyboard=self.Android_back_click)
self.size_hint=(None, None)
self.size=(Window.width, Window.height)
self.pos_hint={'center_x':.5, 'center_y':.5}
self.buildMainScreen()
def Android_back_click(self,window,key,*largs):
if key == 27:
self.buildMainScreen()
return True
def buildMainScreen(self, _=None):
self.clear_widgets()
mainLayout = GridLayout(cols=1, spacing=10, size_hint_y=None)
mainLayout.bind(minimum_height=mainLayout.setter('height'))
self.scroll_y = 1
self.add_widget(mainLayout)
cur.execute("SELECT DISTINCT taskId, endTime FROM Fights WHERE value = 0")
runningTaskDeadlines = {}
for r in cur.fetchall():
runningTaskDeadlines[r[0]] = r[1]
runningTasks = runningTaskDeadlines.keys()
runningTasks.sort(key = lambda tid: runningTaskDeadlines[tid], reverse = False)
cur.execute("SELECT DISTINCT taskId FROM Milestones WHERE deadline >= ?", [time.time()])
tasks = [t[0] for t in cur.fetchall()]
if tasks and not MainScreen.showall:
tasks.sort(key = lambda tid: getCompletionExpirationDate(tid), reverse = False)
else:
MainScreen.showall = True
cur.execute("SELECT id FROM Tasks")
tasks = [x[0] for x in cur.fetchall()]
tasks.sort(key = lambda tid: getScore(tid), reverse = True)
tasks = [t for t in tasks if t not in runningTasks]
tasks = runningTasks + tasks
self.progressbars = []
for tid in tasks:
running = isRunning(tid, True)
completed = isComplete(tid)
taskLayout = GridLayout(cols=2, spacing=0, size_hint_y=None, height=100)
mainLayout.add_widget(taskLayout)
taskButton = Button(text=getTaskName(tid), size_hint_y=None, height=100)
taskLayout.add_widget(taskButton)
pledgeButton = Button(size_hint_y=None, size_hint_x=None, width=100, height=100)
taskLayout.add_widget(pledgeButton)
pledgeButton.background_color = (0,1,0,1)
taskButton.bind(on_press=self.taskMenu(tid))
if running:
taskButton.background_color = (0.8,1,0.8,1)
pledgeButton.background_color = (1,0,0,1)
cur.execute("SELECT startTime, endTime FROM Fights WHERE value = 0 AND taskId = ?",[tid])
startTime, endTime = cur.fetchall()[0]
pledgeButton.bind(on_press=self.taskPopup(tid, startTime, endTime, True))
taskProgress = ProgressBar(max=endTime-startTime)
self.progressbars.append(taskProgress)
mainLayout.add_widget(taskProgress)
timeLeft = endTime - time.time()
if timeLeft > 0:
taskProgress.value = (min(time.time()-startTime, endTime-startTime+1))
else:
taskProgress.max = taskProgress.value = 1
else:
pledgeButton.bind(on_press=self.taskPopup(tid))
if completed:
taskButton.background_color = (1,0.8,0.8,1)
if not MainScreen.showall:
moreButton = Button(text=localisation.get(language,"showmore"), bold=True, size_hint_y=None, height=100)
mainLayout.add_widget(moreButton)
moreButton.bind(on_press=self.toggleTasksShown)
else:
writeTaskInput = TextInput(text='')
writeTaskPopup = Popup(title=localisation.get(language, "createnew"),
content=writeTaskInput,
size_hint=(None, None), size=(400, 200))
writeTaskPopup.bind(on_dismiss=self.addEmptyTask(writeTaskInput))
newTaskButton = Button(text=localisation.get(language,"createnew"), bold=True, size_hint_y=None, height=100)
newTaskButton.bind(on_release=writeTaskPopup.open)
mainLayout.add_widget(newTaskButton)
langDropdown = DropDown()
for lang in localisation.sections():
btn = Button(text=lang,background_color = (0.6,0.6,0.6,1), valign = 'middle', halign='center', size_hint_y=None, height=100)
btn.bind(on_release=self.changeLanguage(lang))
btn.bind(on_release=langDropdown.dismiss)
langDropdown.add_widget(btn)
langButton = Button(text=localisation.get(language,"language"), bold=True, size_hint_y=None, height=100)
langButton.bind(on_press=langDropdown.open)
mainLayout.add_widget(langButton)
lessButton = Button(text=localisation.get(language,"showless"), bold=True, size_hint_y=None, height=100)
mainLayout.add_widget(lessButton)
lessButton.bind(on_press=self.toggleTasksShown)
Clock.unschedule(self.incrementProgressBars)
Clock.schedule_interval(self.incrementProgressBars, 1)
#.........这里部分代码省略.........
示例8: RemoteCommand
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class RemoteCommand(App):
commands = ListProperty([])
container = ObjectProperty(None)
status = ObjectProperty(None)
log = StringProperty('')
mouse_sensivity = NumericProperty(1)
screen_texture = ObjectProperty(None)
capture_fps = NumericProperty(0)
image_size = NumericProperty(128)
dropdown = ObjectProperty(None)
mods = DictProperty({})
mouse_pos = ListProperty([0, 0])
protocol = ObjectProperty(None, allownone=True)
interface = ObjectProperty(None)
processes = DictProperty({})
curtain = ObjectProperty(None)
def connect(self, ip, port):
Window.release_keyboard()
if self.dropdown:
self.dropdown.dismiss()
self.protocol = None
point = TCP4ClientEndpoint(reactor, ip, int(port))
d = point.connect(CommandClientFactory())
d.addCallback(self.got_protocol)
self.log += u"trying to connect…\n"
self.leftover = ''
if ip not in self.config.items('connections'):
self.config.set('connections', ip, str(port))
def send(self, *args, **kwargs):
self.protocol.sendMessage(json_encode(kwargs))
def update_screen(self, *args):
if self.interface.current_tab.text == 'image':
self.send(command='capture',
size=(self.image_size, self.image_size))
def propose_addresses(self, address_input):
if address_input.focus:
if not self.dropdown:
self.dropdown = DropDown()
#self.dropdown.bind(on_select=self.complete_address)
else:
self.dropdown.clear_widgets()
connections = self.config.items('connections')
for c in connections:
if c[0].startswith(address_input.text):
lbl = Button(text=':'.join(c), size_hint_y=None,
height=sp(30))
lbl.bind(on_press=lambda x:
self.connect(*x.text.split(':')))
self.dropdown.add_widget(lbl)
self.dropdown.open(address_input.parent)
def receive(self, stream):
stream = self.leftover + stream
while stream:
try:
datadict, index = json_decode(stream)
self.leftover = ''
except ValueError:
# incomplete data, keep to analyse later
self.leftover = stream
return
stream = stream[index:]
#self.log += 'got data: %s\n' % datadict
if not isinstance(datadict, dict):
# something went wrong, gtfo for now, FIXME
print "didn't get a dict for datadict"
return
if 'commands' in datadict:
self.commands = datadict['commands']
if 'process' in datadict:
process = datadict['process']
status = datadict.get('status', None)
if status == 'started':
label = Label(text=datadict['name'],
size_hint_y='None',
height='30dp')
out = Button(text='output log')
err = Button(text='error log')
kill = Button(text='close')
kill.bind(on_release=lambda *args:
self.send(command='kill', uid=process))
out.bind(on_release=lambda *args:
self.display_out(process))
#.........这里部分代码省略.........
示例9: ScreenMain
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class ScreenMain(Screen):
settings_popup = ObjectProperty(None, allownone=True)
top_layout = ObjectProperty(None)
main_btn = ObjectProperty(None)
dd_btn = ObjectProperty(None)
def __init__ (self,**kwargs):
super (ScreenMain, self).__init__(**kwargs)
Clock.schedule_once(self.prepare, 0)
self.dropdown = DropDown()
self.user_name ='5 '
def prepare(self, *args):
global user_id
# if first time or loged out
user_id = 0
# call the login screen
self.manager.current = 'ScreenLogin'
def new_user(self, sid, name):
print sid, name
global user_name
self.user_name = name
user_name_label=self.ids.user_name_label
user_name_label.text=self.user_name
first_id = self.add_classes()
# need to get first list
self.class_selected(first_id)
def add_classes(self):
# sql get classes for user
# is user a from teacher ?
# change spinner text & values
sql = 'SELECT sg.id, s.name \
FROM studygroups sg \
JOIN subjects s ON (sg.subject_id = s.id) \
WHERE sg.staff_id=%d \
AND sg.schYr = %d' % (user_id, 2016)
alchemysql = alchemy_text(sql)
result = engine.execute(alchemysql)
classes = [r for r in result]
self.create_dropdown(classes)
if not classes: return
print classes
first_id = classes[0][0]
first_name = classes[0][1]
ddbtn = self.ids.btn_ddID
ddbtn.text = str(first_name)
return first_id
def create_dropdown(self, groups):
self.dropdown.clear_widgets()
for group in groups:
# create button
btn = self.create_button(group)
# add it the dropdown
self.dropdown.add_widget(btn)
def create_button(self, group):
gid, name = group
# specify the height so the dropdown can calculate the area it needs.
# store the class id in the buttons name
btn = Button(text= name, size_hint_y=None, height=40, name=str(gid))
# attach a callback that will call the select() method on the dropdown.
# pass the button text as the data of the selection.
btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
# the call to update student list when button pressed
btn.bind(on_release=partial(self.class_selected, gid))
return btn
def class_selected(self, *args ):
class_id = args[0]
student_list_widget = self.ids.student_list
student_list_widget.clear_widgets()
if not class_id: return
sql = 'SELECT s.id, s.name \
FROM students_by_studygroup ss \
JOIN students s ON (ss.student_id = s.id) \
WHERE ss.studygroup_id=%d ' % (class_id,)
alchemysql = alchemy_text(sql)
result = engine.execute(alchemysql)
# convert to a python list
students = [r for r in result]
self.add_students(students)
def drop_down(self, x=''):
# open the dropdown buttons
self.dropdown.open(x)
#.........这里部分代码省略.........
示例10: Pos
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class Pos(BoxLayout):
def __init__(self, **kwargs):
super(Pos, self).__init__(**kwargs)
self.cliente = None
def hacerNota(self):
if self.txt_client.text == "":
MessageBoxTime(
title="Ops", size_hint=(None, None), size=(350, 120), msg="Por favor especifica el cliente", duration=2
).open()
return
elif self.cliente == None:
MessageBoxTime(
title="Espere", size_hint=(None, None), size=(350, 120), msg="Guardando cliente", duration=2
).open()
print "Realizando nota"
nota = Notas()
nota.PUser = app.root.user
nota.Total = self.txt_total.text
nota.Cliente = self.cliente
products = []
for i in self.lst_note.layout.children:
print i.txt_producto.text
products.append(
{
"Cantidad": i.txt_cant.text,
"Product": i.txt_producto.text,
"Precio": i.txt_precio.text,
"Total": i.txt_total.text,
}
)
nota.Productos = products
nota.save()
# limpiar controles de nota
self.lst_note.clear()
self.lst_note.add_widget(NoteItem())
self.txt_client.text = ""
self.txt_total.text = "0"
self.img_button.source = "plus.png"
self.cliente = None
def on_completeclient(self, w):
if not hasattr(self, "dropdown"):
self.dropdown = DropDown()
if len(w.text) > 2:
self.dropdown.clear_widgets()
found = False
for item in Clientes.Query.filter(words__all=w.text.upper().split()):
but = WhiteButton(text=item.Name, size_hint_y=None, height=40)
but.bind(on_press=self.fillClient)
but.Cliente = item
self.dropdown.add_widget(but)
found = True
if found:
self.dropdown.open(w)
def fillClient(self, w):
self.txt_client.text = w.text
self.img_button.source = "ok.png"
self.cliente = w.Cliente
self.dropdown.dismiss()
def addClient(self):
print "Adding the client: " + self.txt_client.text
self.cliente = Clientes()
self.cliente.Name = self.txt_client.text
self.cliente.PUser = app.root.user
self.cliente.save()
self.img_button.source = "ok.png"
def fillNotas(self):
print "Llenado lista de notas"
for i in app.root.notas:
print i
notareg = NoteReg()
notareg.txt_fecha.text = str(i.createdAt)
#.........这里部分代码省略.........
示例11: MainWin
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class MainWin(BoxLayout):
current_map = ObjectProperty('')
current_location = StringProperty()
containers = ObjectProperty(loc_dat['Havana']['container'], allownone=True)
in_event = False
def __init__(self, **kwargs):
super(MainWin, self).__init__(**kwargs)
self.current_map = 'maps/Havana.jpg'
self.current_location = 'Havana'
self.containers = loc_dat['Havana']['container']
self.locale = loc_dat['Havana']['connections']
self.first_run = True
# Drop Down code
self.dropdown = DropDown() # Binds Class
self.dd_updater() # Calls method to determine location containers
self.ids.mb.bind(on_release=self.dropdown.open) # Connects generated locations to
self.dropdown.bind(on_select=lambda instance, x: self.location(x)) # Binds button's location changing behavior
# Widgets
self.ew = EventWindow()
# Handles the placement of buttons on the map
self.place_locale()
def place_locale(self):
self.cleanup()
if self.locale is None:
pass
else:
for place in self.locale:
place_button = Button(text=place,
id='pb',
size_hint=(.05, .05),
pos_hint={'x': loc_dat[self.current_location]['connections'][place][0],
'y': loc_dat[self.current_location]['connections'][place][1]},
on_release=lambda destination: self.location(destination.text))
self.ids.mapspace.add_widget(place_button)
if self.first_run is False:
MainWin.in_event = True
self.ids.mapspace.add_widget(self.ew)
def cleanup(self):
for child in [child for child in self.ids.mapspace.children]:
self.ids.mapspace.remove_widget(child)
def dd_updater(self):
self.dropdown.clear_widgets()
if self.containers is None:
pass
else:
for note in self.containers: # Adds widgets to the existing dropdown
btn = Button(text=note,
color=(0, 0, 0, 1),
background_normal='images/Button.png',
background_down='images/Button.png',
border=(0, 60, 0, 120),
size_hint_y=None,
height=30)
btn.bind(on_release=lambda b: self.dropdown.select(b.text))
self.dropdown.add_widget(btn)
def location(self, new_loc):
if MainWin.in_event is False or self.first_run is True:
self.current_location = new_loc
self.current_map = loc_dat[new_loc]['image']
self.locale = loc_dat[new_loc]['connections']
self.containers = loc_dat[new_loc]['container']
event.event_name()
event.parse()
self.dd_updater()
self.place_locale()
else:
pass
self.first_run = False
示例12: ScreenMain
# 需要导入模块: from kivy.uix.dropdown import DropDown [as 别名]
# 或者: from kivy.uix.dropdown.DropDown import clear_widgets [as 别名]
class ScreenMain(BoxLayout):
top_layout = ObjectProperty(None)
dd_btn = ObjectProperty(None)
student_image_btn = ObjectProperty('None')
def __init__(self,**kwargs):
super (ScreenMain,self).__init__(**kwargs)
self.dropdown = DropDown()
self.messages_grid = self.ids.messages_grid
self.child_id = 0
self.msg_id =10
Clock.schedule_once(self.prepare, 0)
def prepare(self, *args):
global user_id
print 'prepare'
# if first time or loged out
user_id = 0
self.child_id = 0
print ' call the login popup'
p = LoginPopup()
p.open()
Clock.schedule_interval(self.get_new_messages, 1)
Clock.schedule_interval(self.send_rnd_msg, 2)
def send_rnd_msg(self, *args):
cid = (random.choice([705,2,68]))
sql ="INSERT INTO messages VALUES(%d, %d, 'rnd msg', '01,01,2016', 0, 1)" % (self.msg_id, cid )
print sql
cur.execute(sql)
self.msg_id +=1
def new_user(self):
global user_name
print 'new_user'
user_name = ""
if user_id > 0:
user_name = "Andrew Watts" # fetch name for user_id
first_id = self.add_children()
# need to get first list
self.child_selected(first_id)
def add_children(self):
global user_id, children_dict
children_dict = {}
print 'add_children'
# sql get children for parent
user_id = 180 # test
sql = 'SELECT id, name \
FROM students \
WHERE father_id=180'
alchemysql = alchemy_text(sql)
result = engine.execute(alchemysql)
children = [r for r in result]
count_children = len(children)
for sid, name in children:
children_dict[sid] = name
print 'children_dict',children_dict
self.create_dropdown(children)
first_id = children[0][0]
first_name = children[0][1]
ddbtn = self.ids.btn_ddID
ddbtn.text = str(first_name)
return first_id
def drop_down(self, x=''):
# open the dropdown buttons
self.dropdown.open(x)
# set mainbutton text to select item
self.dropdown.bind(on_select=lambda instance, y: setattr(x, 'text', y))
def create_dropdown(self, children):
print 'create_dropdown'
self.dropdown.clear_widgets()
for child in children:
# create button
btn = self.create_button(child)
# add it the dropdown
self.dropdown.add_widget(btn)
def create_button(self, child):
print 'create_button'
gid, name = child
# specify the height so the dropdown can calculate the area it needs.
# store the class id in the buttons name
btn = Button(text= name, size_hint_y=None, height=40, name=str(gid))
#.........这里部分代码省略.........