def showOutputs(self, relativeTo): """show a list of possible outputs""" if self.mode != 'Disabled': try: dropdown = DropDown(auto_width=True) btn = Button(text="None", markup=True, size_hint_y=None, height='44dp') btn.dataItem = None btn.bind(on_press=lambda btn: dropdown.select(btn.dataItem)) dropdown.add_widget(btn) for item in out.outputs: if item.isActive == True: btn = Button(text=str(item.number) + " (" + item.assetLabel + ")", markup=True, size_hint_y=None, height='44dp') btn.dataItem = item btn.bind(on_press=lambda btn: dropdown.select(btn.dataItem)) dropdown.add_widget(btn) for item in out.relays: if item.isActive == True: btn = Button(text=str(item.number) + " (" + item.assetLabel + ")", markup=True, size_hint_y=None, height='44dp') btn.dataItem = item btn.bind(on_press=lambda btn: dropdown.select(btn.dataItem)) dropdown.add_widget(btn) dropdown.bind(on_select=self.OutputSelected) dropdown.open(relativeTo) except Exception as e: showError(e)
def showModes(self, relativeTo): """show the list of modes""" try: dropdown = DropDown(auto_width=True) btn = Button(text='Disabled', markup=True, size_hint_y=None, height='44dp') btn.bind(on_press=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) btn = Button(text='Toggle', markup=True, size_hint_y=None, height='44dp') btn.bind(on_press=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) btn = Button(text='Button', markup=True, size_hint_y=None, height='44dp') btn.bind(on_press=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) btn = Button(text='Analog', markup=True, size_hint_y=None, height='44dp') btn.bind(on_press=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) dropdown.bind(on_select=self.ModeSelected) dropdown.open(relativeTo) except Exception as e: showError(e)
def populate_drop_down(self, entries, attribute, location): """Populate a drop down menu.""" drop_down = DropDown() for entry in entries: Logger.info("populate dropdown for {}: {}" "".format(attribute, entry)) button = Button( text=entry.name, height=44, size_hint_y=None, on_release=lambda a, entry=entry: setattr(self, attribute, entry)) drop_down.add_widget(button) drop_down.open(location)
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()
def show_connected_devices(self, *args): dropdown_view = DropDown() for device_id, device_name in get_connected_devices().items(): device = (device_id, device_name) device_button = Button(text=device_name, size_hint_y=None, height=80) device_button.bind( on_release=lambda button: dropdown_view.select(device)) dropdown_view.add_widget(device_button) dropdown_view.bind(on_select=lambda instance, device_data: self. on_device_selected(device_data)) dropdown_view.open(self.select_device_button)
def showSelectDevice(self, relativeTo): dropdown = DropDown() # auto_width=False, width='140dp' devices = IOT.getDevices(data.credentials.groundid) for dev in devices: btn = Button(size_hint_y=None, height='32dp') btn.DeviceId = dev['id'] if dev['title']: btn.text = dev[ 'title'] # for old devices that didn't ahve a title yet. else: btn.text = dev['name'] btn.bind(on_release=lambda btn: self.selectDevice( btn.parent.parent, btn.DeviceId, btn.text)) dropdown.add_widget(btn) dropdown.open(relativeTo)
def show_compound_spec_prop(self, instance): """ Called to show compound specification. Triggers a drop-down to select. """ dr = DropDown() dr.bind(on_select=self.select_compound_spec_prop) for i in self.compound_spec_prop: btn = butt(text=i, size_hint_y=None, height=25, background_normal='', background_color=(0.4, 0.4, 0.4, 1), font_size=12) btn.bind(on_release=lambda btn: dr.select(btn.text)) dr.add_widget(btn) dr.open(instance)
class client_select(GridLayout): def __init__(self, eid, **kwargs): super().__init__(**kwargs) #defining constructor for class GridLayout self.rows = 2 #attribute of GridLayout self.cols = 1 self.clients_button = Button(text="Select Client") # self.clients_dropdown = DropDown() # print("EID = ", eid) # sql.execute(f"SELECT * FROM client WHERE E_ID = '{eid}'") # clients = sql.fetchall() # # print("Getting clients, eid = "+eid) # for client in clients: # # print(client) # self.cli_option = Button(text = client[7], size_hint_y=None, height=44) # self.cli_option.bind(on_release=lambda btn: clients_dropdown.select(btn.text)) # self.clients_dropdown.add_widget(self.cli_option) self.clients_button.bind(on_press=self.clients_button_selected) self.add_widget(self.clients_button) self.logout = Button(text="Log Out") self.logout.bind(on_press=self.logout_pressed) self.add_widget(self.logout) # (on_press = lambda *args: main_menu_launch(client[7], app, "main_menu_screen")) def logout_pressed(self, instance): header.remove_widget(tab) header.clear_widgets() def clients_button_selected(self, instance): self.clients_dropdown = DropDown() # print("EID = ", eid) sql.execute(f"SELECT * FROM client WHERE E_ID = '{eid}'") clients = sql.fetchall() for client in clients: # print(client) self.cli_option = Button(text=client[7], size_hint_y=None, height=44) self.cli_option.bind( on_release=lambda btn: self.clients_dropdown.select(btn.text)) self.clients_dropdown.add_widget(self.cli_option) self.clients_dropdown.open(self.clients_button) self.clients_dropdown.bind( on_select=lambda instance, x: main_menu_launch( x, app, "main_menu_screen"))
class CustomSpinner(TextButton): '''Custom Appearance and implementation of the Spinner class of Kivy''' values = ListProperty() is_open = BooleanProperty(False) def __init__(self, **kwargs): super().__init__(**kwargs) self.dropdown = DropDown() self.dropdown.bind(on_select=self.on_dropdown_select) self.bind(on_release=lambda _: self.open_dropdown()) def close_dropdown(self): '''Close the dropdown if it is opened''' if self.dropdown.attach_to: self.is_open = False self.dropdown.dismiss() def open_dropdown(self): '''If the dropdown is not opened then open it''' if not self.dropdown.attach_to: self.is_open = True self.dropdown.open(self) def build_dropdown(self): '''Build the dropdown from the values''' for i, value in enumerate(self.values): item = TextButton(size_hint_y=None, height=dp(48), text=value) if is_even(i): item.background_color = constants.TERNARY_COLOR else: item.background_color = constants.SECONDRY_COLOR item.bind( on_release=lambda option: self.dropdown.select(option.text)) self.dropdown.add_widget(item) def on_values(self, instance, values): '''When values change then build dropdown from those values''' if self.dropdown.children: self.dropdown.clear_widgets() self.build_dropdown() def on_dropdown_select(self, instance, value): '''Select the value chosen from dropdown and close the dropdown''' self.text = value self.close_dropdown()
class DtbObjctDropDown(DtbObjctDPbutton): # Class of a DtbObjctDPbutton triggering a dropdown list on_release. def __init__(self, **kwargs): super(DtbObjctDropDown, self).__init__(**kwargs) self.create_dropdown() def create_dropdown(self): self.dropdownlist = DropDown() for ix in self.linked_dataframe.index: # when adding widgets, we need to specify the height manually # (disabling the size_hint_y) so the dropdown can calculate the # area it needs. btn = DtbObjctDPbutton( linked_dataframe = self.linked_dataframe, objct_id = ix, attr_displayed_list = self.attr_displayed_list, attr_backcolor = self.attr_backcolor, size_hint = (None,None), size = self.size ) # for each button, attach a callback that will call the select() # method on the dropdown. We'll pass the text of the button as # the data of the selection. btn.bind( on_release=lambda btn: self.dropdownlist.select(btn.objct_id) ) # then add the button inside the dropdown self.dropdownlist.add_widget(btn) # one last thing, listen for the selection in the dropdown list and # assign the data to the button text. self.dropdownlist.bind( on_select=lambda instance, x: self.new_objct_id(objct_id = x) ) def on_release(self): self.dropdownlist.open(self)
def dropdown(self): drops = DropDown() for index in list_of_subject: btn = Button(text=index) btn.bind(on_release=lambda btn: drops.select(btn.text)) drops.add_widget(btn) self.ids.menu_but.bind(on_release=drops.open) # self.ids.sub.text = self.ids.menu_but.text return drops.open(self)
class DatePicker(Button): def __init__(self, **kwargs): super(DatePicker, self).__init__(**kwargs) self.dropdown = DropDown(auto_width=False, width=300) self.dropdown.bind(on_select=self.on_select) self.dropdown.add_widget( DatePickerBase(size_hint_y=None, height=200, dropdown=self.dropdown)) self.add_widget(self.dropdown) self.dropdown.dismiss() def on_release(self, *args): self.dropdown.open(self) def on_select(self, instance, data): self.text = data
def assign_users(self, users): user_chooser = DropDown() for user in users: user_chooser.add_widget(UserButton(text="{}".format(users[user].__str__()), user=users[user], size_hint_y=None, height=user_chooser.height, on_release=lambda a: user_chooser.select(a))) self.choosen = UserButton(id='chooser', text="Wybierz uzytkownika", size_hint=(1, 1), user=None) self.choosen.bind(on_release=lambda a: user_chooser.open(self.choosen)) user_chooser.bind(on_select=lambda instance, pressed_button: self.update_user_chooser(self.choosen, pressed_button)) self.main_layout.add_widget(self.choosen)
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 = ''
def showOutputs(self, relativeTo): """show a list of possible outputs""" if self.mode != 'Disabled': try: dropdown = DropDown(auto_width=True) btn = Button(text="None", markup=True, size_hint_y=None, height='44dp') btn.dataItem = None btn.bind(on_press=lambda btn: dropdown.select(btn.dataItem)) dropdown.add_widget(btn) for item in out.outputs: if item.isActive == True: btn = Button(text=str(item.number) + " (" + item.assetLabel + ")", markup=True, size_hint_y=None, height='44dp') btn.dataItem = item btn.bind( on_press=lambda btn: dropdown.select(btn.dataItem)) dropdown.add_widget(btn) for item in out.relays: if item.isActive == True: btn = Button(text=str(item.number) + " (" + item.assetLabel + ")", markup=True, size_hint_y=None, height='44dp') btn.dataItem = item btn.bind( on_press=lambda btn: dropdown.select(btn.dataItem)) dropdown.add_widget(btn) dropdown.bind(on_select=self.OutputSelected) dropdown.open(relativeTo) except Exception as e: showError(e)
def on_cinfdata(self, instance, value): """Setup the setup selection page, when the cinfdata ObjectProperty is set (happens only on startup)""" dropdown = DropDown() for setup in self.cinfdata.get_setups(): btn = SetupButton(text='Setup: ' + setup['title'], size_hint_y=None, height=44, setup=setup) btn.bind(on_release=lambda btn: dropdown.select(btn)) dropdown.add_widget(btn) self.mainbutton.bind(on_release=lambda widget: dropdown.open(widget)) dropdown.bind(on_select=self._select)
class DropDownInput(ListItemButton): labels = ListProperty() def __init__(self, *args, **kwargs): super(DropDownInput, self).__init__(*args, **kwargs) self.menu = DropDown() self.on_release = lambda: self.menu.open(self) self.menu.bind(on_select=lambda instance, x: setattr(self, 'text', x)) def on_labels(self, instance, labels): for i in labels: btn = Button(text=i,size_hint_y=None, height=100, font_size=30) btn.bind(on_release=lambda btn:self.menu.select(btn.text)) self.menu.add_widget(btn)
def showStylesDropDown(self, relativeTo): """show a drop down box with all the available style images""" try: if self.tempData.control: dropdown = DropDown(auto_width=False, width='140dp') skins = sm.getAvailableSkins(self.tempData.control.controlType) for skin in skins: if 'example' in skin: imgpPath = os.path.join(skin['path'], skin['example']) btn = ImageButton(source=imgpPath, size_hint_y=None, height='44dp') else: btn = Button(text=skin['name'], size_hint_y=None, height='44dp') btn.skin = skin #btn.bind(on_release=lambda btn: self.setSkin(btn.skin)) btn.bind(on_press=self.stylesDropDownClosed) dropdown.add_widget(btn) dropdown.open(relativeTo) except Exception as e: showError(e)
def show_options(self, txt_inp): input_type = self.input_type if self.input_type == 'bool': txt_inp.readonly = True txt = (self.overlay_text if txt_inp.text == '' else txt_inp.text) txt_inp.text = 'False' if txt[0] == 'T' else 'True' Clock.schedule_once(lambda dt: self.defocus(txt_inp)) elif input_type.startswith('options'): _options = input_type.split(':')[1:] txt_inp.readonly = True drpdn = DropDown() for opt in _options: drpdn.add_widget( Button(text=opt, background_color=(0, 0, 0, 1), on_touch_up=partial(self.dropdown_select, drpdn, txt_inp), size_hint_y=None, height='36sp')) drpdn.open(txt_inp) Clock.schedule_once(lambda dt: self.defocus(txt_inp))
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()
def showMainDropDown(self, attachTo): dropdown = DropDown(auto_width=False, width='140dp') btn = Button(text='%s New' % iconfonts.icon('fa-file-o'), markup=True, size_hint_y=None, height='44dp') btn.bind(on_release=lambda btn: self.newLayout(btn.parent.parent)) dropdown.add_widget(btn) btn = Button(text='%s Edit' % iconfonts.icon('fa-edit'), markup=True, size_hint_y=None, height='44dp') btn.bind(on_release=lambda btn: self.editLayout(btn.parent.parent)) dropdown.add_widget(btn) btn = Button(text='%s Credentials' % iconfonts.icon('fa-user'), markup=True, size_hint_y=None, height='44dp') btn.bind(on_release=lambda btn: self.editCredentials(btn.parent.parent)) dropdown.add_widget(btn) btn = Button(text='%s Capture scene' % iconfonts.icon('fa-camera'), markup=True, size_hint_y=None, height='44dp') btn.bind(on_release=lambda btn: self.captureScene(btn.parent.parent)) dropdown.add_widget(btn) btn = Button(text='%s Open' % iconfonts.icon('fa-folder-open-o'), markup=True, size_hint_y=None, height='44dp') btn.bind(on_release=lambda btn: self.openLayout(btn.parent.parent)) dropdown.add_widget(btn) dropdown.open(attachTo)
def show_options(self, txt_inp): input_type = self.input_type if self.input_type == 'bool': txt_inp.readonly = True txt = (self.overlay_text if txt_inp.text == '' else txt_inp.text) txt_inp.text = 'False' if txt[0] == 'T' else 'True' Clock.schedule_once(lambda dt:self.defocus(txt_inp)) elif input_type.startswith('options'): _options = input_type.split(':')[1:] txt_inp.readonly = True drpdn = DropDown() for opt in _options: drpdn.add_widget( Button(text=opt, background_color=(0, 0, 0, 1), on_touch_up=partial(self.dropdown_select, drpdn, txt_inp), size_hint_y=None, height = '36sp')) drpdn.open(txt_inp) Clock.schedule_once(lambda dt: self.defocus(txt_inp))
class Root(FloatLayout): slides = ListProperty([]) sm = ObjectProperty(None) controls = ObjectProperty(None) dropdown = ObjectProperty(None) dd_open = BooleanProperty(False) def __init__(self, **kwargs): super(Root, self).__init__(**kwargs) self.sm.transition = BlurTransition() for slide, name in self.slides: self.sm.add_widget(slide, name) self.dropdown = DropDown() for name in self.sm.slide_names: btn = Button(text=name, size_hint_y=None, height="40dp") btn.bind(on_release=lambda btn: self.dropdown.select(btn.text)) self.dropdown.add_widget(btn) self.sm.add_widget(Factory.EndSlide, "Fine della presentazione") def dd_open_wrapper(*args, **kwargs): self.dd_open = True return self.dropdown.open(*args, **kwargs) def dd_dismiss_wrapper(*args): self.dd_open = False self.controls.ddbutton.bind(on_release=dd_open_wrapper) self.dropdown.bind(on_select=lambda instance, x: setattr(self.controls.ddbutton, 'text', x), on_dismiss=dd_dismiss_wrapper) self.dropdown.bind(on_select=lambda instance, x: self.sm.switch_to_slide(x)) self.controls.ddbutton.text = self.sm.current self.sm.bind(current=self.controls.ddbutton.setter("text")) def fade_out_controls(self, *args): if self.controls.collide_point(*Window.mouse_pos) or self.dd_open: Clock.schedule_once(self.fade_out_controls, 1.5) return anim = Animation(opacity=.2, duration=1) anim.start(self.controls) def fade_in_controls(self, *args): anim = Animation(opacity=.8, duration=.2) anim.start(self.controls)
def on_cinfdata(self, instance, value): """Setup the setup selection page, when the cinfdata ObjectProperty is set (happens only on startup)""" dropdown = DropDown() for setup in self.cinfdata.get_setups(): # Do not show setups that has no dateplots if len([l for l in setup['links'] if l['pagetype'] == 'dateplot']) == 0: continue btn = SetupButton(text='Setup: ' + setup['title'], size_hint_y=None, height=44, setup=setup) btn.bind(on_release=lambda btn: dropdown.select(btn)) dropdown.add_widget(btn) self.mainbutton.bind(on_release=lambda widget: dropdown.open(widget)) dropdown.bind(on_select=self._select)
def make_filter_dropdown(self, button, data, init_data, callback): current_buttons = [] current_dropdown = DropDown(dismiss_on_select=False) for tag in data: # When adding widgets, we need to specify the height manually # (disabling the size_hint_y) so the dropdown can calculate # the area it needs. btn = ToggleButton(text='%s' % tag, size_hint_y=None, height=25) if tag in init_data: btn.state = 'down' # for each button, attach a callback that will call the select() method # on the dropdown. We'll pass the text of the button as the data of the # selection. btn.bind(on_release=lambda in_btn: self.update_multiselect_tags( in_btn, current_dropdown, current_buttons, callback)) current_buttons.append(btn) # then add the button inside the dropdown current_dropdown.add_widget(btn) # button.bind(on_press=current_dropdown.open) button.bind(on_release=lambda button_instance: current_dropdown.open( button_instance)) # one last thing, listen for the selection in the dropdown list and # assign the data to the button text. current_dropdown.bind( on_select=lambda instance, x: setattr(button, 'text', x)) if len(init_data) > 0: current_dropdown.select('None') tags_text = self.get_text_from_dropdown_multiselect( current_buttons) if tags_text: current_dropdown.select(tags_text) self.filter_dropdowns[button] = {current_dropdown, callback}
def assign_permissions(self): privilege_chooser = DropDown() for privilege in privileges: privilege_chooser.add_widget(FontFittingButton(text="{}".format(privilege), size_hint_y=None, height=privilege_chooser.height, on_release=lambda a: privilege_chooser.select(a.text))) self.choosen_privilege = FontFittingButton(id='privilege_chooser', text="Wybierz uprawnienia", size_hint=(1, 1), user=None) self.choosen_privilege.bind(on_release=lambda a: privilege_chooser.open(self.choosen_privilege)) privilege_chooser.bind(on_select=lambda instance, choosen: setattr(self.choosen_privilege, 'text', choosen)) self.main_layout.add_widget(self.choosen_privilege) self.confirm_button = FontFittingButton(text="Zmień uprawnienia", size_hint=(1, 1), on_press=lambda a: ConfirmationPopup( confirmed_function=schedule_task, func_args=ChangePermissions(self.choosen.user, self.choosen_privilege.text), func_kwargs={'instance': self}).open()) self.main_layout.add_widget(self.confirm_button)
def setup_period_chooser(self): period_chooser = DropDown() for x in self.dates: period_chooser.add_widget( FontFittingButton( text="{}".format(x), size_hint_y=None, height=self.dropdown_height, on_release=lambda a: period_chooser.select(a.text), **self.dropdown_buttons_properties)) self.choosen = FontFittingButton(text="Dzis", size_hint=(1, 1), **self.button_properties) self.choosen.bind( on_release=lambda a: period_chooser.open(self.choosen)) period_chooser.bind( on_select=lambda instance, z: setattr(self.choosen, 'text', z)) self.main_layout.add_widget( FontFittingLabel(text="Wybierz okres rozliczeniowy:", size_hint=(1, 1), color=self.header_font_color)) self.main_layout.add_widget(self.choosen) self.main_layout.add_widget( FontFittingButton(text="Wybierz inny dzień", size_hint=(1, 1), on_press=lambda a: self.choose_other_date(), **self.button_properties)) self.main_layout.add_widget( FontFittingButton(text="Wyswietl", size_hint=(1, 1), on_press=lambda a: self.display_choosen(), **self.button_properties)) if App.get_running_app().root.logged_user.privileges == 'Admin': self.main_layout.add_widget( FontFittingButton( text="Wyswietl łączne zarobki", size_hint=(1, 1), on_press=lambda a: self.display_choosen(all_users=True), **self.button_properties))
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
class EventHandlerTextInput(TextInput): '''EventHandlerTextInput is used to display/change/remove EventHandler for an event ''' eventwidget = ObjectProperty(None) '''Current selected widget :data:`eventwidget` is a :class:`~kivy.properties.ObjectProperty` ''' eventname = StringProperty(None) '''Name of current event :data:`eventname` is a :class:`~kivy.properties.ObjectProperty` ''' kv_code_input = ObjectProperty() '''Reference to KVLangArea :data:`kv_code_input` is a :class:`~kivy.properties.ObjectProperty` ''' text_inserted = BooleanProperty(None) '''Specifies whether text has been inserted or not :data:`text_inserted` is a :class:`~kivy.properties.ObjectProperty` ''' info_message = StringProperty(None) '''Message to be displayed by InfoBubble :data:`info_message` is a :class:`~kivy.properties.StringProperty` ''' dropdown = ObjectProperty(None) '''DropDown which will be displayed to show possible functions for that event :data:`dropdown` is a :class:`~kivy.properties.ObjectProperty` ''' def on_touch_down(self, touch): '''Default handler for 'on_touch_down' event ''' if self.collide_point(*touch.pos): self.info_bubble = InfoBubble(message=self.info_message) bubble_pos = list(self.to_window(*self.pos)) bubble_pos[1] += self.height self.info_bubble.show(bubble_pos, 1.5) return super(EventHandlerTextInput, self).on_touch_down(touch) def show_drop_down_for_widget(self, widget): '''Show all functions for a widget in a Dropdown. ''' self.dropdown = DropDown() list_funcs = dir(widget) for func in list_funcs: if '__' not in func and hasattr(getattr(widget, func), '__call__'): btn = Button(text=func, size_hint=(None, None), size=(100, 30), shorten=True) self.dropdown.add_widget(btn) btn.bind(on_release=lambda btn: self.dropdown.select(btn.text)) btn.text_size = [btn.size[0] - 4, btn.size[1]] btn.valign = 'middle' self.dropdown.open(self) self.dropdown.pos = (self.x, self.y) self.dropdown.bind(on_select=self._dropdown_select) def _dropdown_select(self, instance, value): '''Event handler for 'on_select' event of self.dropdown ''' self.text += value def on_text(self, instance, value): '''Default event handler for 'on_text' ''' if not self.kv_code_input: return d = get_designer() playground = d.ui_creator.playground self.kv_code_input.set_event_handler(self.eventwidget, self.eventname, self.text) if self.text and self.text[-1] == '.': if self.text == 'self.': self.show_drop_down_for_widget(self.eventwidget) ## TODO recursively call eventwidget.parent to get the root widget elif self.text == 'root.': self.show_drop_down_for_widget(playground.root) else: _id = self.text.replace('.', '') root = playground.root widget = None if _id in root.ids: widget = root.ids[_id] if widget: self.show_drop_down_for_widget(widget) elif self.dropdown: self.dropdown.dismiss()
class DropDownMenu(BoxLayout): """ General dropdown menu for the form """ def __init__(self, **kwargs): super(DropDownMenu, self).__init__(**kwargs, orientation='vertical') self.button = Button(text='Select ', font_size=30, size_hint_y=0.15, on_release=self.drop_down) # main button self.add_widget(self.button) self.dropdown = DropDown() self.dropdown.bind(on_select=self.select) self.tag = None # name for the options group self.selected = False # has selected value self.options = { } # the options to select(keys) and their actual values (values) @property def text(self): """ :return: the text selected in the menu. if non text selected return empty string """ return self.button.text if self.selected else 'No {}'.format( self.tag) if self.tag else '' @property def value(self): """ :return: the actual value selected. if non selected return None """ return self.options[self.button.text] if self.selected else None def select(self, instance, x): """ select the option and show it on the main button, and set selected field to True :param instance: obligated for the dropdown object :param x: the selected text from options """ setattr(self.button, 'text', x) self.selected = True def reset(self): """ reset the dropdown menu """ setattr(self.button, 'text', 'Select {}'.format(self.tag if self.tag else '')) self.selected = False def set_tag(self, tag): """ sets the tag (the options group name) :param tag: (str) the tag name """ self.tag = tag self.button.text += tag def drop_down(self, button): """ when main button is released, open the dropdown :param button: obligated for the button """ self.dropdown.open(button) def set_options(self, options): """ set the options in the menu :param options: (dict) dictionary of options like {'text for the user': $actual_value} """ self.options = options for option in options.keys(): btn = Button(text=option, size_hint_y=None, height=44, on_release=lambda b: self.dropdown.select(b.text)) self.dropdown.add_widget(btn)
class SimpleActionBar(BoxLayout): time = StringProperty() emp_popup = None popup = None logger = logging.getLogger('JAM') def __init__(self, config, **kwargs): BoxLayout.__init__(self, **kwargs) Clock.schedule_interval(self.update_time, 1) self.machine_dropdown = DropDown() self.machine_dropdown.bind(on_select=lambda instance, x: setattr(self.machine_button, 'text', x)) self.set_machine_dropdown(config) def update_time(self, _dt): self.time = time.strftime('%x %H:%M') def set_machine_dropdown(self, config): self.machine_button.text = App.get_running_app().get_current_machine().config['machine_name'] self.machine_dropdown.clear_widgets() blayout = BoxLayout(orientation='vertical', padding=10, spacing=10, size_hint=(None, None), width='150sp') for idx in range(1, 4): if int(config.get('Machine', 'machine{}_enable'.format(idx))): name = config.get('General{}'.format(idx), 'machine_name') colour = config.get('General{}'.format(idx), 'bg_colour') button = Button(text=name, size_hint_y=None, height=100, background_normal='', background_color=Colour[colour].value) button.idx = idx button.bind(on_release=self.machine_selected) blayout.add_widget(button) blayout.height = len(blayout.children) * 110 with blayout.canvas.before: Color(rgba=(0, 0, 0, 1)) Rectangle(pos=blayout.pos, size=blayout.size) self.machine_dropdown.add_widget(blayout) def select_machine(self): self.machine_dropdown.open(self.machine_button) def machine_selected(self, button): self.machine_dropdown.select(button.text) if button.idx is not App.get_running_app().current_index: App.get_running_app().change_machine(button.idx) self.logger.debug("Selected index {}".format(button.idx)) def toggle_button_states(self): self.machine_button.disabled = not self.machine_button.disabled self.main_button.disabled = not self.main_button.disabled def select_employee(self): self.toggle_button_states() sm = App.get_running_app().screen_manager sm.transition = SlideTransition() if sm.current is not 'employee_page': sm.transition.direction = 'up' sm.current = 'employee_page' else: sm.transition.direction = 'down' sm.current = App.get_running_app().get_current_machine().get_page() def select_maintenance(self): sm = App.get_running_app().screen_manager if sm.current is not 'maintenance_page': self.emp_popup = EmployeeScanPage(caller=self, auto_dismiss=False) self.emp_popup.parent_method = self.start_maintenance self.emp_popup.open() def start_maintenance(self, emp_id, _alternate=False): machine = App.get_running_app().get_current_machine() self.logger.debug("Starting maintenance for machine {}".format(machine.index)) machine.start_maintenance(emp_id) self.emp_popup.dismiss() sm = App.get_running_app().screen_manager if sm.current is not 'maintenance_page': sm.transition = SlideTransition() sm.transition.direction = 'up' sm.current = 'maintenance_page' def select_settings(self): popup_boxlayout = BoxLayout(orientation='vertical', spacing='10sp', padding='10sp') self.popup = Popup(title='Admin', content=popup_boxlayout, size_hint=(0.5, 0.5)) popup_boxlayout.add_widget(Label(text='Password: '******'auto' pass_input.password = True popup_boxlayout.add_widget(pass_input) cancel_btn = Button(text='Cancel') cancel_btn.bind(on_press=self.popup.dismiss) confirm_btn = Button(text='Confirm') confirm_btn.bind(on_press=lambda btn: self.start_settings(pass_input.text)) hbox_layout = BoxLayout(orientation='horizontal', spacing='10sp', padding='10sp') hbox_layout.add_widget(cancel_btn) hbox_layout.add_widget(confirm_btn) popup_boxlayout.add_widget(hbox_layout) # pass_input.focus = True self.popup.open() def start_settings(self, password): self.popup.dismiss() if password == App.get_running_app().config.get('Settings', 'password'): self.logger.debug("Password is correct, opening settings") App.get_running_app().open_settings()
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) if i.Cliente != None: notareg.txt_cliente.text = i.Cliente.Name notareg.txt_total.text = str(i.Total) self.lst_notas.add_widget(notareg)
class LoungeScreen(BaseScreen): current_player_slot = NumericProperty(0) players = ListProperty([{}] * 4) dropdown_player = ObjectProperty() drag_start_id = NumericProperty(-1) drag_stop_id = NumericProperty(-1) dragging = BooleanProperty() def __init__(self, **kwargs): super(LoungeScreen, self).__init__(**kwargs) self.set_title('Aufstellung') self.ids.topbar.hasNext = True self.is_dropdown_open = False self.slot_touch = None self.__reset() def on_enter(self): Clock.schedule_once(lambda dt: self.__setup_player_dropdown(), 0.2) self.current_player_slot = 0 def on_leave(self): self.close_dropdown() def on_next(self): self.manager.current = 'match' def __reset(self): self.players = [{}] * 4 self.current_player_slot = 0 def __setup_player_dropdown(self): # only create if not existing if not self.dropdown_player: self.dropdown_player = DropDown(auto_dismiss=False) self.dropdown_player.bind(on_select=self.on_player_select) self.dropdown_player.bind(on_dismiss=self.on_dropdown_dismiss) players = sorted(PlayerData.get_players(), key=lambda player: player['name']) for player in players: btn = PlayerButton(data=player) btn.bind(on_release=lambda btn: self.dropdown_player.select(btn.data)) self.dropdown_player.add_widget(btn) def on_dropdown_dismiss(self, instance): self.is_dropdown_open = False def open_dropdown(self, slot_id): if not self.is_dropdown_open: obj = self.ids['p' + str(slot_id)] self.dropdown_player.open(obj) self.is_dropdown_open = True def close_dropdown(self): if self.is_dropdown_open: self.dropdown_player.dismiss() def on_player_select(self, instance, data): # player was selected from dropdown list self.dropdown_player.dismiss() self.set_player(data) def on_players(self, instance, value): GameData.set_players(value) count_players = 0 for player in self.players: count_players = count_players + (1 if player else 0) self.ids.topbar.isNextEnabled = (count_players == 4) def click_player_slot(self, player_slot): pass def __handle_rfid(self, rfid): # RFID --> player ID player_id = PlayerData.get_player_by_rfid(rfid) # player ID --> player dict player = PlayerData.get_player_by_id(player_id) Logger.info('ScoreTracker: RFID: {0} - ID: {1} - Player: {2}'.format(rfid, player_id, player)) # player does not exist if player == None: self.denied() # player does exist else: if self.dropdown_player: self.dropdown_player.dismiss() self.set_player(player) def highlight_player(self, slot_id): obj = self.ids['p' + str(slot_id)].ids.playerName HighlightOverlay(orig_obj=obj, parent=self, active=True, bold=True).animate(font_size=80, color=(1, 1, 1, 0)) def switch_players(self, slot_id_1, slot_id_2): self.players[slot_id_1], self.players[slot_id_2] = self.players[slot_id_2], self.players[slot_id_1] for player_id in [slot_id_1, slot_id_2]: self.highlight_player(player_id) SoundManager.play(Trigger.PLAYERS_SWITCHED) def get_slot_collision(self, event): slot_id = None colliding = False for i in range(0, 4): obj = self.ids['p' + str(i)] collide = obj.collide_point(event.pos[0], event.pos[1]) if collide: slot_id = i return slot_id def handle_slot_touch_down(self, event): # check if slot was pressed colliding_slot_id = self.get_slot_collision(event) if colliding_slot_id is not None: self.slot_touch = {'source_id': colliding_slot_id, 'source_pos': event.pos, 'target_id': colliding_slot_id, 'dist': 0.0} self.drag_start_id = colliding_slot_id self.dragging = False #print 'down', self.slot_touch def handle_slot_touch_move(self, event): # a slot was dragged if self.slot_touch: dx = abs(self.slot_touch['source_pos'][0] - event.pos[0]) dy = abs(self.slot_touch['source_pos'][1] - event.pos[1]) dist = math.sqrt(dx * dx + dy * dy) self.slot_touch['dist'] = dist self.dragging = (dist > 10.0) # check collision colliding_slot_id = self.get_slot_collision(event) if colliding_slot_id is not None: self.slot_touch['target_id'] = colliding_slot_id self.drag_stop_id = colliding_slot_id else: self.slot_touch['target_id'] = None self.drag_stop_id = -1 #print 'move', self.slot_touch # a slot was released def handle_slot_touch_up(self, event): if self.slot_touch: #print 'up', self.slot_touch # release on same slot if self.slot_touch['source_id'] == self.slot_touch['target_id']: # started in this slot: toggle dropdown if self.slot_touch['source_id'] == self.current_player_slot: if self.is_dropdown_open: self.close_dropdown() else: self.open_dropdown(self.slot_touch['target_id']) # activate else: self.current_player_slot = self.slot_touch['source_id'] self.close_dropdown() # highlight icon obj = self.ids['p' + str(self.current_player_slot)].ids.icon HighlightOverlay(orig_obj=obj, parent=self, active=True).animate(font_size=160, color=(1, 1, 1, 0)) # dragged to another slot else: if self.slot_touch['target_id'] is not None: self.switch_players(self.slot_touch['source_id'], self.slot_touch['target_id']) self.slot_touch = None self.drag_start_id = -1 self.drag_stop_id = -1 def set_player(self, player): # check if player has already been set before try: idx_already_set = self.players.index(player) except ValueError, e: # player is not in any team yet self.players[self.current_player_slot] = player self.highlight_player(self.current_player_slot) SoundManager.play(Trigger.PLAYER_JOINED, player) else:
class Shown_Mama(FloatLayout): def __init__(self,**kwargs): super(Shown_Mama, self).__init__(**kwargs) Window.bind(on_resize=self.window_size_changed) self.chveneba_klasi = Shown_Scroll() self.pirovneba_klasi = Pirovneba_box1() self.add_widget(self.chveneba_klasi) self.add_widget(self.pirovneba_klasi) self.dropdown = DropDown() # Create the dropdown once and keep a reference to it self.dropdown.bind(on_select=lambda instance, x: setattr(self.button, 'text', x)) self.button = Button(text='იუნკერთა სია', font_size=20, size_hint=(.15,.10),font_name="bpg_arial_2009", pos_hint= {'x':.0,'y':.80},background_color = get_color_from_hex("#ff680a"),on_release=self.refresh_dopdown) self.add_widget(self.button) self.items_klasi = Shown_Box() self.chveneba_klasi.add_widget(self.items_klasi) self.sataurebi_lay = sataurebi_layout() self.add_widget(self.sataurebi_lay) self.refres_btn = Button(text = "ძებნა",font_name="bpg_arial_2009", font_size=20) self.refres_btn.bind(on_release = self.refresh) self.pirovneba_klasi.add_widget(self.refres_btn) self.delete_btn = Button(text = "წაშლა",font_name="bpg_arial_2009", font_size=20) self.delete_btn.bind(on_release = self.delete_junker) self.pirovneba_klasi.add_widget(self.delete_btn) def window_size_changed(self,window, width,height): self.button.font_size = width/68.3 self.dropdown.font_size = width/68.3 def delete_junker(self,*args): Main.con.execute("delete from Junker_list where Name = N'%s'and Surname=N'%s'"%(self.pirovneba_klasi.kaci_teqst.text, self.pirovneba_klasi.kaci_gvari_teqst.text)) self.pirovneba_klasi.name_text.text = "უცნობია" self.pirovneba_klasi.surname_text.text = "უცნობია" self.pirovneba_klasi.laptop_serial_result.text = "უცნობია" self.button.text = "იუნკერთა სია" self.pirovneba_klasi.kaci_teqst.text = "" self.pirovneba_klasi.kaci_gvari_teqst.text = "" self.items_klasi.clear_widgets() def refresh_dopdown(self,*args): self.dropdown.open(self.button) self.dropdown.clear_widgets() for index in self.junker_list(): btn = Button(text='Value %s %s' % (index[2],index[2]), size_hint_y=None, height=44,font_name="bpg_arial_2009", on_release=lambda btn: self.command2(name=btn.text)) # bind every btn to a print statement btn.text = '%s %s' % (index[1],index[2]) btn.bind(on_release=lambda btn: self.dropdown.select(btn.text)) self.dropdown.add_widget(btn) def info_container(self): self.command= Main.con.execute("select Name,Surname,dasaxeleba,gacema,vada,Laptop_number from Junker_list, Item_list " "where Junker_list.Jun_ID = Item_list.junker_id and Name = N'%s'and Surname=N'%s' " "order by name"%(self.pirovneba_klasi.kaci_teqst.text,self.pirovneba_klasi.kaci_gvari_teqst.text)) for items in self.command: yield items def junker_list(self): self.junker_fetch = Main.con.execute("select * from Junker_list") for junker in self.junker_fetch: yield junker def command2(self,name): self.dakofili = name.split(' ') self.pirovneba_klasi.kaci_teqst.text = self.dakofili[0] self.pirovneba_klasi.kaci_gvari_teqst.text = self.dakofili[1] self.refresh() def refresh(self,*args): self.items_klasi.clear_widgets() for self.number, self.item in enumerate(self.info_container()): self.pirovneba_klasi.name_text.text = self.item[0] self.pirovneba_klasi.surname_text.text = self.item[1] self.pirovneba_klasi.laptop_serial_result.text = self.item[5] self.a = self.item[4].split("-") self.vada_list = [int(g) for g in self.a] self.mimdinare_dro = datetime.datetime(int(self.vada_list[0]),int(self.vada_list[1]),int(self.vada_list[2])) - datetime.datetime.today() self.strig_converted = str(self.mimdinare_dro) if self.mimdinare_dro.days >= 60: self.items_klasi.add_widget(Shown_class.monacemebi(gamoidzaxe_row=str(self.item[2]),gamoidzaxe_nomeri=str(self.number+1), gamoidzaxe_gacema=str(self.item[3]),gamoidzaxe_vada=self.item[4], gamoidzaxe_statusi="[color=#55FB0E]%s დღე - %s სთ[/color]"%(self.strig_converted[:5],self.strig_converted[10:19]))) elif self.mimdinare_dro.days < 60 and self.mimdinare_dro.days > 30: self.items_klasi.add_widget(Shown_class.monacemebi(gamoidzaxe_row=str(self.item[2]),gamoidzaxe_nomeri=str(self.number+1), gamoidzaxe_gacema=str(self.item[3]),gamoidzaxe_vada=self.item[4], gamoidzaxe_statusi="[color=#ffff14]%s დღე - %s სთ[/color]"%(self.strig_converted[:5],self.strig_converted[10:19]))) elif self.mimdinare_dro.days <=30: self.items_klasi.add_widget(Shown_class.monacemebi(gamoidzaxe_row=str(self.item[2]),gamoidzaxe_nomeri=str(self.number+1), gamoidzaxe_gacema=str(self.item[3]),gamoidzaxe_vada=self.item[4], gamoidzaxe_statusi="[color=#ff2914]%s დღე - %s სთ[/color]"%(self.strig_converted[:5],self.strig_converted[10:19])))
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) # set mainbutton text to select item self.dropdown.bind(on_select=lambda instance, y: setattr(x, 'text', y)) def changer2(self, result, *args): global student_id student_id = args[0] self.manager.get_screen('ScreenStudentDetails').update(result) self.manager.current = 'ScreenStudentDetails' def add_students(self, lst): student_list_widget = self.ids.student_list for item in lst: btn = self.build_student_button(item) student_list_widget.add_widget(btn) sid = item[0] btn.bind(on_press=partial(self.changer2, sid)) student_list_widget.bind(minimum_height=student_list_widget.setter('height')) def build_student_button(self, item): image_id = str(item[0]).zfill(5) image_file = "student_images/0000%d.jpg" % item[0] btn = StudentListItemButton( wid = str(item[0]), image = image_file, title = item[1], label = item[1] ) btn.size_hint=(1, None) btn.height = 42 return btn
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)) err.bind(on_release=lambda *args: self.display_out(process, 'err')) box = BoxLayout(size_hint_y=None, height=sp(20)) box.add_widget(label) box.add_widget(out) box.add_widget(err) box.add_widget(kill) self.processes[process] = { 'label': label, 'box': box, 'kill': kill, 'out': '', 'err': ''} self.status.add_widget(box) elif status == 'ended': box = self.processes[process]['box'] if datadict['autoclose']: app.status.remove_widget(box) else: label = self.processes[process]['label'] label.text += ' - DONE' kill = self.processes[process]['kill'] box.remove_widget(kill) close = Button(text='close') close.bind(on_release=lambda *args: app.status.remove_widget(box)) box.add_widget(close) elif 'stdout' in datadict: self.processes[process]['out'] += datadict['stdout'].\ decode('base64') elif 'stderr' in datadict: self.processes[process]['err'] += datadict['stderr'].\ decode('base64') if 'mouse_pos' in datadict: self.mouse_pos = datadict['mouse_pos'] if 'image' in datadict: #print "receiving capture" uid = datadict['image'] if uid not in self.images: fn = 'tmp-%s.png' % uid self.images[uid] = [ fn, # filename open(fn, 'w'), # file descriptor 0, # next expected chunk {} # chunks arrived too early ] fn, f, c, chunks = self.images[uid] data = datadict['data'] chunk = datadict['chunk'] #print'receiving %s chunk %s data %s' % (uid, chunk, data[:10]) if chunk == c: if not data: #print "empty chunk, closing" f.close() move(fn, 'tmp.png') self.screen_texture.reload() del self.images[uid] else: f.write(datadict['data'].decode('base64')) #print "writting chunk", c c += 1 else: chunks[chunk] = data.decode('base64') while c in chunks: #print "applying chunk %s that we got before" % c f.write(chunks[c]) c += 1 if data: self.images[uid] = fn, f, c, chunks def process_menu(self, process, *args): pass def display_out(self, uid, out='out'): process = self.processes[uid] p = Popup(size_hint=(.95, .95), title='std%s %s' % (out, process['label'].text)) sc = ScrollView() content = Label(text=process[out], size_hint=(None, None)) sc.bind(width=content.setter('width')) content.bind(width=lambda c, w: content.setter('text_size')(c, (w, None))) content.bind(texture_size=content.setter('size')) sc.add_widget(content) p.add_widget(sc) p.open() def got_protocol(self, p): self.log += "got protocol\n" self.protocol = p def on_protocol(self, *args): if not self.protocol: Animation(top=self.interface.top, d=.5, t='in_quad').start( self.curtain) else: Animation(top=0, d=.5, t='out_quad').start(self.curtain) def on_capture_fps(self, *args): Clock.unschedule(self.update_screen) if self.capture_fps: Clock.schedule_interval(self.update_screen, 1 / self.capture_fps) def on_commands(self, *args): self.container.clear_widgets() self.log += 'got a list of commands!\n' for command, arguments in self.commands: box = BoxLayout(height=sp(30)) button = Button(text=command) args_inputs = [] for arg in arguments.split(','): if arg == 'str': txtinput = TextInput() args_inputs.append(txtinput) box.add_widget(txtinput) button.bind(on_press=partial( self.execute, command, arguments.split(','), args_inputs)) box.add_widget(button) self.container.add_widget(box) def execute(self, command, arguments, args_inputs, *args): values = [] for arg_type, arg_input in zip(arguments, args_inputs): if arg_type == 'str': values.append(arg_input.text) self.send(run=command, arguments=values) def mouse_move(self, dx, dy): self.send(command='mouse', action='move', dx=int(round(dx * self.mouse_sensivity)), dy=-int(round(dy * self.mouse_sensivity))) def mouse_click(self, b=1, n=2): self.send(command='mouse', action='click', b=b, n=n) def mouse_press(self, b=1): #self.log += 'mouse pressed\n' self.send(command='mouse', action='press', b=b) def mouse_release(self, b=1): #self.log += 'mouse released\n' self.send(command='mouse', action='release', b=b) def send_keys(self, string): self.send(command='type', string=string) def press_special_key(self, key): self.send(command='press_key', key=key.text) def release_special_key(self, key): self.send(command='release_key', key=key.text) def on_start(self, *args): self.config = ConfigParser() self.config.read(CONFIG) self.images = {} if not self.config.has_section('connections'): self.config.add_section('connections') with open(CONFIG, 'w') as f: self.config.write(f) def on_pause(self, *args): with open(CONFIG, 'w') as f: self.config.write(f) return True def on_resume(self, *args): return True def on_stop(self, *args): with open(CONFIG, 'w') as f: self.config.write(f) return True def populate_keyboard(self, grid): b = Button(text='escape') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for f in range(12): b = Button(text='f%d' % (f + 1)) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for i in range(13): grid.add_widget(Widget()) grid.add_widget(Widget()) b = Button(text='up') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for i in range(2): grid.add_widget(Widget()) for t in 'home', 'end': b = Button(text=t) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) grid.add_widget(Widget()) b = Button(text='shift') grid.add_widget(b) self.mods['shift'] = b b = Button(text='control') grid.add_widget(b) self.mods['control'] = b b = Button(text='alt') grid.add_widget(b) self.mods['alt'] = b b = Button(text='meta') grid.add_widget(b) self.mods['meta'] = b grid.add_widget(Widget()) b = Button(text='backspace') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) #for i in range(5): #grid.add_widget(Widget()) for t in 'left', 'down', 'right': b = Button(text=t) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) grid.add_widget(Widget()) for t in 'up', 'down': b = Button(text='page%s' % t) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for i in range(6): grid.add_widget(Widget()) b = Button(text='return') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b)
class MainScreen(Screen): def __init__(self, *args, **kwargs): super(MainScreen, self).__init__(*args, **kwargs) self.gen_env() #self.gen_map() self.edges = list() self.countries = list() self.player = None def gen_env(self): width, height = Window.size # Заголовок self.text1 = BlackLabel(size_hint=(None, None), width=100, height=30, font_size=14, pos=(50, height - 30)) self.text1.text = 'Количество стран-вершин' self.add_widget(self.text1) # Окно поиска self.input1 = TextInput(multiline=False, size_hint=(None, None), width=100, height=30, font_size=14, pos=(200, height - 30), text='1') # on_text_validate=print) self.add_widget(self.input1) # Генерация карты вершин self.generate_map = Button( size_hint=(None, None), width=100, height=30, font_size=14, text='Генерировать', pos=(310, height - 30) ) self.generate_map.bind(on_release=self.gen_map) self.add_widget(self.generate_map) #gamma self.gamma_text = BlackLabel(size_hint=(None, None), width=100, height=30, font_size=14, pos=(450, height - 30)) self.gamma_text.text = 'Введите гамма' self.add_widget(self.gamma_text) # Окно ввода гаммы self.input_gamma = TextInput(multiline=False, size_hint=(None, None), width=100, height=30, font_size=14, pos=(550, height - 30), text='2') # on_text_validate=print) self.add_widget(self.input_gamma) # ввод гаммы self.gamma_button = Button(size_hint=(None, None), width=130, height=30, font_size=14, text='Изменить гамма', pos=(550, height - 70)) self.gamma_button.bind(on_release=self.change_gamma) self.add_widget(self.gamma_button) # Заголовок self.play_button= Button(size_hint=(None, None), width=100, height=30, font_size=14, text='Играть за', pos=(50, height - 70)) self.play_button.bind(on_release=self.add_player) self.add_widget(self.play_button) # Окно выбора игрока self.dropdown_1 = DropDown() self.country_change = Button( size_hint=(None, None), width=100, height=30, font_size=14, text='', pos=(150, height - 70) ) self.country_change.bind(on_release=self.update_dropdown_1) # Действие в момент выбора # self.dropdown.bind(on_select=lambda instance, x: setattr(self.search, 'text', x)) self.add_widget(self.country_change) self.model_game_btn = Button( size_hint=(None, None), width=100, height=30, font_size=14, text='Играть раунд', pos=(310, height - 70) ) self.model_game_btn.bind(on_release=partial(self.model_game, 0)) self.add_widget(self.model_game_btn) # Кнопка атаки self.attack = Button(size_hint=(None, None), width=100, height=30, font_size=14, text='Атаковать', pos=(50, height - 110)) self.attack.bind(on_release=self.country_conquest) self.add_widget(self.attack) # Окно выбора игрока self.dropdown_2 = DropDown() self.attack_country = Button( size_hint=(None, None), width=100, height=30, font_size=14, text='', pos=(150, height - 110) ) self.attack_country.bind(on_release=self.update_dropdown_2) # Действие в момент выбора # self.dropdown.bind(on_select=lambda instance, x: setattr(self.search, 'text', x)) self.add_widget(self.attack_country) # Кнопка паса self.passs = Button(size_hint=(None, None), width=100, height=30, font_size=14, text='Пасовать', pos=(50, height - 150)) self.passs.bind(on_release=self.pass_round) self.add_widget(self.passs) def change_gamma(self, *args): global my_w my_w.gamma = float(self.input_gamma.text) def update_dropdown_1(self, struct): if self.player: return -1 global my_w self.dropdown_1.dismiss() self.dropdown_1=DropDown() self.dropdown_1.max_height = Window.size[1] * 0.7 #Здесь будет возвращаться список стран for country in my_w.country_list: btn = Button(text=f'{country.get_number()}', size_hint_y=None, height=30) btn.bind(on_release=lambda btn: self.dropdown_1.select(btn.text)) self.dropdown_1.add_widget(btn) self.dropdown_1.open(struct) self.dropdown_1.bind(on_select=lambda instance, x: setattr(self.country_change, 'text', x)) self.attack_country.text='' def update_dropdown_2(self, struct): global my_w # Здесь будет возвращаться список соседей для выбранной страны if self.country_change.text!='': self.dropdown_2.dismiss() self.dropdown_2 = DropDown() self.dropdown_2.max_height = Window.size[1] * 0.7 number = int(self.country_change.text) your_country = my_w.search_country_by_number(number) for neigh in your_country.get_neighbors(): btn = Button(text=f'{neigh.get_number()}', size_hint_y=None, height=30) btn.bind(on_release=lambda btn: self.dropdown_2.select(btn.text)) self.dropdown_2.add_widget(btn) self.dropdown_2.open(struct) self.dropdown_2.bind(on_select=lambda instance, x: setattr(self.attack_country, 'text', x)) def country_conquest(self, *args): global my_w at_number = int(self.country_change.text) def_number = int(self.attack_country.text) if at_number!='' and def_number!='': att = my_w.search_country_by_number(at_number) deff = my_w.search_country_by_number(def_number) my_w.attack(att, deff) self.attack_country.text='' self.update_map() self.model_game(flag=1) def pass_round(self, *args): self.model_game(flag=1) def model_game(self, flag=0, *args): global my_w #создаём очередь if flag==0: self.queue = my_w.generate_queue() self.i = 0 while self.i < len(self.queue): play_country = self.queue[self.i] if self.player == play_country: self.update_map() break loser = my_w.play(play_country) # создаём новую очередь, если что-то делаем if loser: new_queue = list() for country in self.queue: if country != loser: new_queue.append(country) self.queue = new_queue # проверяем сместилась ли она так, что элемент с текущим номером стал другим, если да, то ничего не делаем, # если нет, то i++ if self.i < len(self.queue): if play_country == self.queue[self.i]: self.i += 1 self.update_map() def add_player(self, *args): if self.country_change.text !='': self.player = self.country_change.text def gen_map(self, *args): global my_w quantity = int(self.input1.text) my_w.zeroize() my_w.generate_vertexes(quantity=quantity) my_w.generate_countries() self.update_map() def update_map(self, *args): coordinate_vert_dict = dict() k = 0 for vert in my_w.vertexes: coordinate_vert_dict[vert.get_number()] = (20 + k * 80, 200) k += 1 defalt_size = 50 # очистка ребёр с экрана for edge in self.edges: self.remove_widget(edge) self.edges = list() for edge in my_w.edges: x1, y1 = coordinate_vert_dict[edge[0]] x2, y2 = coordinate_vert_dict[edge[1]] kivy_edge = Edge([x1 + defalt_size // 2, y1 + defalt_size // 2, x2 + defalt_size // 2, y2 + defalt_size // 2]) self.edges.append(kivy_edge) self.add_widget(kivy_edge) for country in self.countries: # print(country) self.remove_widget(country) self.countries = list() for country in my_w.country_list: for vert in country.vertexes: cb = CircleButton(text=f'{vert.weight}', circle_color=country.color, font_size=25, pos=coordinate_vert_dict[vert.get_number()], size=(defalt_size, defalt_size)) self.countries.append(cb) self.add_widget(cb)
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)) err.bind(on_release=lambda *args: self.display_out( process, 'err')) box = BoxLayout(size_hint_y=None, height=sp(20)) box.add_widget(label) box.add_widget(out) box.add_widget(err) box.add_widget(kill) self.processes[process] = { 'label': label, 'box': box, 'kill': kill, 'out': '', 'err': '' } self.status.add_widget(box) elif status == 'ended': box = self.processes[process]['box'] if datadict['autoclose']: app.status.remove_widget(box) else: label = self.processes[process]['label'] label.text += ' - DONE' kill = self.processes[process]['kill'] box.remove_widget(kill) close = Button(text='close') close.bind(on_release=lambda *args: app.status. remove_widget(box)) box.add_widget(close) elif 'stdout' in datadict: self.processes[process]['out'] += datadict['stdout'].\ decode('base64') elif 'stderr' in datadict: self.processes[process]['err'] += datadict['stderr'].\ decode('base64') if 'mouse_pos' in datadict: self.mouse_pos = datadict['mouse_pos'] if 'image' in datadict: #print "receiving capture" uid = datadict['image'] if uid not in self.images: fn = 'tmp-%s.png' % uid self.images[uid] = [ fn, # filename open(fn, 'w'), # file descriptor 0, # next expected chunk {} # chunks arrived too early ] fn, f, c, chunks = self.images[uid] data = datadict['data'] chunk = datadict['chunk'] #print'receiving %s chunk %s data %s' % (uid, chunk, data[:10]) if chunk == c: if not data: #print "empty chunk, closing" f.close() move(fn, 'tmp.png') self.screen_texture.reload() del self.images[uid] else: f.write(datadict['data'].decode('base64')) #print "writting chunk", c c += 1 else: chunks[chunk] = data.decode('base64') while c in chunks: #print "applying chunk %s that we got before" % c f.write(chunks[c]) c += 1 if data: self.images[uid] = fn, f, c, chunks def process_menu(self, process, *args): pass def display_out(self, uid, out='out'): process = self.processes[uid] p = Popup(size_hint=(.95, .95), title='std%s %s' % (out, process['label'].text)) sc = ScrollView() content = Label(text=process[out], size_hint=(None, None)) sc.bind(width=content.setter('width')) content.bind( width=lambda c, w: content.setter('text_size')(c, (w, None))) content.bind(texture_size=content.setter('size')) sc.add_widget(content) p.add_widget(sc) p.open() def got_protocol(self, p): self.log += "got protocol\n" self.protocol = p def on_protocol(self, *args): if not self.protocol: Animation(top=self.interface.top, d=.5, t='in_quad').start(self.curtain) else: Animation(top=0, d=.5, t='out_quad').start(self.curtain) def on_capture_fps(self, *args): Clock.unschedule(self.update_screen) if self.capture_fps: Clock.schedule_interval(self.update_screen, 1 / self.capture_fps) def on_commands(self, *args): self.container.clear_widgets() self.log += 'got a list of commands!\n' for command, arguments in self.commands: box = BoxLayout(height=sp(30)) button = Button(text=command) args_inputs = [] for arg in arguments.split(','): if arg == 'str': txtinput = TextInput() args_inputs.append(txtinput) box.add_widget(txtinput) button.bind(on_press=partial(self.execute, command, arguments.split(','), args_inputs)) box.add_widget(button) self.container.add_widget(box) def execute(self, command, arguments, args_inputs, *args): values = [] for arg_type, arg_input in zip(arguments, args_inputs): if arg_type == 'str': values.append(arg_input.text) self.send(run=command, arguments=values) def mouse_move(self, dx, dy): self.send(command='mouse', action='move', dx=int(round(dx * self.mouse_sensivity)), dy=-int(round(dy * self.mouse_sensivity))) def mouse_click(self, b=1, n=2): self.send(command='mouse', action='click', b=b, n=n) def mouse_press(self, b=1): #self.log += 'mouse pressed\n' self.send(command='mouse', action='press', b=b) def mouse_release(self, b=1): #self.log += 'mouse released\n' self.send(command='mouse', action='release', b=b) def send_keys(self, string): self.send(command='type', string=string) def press_special_key(self, key): self.send(command='press_key', key=key.text) def release_special_key(self, key): self.send(command='release_key', key=key.text) def on_start(self, *args): self.config = ConfigParser() self.config.read(CONFIG) self.images = {} if not self.config.has_section('connections'): self.config.add_section('connections') with open(CONFIG, 'w') as f: self.config.write(f) def on_pause(self, *args): with open(CONFIG, 'w') as f: self.config.write(f) return True def on_resume(self, *args): return True def on_stop(self, *args): with open(CONFIG, 'w') as f: self.config.write(f) return True def populate_keyboard(self, grid): b = Button(text='escape') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for f in range(12): b = Button(text='f%d' % (f + 1)) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for i in range(13): grid.add_widget(Widget()) grid.add_widget(Widget()) b = Button(text='up') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for i in range(2): grid.add_widget(Widget()) for t in 'home', 'end': b = Button(text=t) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) grid.add_widget(Widget()) b = Button(text='shift') grid.add_widget(b) self.mods['shift'] = b b = Button(text='control') grid.add_widget(b) self.mods['control'] = b b = Button(text='alt') grid.add_widget(b) self.mods['alt'] = b b = Button(text='meta') grid.add_widget(b) self.mods['meta'] = b grid.add_widget(Widget()) b = Button(text='backspace') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) #for i in range(5): #grid.add_widget(Widget()) for t in 'left', 'down', 'right': b = Button(text=t) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) grid.add_widget(Widget()) for t in 'up', 'down': b = Button(text='page%s' % t) b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b) for i in range(6): grid.add_widget(Widget()) b = Button(text='return') b.bind(on_press=self.press_special_key) b.bind(on_release=self.release_special_key) grid.add_widget(b)
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) if i.Cliente != None: notareg.txt_cliente.text = i.Cliente.Name notareg.txt_total.text = str(i.Total) self.lst_notas.add_widget(notareg)
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 self.albumart = "http://%s:1400%s#.jpg" % ( self.currentplayer.ip_address, metadata.album_art_uri) # Is this a radio track if type(event.current_track_meta_data) is soco.data_structures.DidlItem: #noqa currenttrack = event.enqueued_transport_uri_meta_data.title else: currenttrack = "%s - %s\n%s" % (metadata.creator, metadata.title, metadata.album if hasattr(metadata, 'album') else "") self.currenttrack = currenttrack def monitor(self, dt): try: event = self.queue.get_nowait() except Empty: return if event.service.service_type == "RenderingControl": self.parserenderingevent(event) else: self.parseavevent(event) def volumeslider_touch_down(self, instance, touch): if instance.collide_point(*touch.pos): self.activeslider = True return True def volumeslider_touch_up(self, instance, touch): if touch.grab_current is instance: self.activeslider = False return True def makegroup(self, player, widget): if player in self.currentplayer.group.members: player.unjoin() else: player.join(self.currentplayer) self.updatename() def editgroup(self, widget): self.dropdown.clear_widgets() for player in sorted(self.currentplayer.all_zones, key=lambda x: x.player_name): btn = ToggleButton(text='%s' % (player.player_name,), size_hint_y=None, height=60) btn.bind(on_release=partial(self.makegroup, player)) if player in self.currentplayer.group.members: btn.state = "down" self.dropdown.add_widget(btn) self.dropdown.open(widget) def updatename(self): self.playername = self.currentplayer.group.label
class GroupSongDropdown(Button): def __init__(self, db: DBMuziek, default=None, **kwargs): super(GroupSongDropdown, self).__init__(**kwargs) self.dropdown = DropDown() self.song_id = None self.text = "<Choice>" self._db = db self.songs = None self.g_id = None self.g_name = None self.disable() self.update_data(default) self.bind(on_release=self.open) self.dropdown.bind(on_select=lambda _, btn: self.on_select(btn)) def disable(self): self.disabled = True def enable(self): self.disabled = False def update_data(self, data): if data and "group_id" in data: self.g_id = data["group_id"] self.g_name = data["group_name"] if "song_id" in data: self.song_id = data["song_id"] self.text = data["song_name"] if self.g_id is not None: self.update_songs() self.enable() def reset_choice(self, dd): if dd: dd.dismiss() self.text = "<Choice>" self.song_id = None def update_songs(self, g_id=-1, g_name=None): if g_id is None: self.reset_choice(None) self.g_id = None self.disable() return elif g_id != -1 and self.g_id != g_id: self.g_id = g_id self.enable() self.reset_choice(None) if g_name: self.g_name = g_name self.songs = self._db.get_songs({"group_id": self.g_id}) self.dropdown.clear_widgets() btn = Button(text="<Choice>", size_hint_y=None, height=44) btn.bind(on_release=lambda _: self.reset_choice(self.dropdown)) self.dropdown.add_widget(btn) for song in self.songs: btn = SongButton(text=song["song_name"], size_hint_y=None, height=44) btn.set_id(song["song_id"]) btn.bind(on_release=self.dropdown.select) self.dropdown.add_widget(btn) btn = Button(text="+", size_hint_y=None, height=44) btn.bind(on_release=lambda _: summon_popup_song( self._db, self.dropdown, self.g_id, self.g_name)) self.dropdown.add_widget(btn) def open(self, btn): self.update_songs() self.dropdown.open(btn) def on_select(self, btn): self.text = btn.text self.song_id = btn.song_id
class EventHandlerTextInput(TextInput): '''EventHandlerTextInput is used to display/change/remove EventHandler for an event ''' eventwidget = ObjectProperty(None) '''Current selected widget :data:`eventwidget` is a :class:`~kivy.properties.ObjectProperty` ''' eventname = StringProperty(None) '''Name of current event :data:`eventname` is a :class:`~kivy.properties.ObjectProperty` ''' kv_code_input = ObjectProperty() '''Reference to KVLangArea :data:`kv_code_input` is a :class:`~kivy.properties.ObjectProperty` ''' text_inserted = BooleanProperty(None) '''Specifies whether text has been inserted or not :data:`text_inserted` is a :class:`~kivy.properties.ObjectProperty` ''' project_loader = ObjectProperty(None) '''Reference to ProjectLoader :data:`project_loader` is a :class:`~kivy.properties.ObjectProperty` ''' info_message = StringProperty(None) '''Message to be displayed by InfoBubble :data:`info_message` is a :class:`~kivy.properties.StringProperty` ''' dropdown = ObjectProperty(None) '''DropDown which will be displayed to show possible functions for that event :data:`dropdown` is a :class:`~kivy.properties.ObjectProperty` ''' def on_touch_down(self, touch): '''Default handler for 'on_touch_down' event ''' if self.collide_point(*touch.pos): self.info_bubble = InfoBubble(message=self.info_message) bubble_pos = list(self.to_window(*self.pos)) bubble_pos[1] += self.height self.info_bubble.show(bubble_pos, 1.5) return super(EventHandlerTextInput, self).on_touch_down(touch) def show_drop_down_for_widget(self, widget): '''Show all functions for a widget in a Dropdown. ''' self.dropdown = DropDown() list_funcs = dir(widget) for func in list_funcs: if '__' not in func and hasattr(getattr(widget, func), '__call__'): btn = Button(text=func, size_hint=(None, None), size=(100, 30), shorten=True) self.dropdown.add_widget(btn) btn.bind(on_release=lambda btn: self.dropdown.select(btn.text)) btn.text_size = [btn.size[0] - 4, btn.size[1]] btn.valign = 'middle' self.dropdown.open(self) self.dropdown.pos = (self.x, self.y) self.dropdown.bind(on_select=self._dropdown_select) def _dropdown_select(self, instance, value): '''Event handler for 'on_select' event of self.dropdown ''' self.text += value def on_text(self, instance, value): '''Default event handler for 'on_text' ''' if not self.kv_code_input: return self.kv_code_input.set_event_handler(self.eventwidget, self.eventname, self.text) if self.text and self.text[-1] == '.': if self.text == 'self.': self.show_drop_down_for_widget(self.eventwidget) elif self.text == 'root.': self.show_drop_down_for_widget( self.project_loader.root_rule.widget) else: _id = self.text.replace('.', '') root = self.project_loader.root_rule.widget widget = None if _id in root.ids: widget = root.ids[_id] if widget: self.show_drop_down_for_widget(widget) elif self.dropdown: self.dropdown.dismiss()
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)) # 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.child_selected, gid)) return btn def create_mask(self): self.mask = Image.new('L', (200,200), 0) draw = ImageDraw.Draw(self.mask) draw.ellipse((0, 0) + self.mask.size, fill=255) def child_selected(self, *args ): print 'child_selected' self.messages_grid.clear_widgets() self.child_id = args[0] image_id = str(self.child_id).zfill(5) self.imagefile = 'student_images/%s' % image_id print 'the imagefile', self.imagefile name = "Name:%s \n ID:%d" % (children_dict[self.child_id], self.child_id) studentname_label = self.ids.studentname_label studentname_label.text = name # would like to change img_btn to image # image would be a background fill with a # round masked image of the student on top # or student behind and the fill has a hole in it img_btn = self.ids.student_image_btn img_btn.background_normal = 'student_images/00001.jpg' stored_messages = self.get_stored_messages() # get new messages self.get_new_messages() def get_new_messages(self, x=0): new_messages = self.select_column_and_value("SELECT id, message, date \ FROM messages \ WHERE child_id = %d \ AND user_id = 1 \ AND read <> 1" % self.child_id) txt = "there are %d new messages for child_id %d)" % (len(new_messages), self.child_id) print txt for msg in new_messages: msg_id, child_id, content, date = msg['id'], self.child_id, msg['message'], msg['date'] sql = "INSERT INTO stored_messages VALUES (%d, %d, '%s', '%s')" % (msg_id, child_id, content, date) print sql cur.execute(sql) sql = "UPDATE messages SET read=1 WHERE id=%d" % (msg_id, ) print sql cur.execute(sql) self.display_msg(msg, 1) def notify_db(self, msg_id): pass def select_column_and_value(self, sql, parameters=()): execute = cur.execute(sql, parameters) fetch = execute.fetchall() if fetch is None: return {k[0]: None for k in execute.description} else: lis = [] for row in fetch: lis.append( {k[0]: v for k, v in list(zip(execute.description, row))} ) return lis def get_stored_messages(self): print 'get_stored_messages' stored_messages = self.select_column_and_value("SELECT id, message, date FROM stored_messages WHERE child_id = %d " % self.child_id) for msg in stored_messages: self.display_msg(msg) return stored_messages # save to file # if self.notify_db(key): is sucsessful # pass # else: # return # wait for clock def display_msg(self, entry, new=0): print 'display_msg ', entry content = entry['message'] print 'content = ', content if new: content = 'new %s' % content lbl = Label( text = content) self.messages_grid.add_widget(lbl) widget = self.ids.messages_grid widget.bind(minimum_height= widget.setter('height'))
class MainLayout(Widget): btn_toggle_airports = ObjectProperty( None ) # Hold a reference to the "Show Airports" button after the graphics are rendered. btn_toggle_airplanes = ObjectProperty( None ) # Hold a reference to the "Show Airplanes" button after the graphics are rendered. locations_map = ObjectProperty( None) # Hold a reference to the map after the graphics are rendered. airports_search_bar = ObjectProperty( None ) # Hold a reference to the airports search bar after the graphics are rendered. airplanes_search_bar = ObjectProperty( None ) # Hold a reference to the airplanes search bar after the graphics are rendered. settings_panel = ObjectProperty( None ) # Hold a reference to the settings panel after the graphics are rendered. def __init__(self): super(MainLayout, self).__init__() self.suggestions_dropdown = DropDown( ) # Declare and initialize the suggestions drop-down object for both search bars. self.app = MDApp.get_running_app( ) # Hold a reference to the main class which inherits from App to jump-start the app. def toggle_airports(self): """ Allows to application to add the airports found within the field of view. :return: None """ if self.locations_map.show_airports: self.locations_map.show_airports = False else: if self.locations_map.zoom > 5: self.locations_map.show_airports = True self.locations_map.start_getting_locations_in_fov() else: self.btn_toggle_airports.state = 'normal' show_message_popup("Zoom level must be greater than 5.") def toggle_airplanes(self): """ Allows the application to add the airplanes found within the field of view. :return: None """ if self.locations_map.show_airplanes: self.locations_map.show_airplanes = False else: if self.locations_map.zoom > 5: self.locations_map.show_airplanes = True self.locations_map.start_getting_locations_in_fov() else: self.btn_toggle_airplanes.state = 'normal' show_message_popup("Zoom level must be greater than 5.") def get_airport_suggestions(self): """ Renders the airports suggestions as options within a drop-down menu based on the text given by the user within the airports search bar. :return: None """ if not self.airports_search_bar.focus: # If the function gets called after the user has chosen option, self.suggestions_dropdown.dismiss() # hide drop-down. return else: # else, if the function is called to select option, self.suggestions_dropdown.dismiss() # hide previous drop-down. self.suggestions_dropdown = DropDown() airports_data = self.app.data_manager.airports_tree_manager.get_in_order_list( self.app.data_manager.airports_tree, self.airports_search_bar.text.upper()) airport_id_index = self.app.data_manager.airports_tree_manager.index if airports_data is None: btn_suggestion = Button(text='NOT FOUND', size_hint_y=None, height=44) self.suggestions_dropdown.add_widget(btn_suggestion) else: for airport_data in airports_data: btn_suggestion = DataButton( data=airport_data, text=airport_data[airport_id_index], size_hint_y=None, height=44) btn_suggestion.bind(on_release=lambda btn_suggestion_ref: self. focus_on_airport(btn_suggestion_ref)) self.suggestions_dropdown.add_widget(btn_suggestion) self.suggestions_dropdown.bind( on_select=lambda instance, btn_suggestion_ref: setattr( self.airports_search_bar, 'text', btn_suggestion_ref)) self.suggestions_dropdown.open(self.airports_search_bar) self.airports_search_bar.bind( on_parent=self.suggestions_dropdown.dismiss) def focus_on_airport(self, btn_suggestion): """ Focuses the map's current field of view on the chosen airport. :param btn_suggestion: The button carrying the airport's information. :return: None """ self.locations_map.remove_airports() self.locations_map.remove_airplanes() self.suggestions_dropdown.select(btn_suggestion.text) self.locations_map.zoom = 10 self.locations_map.center_on(btn_suggestion.data[15], btn_suggestion.data[16]) self.airports_search_bar.focus = False self.locations_map.focus_on_airport = True self.locations_map.focus_on_airplane = True #self.locations_map.add_airport(btn_suggestion.data) Thread(target=self.app.data_manager.get_potential_collisions, args=( self.app.data_manager.collision_forecaster. get_potential_collisions_from_airport, (btn_suggestion.data[15], btn_suggestion.data[16]), )).start() self.locations_map.get_locations_in_fov(airport_focus=True, airplane_focus=True) def get_airplane_suggestions(self): """ Renders the airplanes suggestions as options within a drop-down menu based on the text given by the user within the airplanes search bar. :return: None """ if not self.airplanes_search_bar.focus: # If the function gets called after the user has chosen option, self.suggestions_dropdown.dismiss() # hide drop-down. return else: # else, if the function is called to select option, self.suggestions_dropdown.dismiss() # hide previous drop-down. self.suggestions_dropdown = DropDown() airplanes_data = self.app.data_manager.airplanes_tree_manager.get_in_order_list( self.app.data_manager.airplanes_tree, self.airplanes_search_bar.text.upper()) airplane_id_index = self.app.data_manager.airplanes_tree_manager.index if airplanes_data is None: btn_suggestion = Button(text='NOT FOUND', size_hint_y=None, height=44) self.suggestions_dropdown.add_widget(btn_suggestion) else: for airplane_data in airplanes_data: btn_suggestion = DataButton( data=airplane_data, text=airplane_data[airplane_id_index], size_hint_y=None, height=44) btn_suggestion.bind(on_release=lambda btn_suggestion_ref: self. focus_on_airplane(btn_suggestion_ref)) self.suggestions_dropdown.add_widget(btn_suggestion) self.suggestions_dropdown.bind( on_select=lambda instance, btn_suggestion_ref: setattr( self.airplanes_search_bar, 'text', btn_suggestion_ref)) self.suggestions_dropdown.open(self.airplanes_search_bar) self.airplanes_search_bar.bind( on_parent=self.suggestions_dropdown.dismiss) def focus_on_airplane(self, btn_suggestion): """ Focuses the map's current field of view on the chosen airplane. :param btn_suggestion: The button carrying the airplane's information. :return: None """ self.locations_map.remove_airports() self.locations_map.remove_airplanes() self.suggestions_dropdown.select(btn_suggestion.text) self.locations_map.zoom = 10 self.locations_map.center_on(btn_suggestion.data[6], btn_suggestion.data[7]) self.airports_search_bar.focus = False self.locations_map.focus_on_airplane = True self.locations_map.focus_on_airport = True #self.locations_map.add_airplane(btn_suggestion.data) Thread(target=self.app.data_manager.get_potential_collisions, args=( self.app.data_manager.collision_forecaster. get_potential_collisions_from_plane, btn_suggestion.data[0], )).start() self.locations_map.get_locations_in_fov(airplane_focus=True, airport_focus=True) @staticmethod def open_settings_window(): """ Opens the settings window. :return: None """ settings_window = ModalView(size_hint=(0.5, 0.5), auto_dismiss=False) settings_window.add_widget(SettingsView(settings_window)) settings_window.open() def close_app(self): """ Cleans the airplanes database information, deletes the rotated airplanes images and closes the application. :return: None """ BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, "..", "DATA", "AIRCRAFT_COLLISION_FORECAST_SYSTEM.db") clean_table(db_path, 'AIRPLANES') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) img_path = os.path.join(BASE_DIR, "..", "GUI", "IMAGE") # img_path = 'GUI\\IMAGE\\' img_file_names = [ file_name for file_name in listdir(img_path) if isfile(join(img_path, file_name)) ] for file_name in img_file_names: if file_name not in ('map_marker.png', 'airplane_marker.png', 'collision_marker.png'): os.remove(os.path.join(img_path, file_name)) print('Closing app') self.app.root_window.close()
class CreateGroup(Popup): ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the CreateGroup class. # This function creates the layout for the popup as well as initializes all the # popup attributes. # # @params # (CreateGroup) self This instance of CreateGroup # (Various) **kwargs Arguments for constuction of internal Popup object ## def __init__(self, **kwargs): self.layout = FloatLayout(size=(Window.width, 200)) super(CreateGroup, self).__init__(title='Add Group', content=self.layout, size_hint=(None,None), size=(400,200), background=BKGD_DCHRC, pos_hint={"center_x":.5, 'top':.7}, auto_dismiss=False, **kwargs) ## # Class Method: draw_layout # ------------------------- # This method creates the entire layout for the create group popup by calling functions to create # the group name text box, create the users dropdown, and the add or cancel buttons # # @params # (CreateGroup) self This instance of CreateGroup ## def draw_layout(self): self.dropdown = DropDown(auto_width=False, width=180, max_height=180, on_dismiss=self.display_num_down) self.dropdown.main_button = HoverButton(text="Select Users", size=(180,30), size_hint=(None,None), pos_hint={"center_x":.5, 'top':.65}, button_down=DD_DCHRC[1], button_up=DD_DCHRC[0], on_release=self.display_label) self.group_name = TextInput(size_hint=(None, None), size=(250, 30), pos_hint={'center_x':.5, 'top':.91}, hint_text='Group Name', multiline=False) self.layout.add_widget(self.group_name) self.layout.add_widget(self.dropdown.main_button) self.add_group_dropdown() self.layout.add_widget(HoverButton(text="Add", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.7, 'top':.35}, on_press=self.add_group)) self.layout.add_widget(HoverButton(text="Cancel", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.3, 'top':.35}, on_press=self.dismiss)) ## # Class Method: open_popup # ------------------------ # This method is called to clear the widgets of the current popup layout and redraw the # layout according to the current situation. # # @params # (CreateGroup) self This instance of CreateGroup ## def open_popup(self): self.layout.clear_widgets() self.draw_layout() self.open() ## # Class Method: display_num_down # ------------------------------ # This method displays the number of users selected in the dropdown on the mainbutton # and creates all of the ToggleButtons for all of the users # # @params # (CreateGroup) self This instance of CreateGroup # (DropDown) instance This is the dropdown that calls this function on_dismiss ## def display_num_down(self, instance): num_down = 0 for user_panel in self.dropdown.container.children: for user in user_panel.children: if type(user) == ToggleButton: if user.state == 'down': num_down += 1 if num_down == 1: self.dropdown.main_button.text = str(num_down) + " User Selected" else: self.dropdown.main_button.text = str(num_down) + " Users Selected" for child in self.layout.children: if type(child) == Label and child.text == 'Priority': self.layout.remove_widget(child) ## # Class Method: display_label # --------------------------- # This method displays the label priority when the popup opens for clarification of the text boxes # in the ToggleButtons # # @params # (CreateGroup) self This instance of CreateGroup # (HoverButton) instance This is the main button for the dropdown ## def display_label(self, instance): self.dropdown.open(self.dropdown.main_button) self.layout.add_widget(Label(text="Priority", size_hint=(None,None), size = (40,20), font_size=9, pos_hint={'center_x':.7, 'top':.56})) ## # Class Method: add_group_dropdown # -------------------------------- # This method adds all of the ToggleButtons to the dropdown # # @params # (CreateGroup) self This instance of CreateGroup ## def add_group_dropdown(self): all_users = database.get_all_users() for user in all_users: user_tog = UserToggle(user) self.dropdown.add_widget(user_tog) ## # Class Method: add_group # ----------------------- # This method adds all of the selected users to a group with the name stored in the group name text input. # If no users are selected or no group name is provided, and error label appears to inform the end user # # @params # (CreateGroup) self This instance of CreateGroup # (HoverButton) instance The button pressed in order to call add_group ## def add_group(self, instance): if self.group_name.text == '': for child in self.layout.children: if type(child) == Label and child.text == "Please Insert a Group Name and Select Group Members": self.content.remove_widget(child) self.content.add_widget(Label(text="Please Insert a Group Name and Select Group Members", size_hint=(None,None), font_size=12, color=(1,0,0,1), pos_hint={'center_x':.5, 'top':1.8})) else: names_selected = False for user_panel in self.dropdown.container.children: for user in user_panel.children: if type(user) == ToggleButton and user.state == 'down': names_selected = True database.add_group_member(user.text, self.group_name.text, user_panel.priority_text.text) if not names_selected: for child in self.layout.children: if type(child) == Label and child.text == "Please Insert a Group Name and Select Group Members": self.content.remove_widget(child) self.content.add_widget(Label(text="Please Insert a Group Name and Select Group Members", size_hint=(None,None), font_size=12, color=(1,0,0,1), pos_hint={'center_x':.5, 'top':1.8})) else: self.dismiss() manager.menu.show_groups()
class MainBox(BoxLayout): def __init__(self, **kwargs): super(MainBox, self).__init__(**kwargs) self.main_area = self.ids.main_area self.search = self.ids.search self.drop_down = DropDown() self.drop_down.auto_dismiss = False self.round_button = RoundButton() self.round_button.direction = '>' self.main_cols = 1 self.refresh_main_area() def refresh_search_actions(self, search_text): self.drop_down.clear_widgets() btn = SearchButton(text='Create new action', size_hint_y=None, height=Window.height / 10) btn.bind(on_press=self.create_new_action) self.drop_down.add_widget(btn) for action in db.actions(search_text): line = SearchLine() line.ids.action.text = str(action[0]) line.ids.action.bind(on_press=self.choose_search_action) self.drop_down.add_widget(line) def choose_search_action(self, instance): self.drop_down.dismiss() self.append_current_action(instance.text, False) self.refresh_main_area() self.search.text = "" def show_search_actions(self, focused): if focused: try: self.drop_down.open(self.search) except WidgetException: # Возникает в случае, когда несколько раз вызывается открытие виджета pass else: self.drop_down.dismiss() def create_new_action(self, instance): if self.search.text == "": self.drop_down.dismiss() return db.create_new_action(self.search.text) self.choose_search_action(self.search) @staticmethod def append_current_action(action, in_progress=True): db.append_current_action(datetime.now(), action, in_progress) def refresh_main_area(self): self.main_area.clear_widgets() actions = db.current_actions() self.set_cols(len(actions)) for action in actions: act_butt = MyActionButton( text=str(action[1]), state='down' if action[2] == 'True' else 'normal') act_butt.date_start = action[0] act_butt.my_parent = self self.main_area.add_widget(act_butt) def set_cols(self, qty): if qty > 5: self.main_cols = 2 else: self.main_cols = 1