示例#1
0
class PopList(TwoLineListItem):
    def __init__(self,**kwargs):
        super(PopList,self).__init__(**kwargs)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            print(str(self.text))
            content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="{}".format(self.secondary_text),
                          size_hint_y=None,
                          valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="{}".format(self.text),
                                   content=content,
                                   size_hint=(.9, None),
                                   height=dp(300),
                                   auto_dismiss=False)

            self.dialog.add_action_button("Dismiss",
                                          action=lambda *x: self.dialog.dismiss())
            self.dialog.open()

        super(PopList, self).on_touch_down(touch)
示例#2
0
    def insert_data(self):
        con = sqlite3.connect(self.mainwid.DB_PATH)
        cursor = con.cursor()
        d1 = self.ids.dono.text
        d2 = self.ids.marca.text
        d3 = self.ids.defeito.text
        d4 = self.ids.preco.text
        d5 = self.ids.data_in.text
        d6 = self.ids.data_out.text
        a1 = (d1, d2, d3, d4, d5, d6)
        s1 = 'INSERT INTO products(Dono, Marca, Defeito, Preco, Data_in, Data_out)'
        s2 = 'VALUES("%s", "%s", "%s", %s, "%s", "%s")' % a1

        try:
            cursor.execute(s1 + ' ' + s2)
            con.commit()
            con.close()
            self.mainwid.transition.direction = 'right'
            self.mainwid.goto_list_item()
            self.show_snackbar()
        except Exception as e:
            dialog = MDDialog(
                title='Oops',
                size_hint=(.8, .4),
                text='Certifique-se que os dados fornecidos estao corretos',
                events_callback=self.close_dialog)
            dialog.open()
            con.close()
示例#3
0
def dialog(font_style='Body1',
           theme_text_color='Secondary',
           title='Title',
           text='Text',
           valign='top',
           dismiss=True,
           buttons=None,
           ref_callback=None,
           height=dp(200)):
    '''Вывод диалоговых окон.'''

    if buttons is None:
        buttons = []

    content = MDLabel(font_style=font_style,
                      theme_text_color=theme_text_color,
                      text=text,
                      valign=valign,
                      markup=True)
    content.bind(size=content.setter('text_size'))
    if ref_callback:
        content.bind(on_ref_press=ref_callback)

    dialog = MDDialog(title=title,
                      content=content,
                      size_hint=(.8, None),
                      height=height,
                      auto_dismiss=dismiss)

    for list_button in buttons:
        text_button, action_button = list_button
        dialog.add_action_button(text_button, action=action_button)
    dialog.open()

    return dialog
示例#4
0
class RemoveButton(IRightBodyTouch, MDIconButton):
    name = StringProperty()

    def remove_anime_from_list(x, self, anime_to_remove):
        x.parent.parent.parent.remove_widget(x.parent.parent)
        if anime_to_remove in Global.ANIME_CONFIRM_LIST:
            Global.ANIME_CONFIRM_LIST.remove(anime_to_remove)

        self.dismiss()

    def on_release(self):
        anime_to_remove = self.parent.parent.text
        self.dialog3 = MDDialog(title='Are you sure you want to remove ' +
                                anime_to_remove +
                                ' anime from your watchlist?',
                                size_hint=(.8, None),
                                height=dp(150),
                                auto_dismiss=False)

        self.dialog3.add_action_button(
            "Actually....", action=lambda *x: self.dialog3.dismiss())
        self.dialog3.add_action_button(
            "Im Sure!",
            action=lambda *x: self.remove_anime_from_list(
                self.dialog3, anime_to_remove))
        self.dialog3.open()

        pass
示例#5
0
 def change_data(self):
     con = sqlite3.connect(self.mainwid.DB_PATH)
     cursor = con.cursor()
     d1 = self.ids.dono.text
     d2 = self.ids.marca.text
     d3 = self.ids.defeito.text
     d4 = self.ids.preco.text
     d5 = self.ids.data_in.text
     d6 = self.ids.data_out.text
     a1 = (d1, d2, d3, d4, d5, d6)
     s1 = 'UPDATE products SET'
     s2 = 'Dono="%s", Marca="%s", Defeito="%s", Preco=%s, Data_in="%s", Data_out="%s"' % a1
     s3 = 'WHERE ID=%s' % self.data_id
     try:
         cursor.execute(s1 + ' ' + s2 + ' ' + s3)
         con.commit()
         con.close()
         self.mainwid.transition.direction = 'right'
         self.mainwid.goto_list_item()
         self.show_snackbar()
     except Exception as e:
         dialog = MDDialog(
             title='Oops',
             size_hint=(.8, .4),
             text='Certifique-se que os dados fornecidos estao corretos',
             events_callback=self.close_dialog)
         dialog.open()
         con.close()
示例#6
0
def dialog(font_style='Body1', theme_text_color='Secondary', title='Title',
           text='Text', valign='top', dismiss=True, buttons=None,
           use_check=False, text_check='', height=300, size_hint=(.85, None),
           ref_callback=None, check_callback=None):
    '''Вывод диалоговых окон.'''

    if buttons is None:
        buttons = []

    text_dialog = MDLabel(
        font_style=font_style, theme_text_color=theme_text_color,
        text=text, valign=valign, markup=True,
        size_hint_y=None
    )
    dialog = MDDialog(
        title=title, content=text_dialog, size_hint=size_hint,
        auto_dismiss=dismiss, height=dp(height)
    )

    text_dialog.bind(texture_size=text_dialog.setter('size'))
    if ref_callback:
        text_dialog.bind(on_ref_press=ref_callback)

    if use_check:
        selection = Selection(text=text_check)
        if check_callback:
            selection.callback = check_callback
        dialog.children[0].children[1].add_widget(selection)

    for list_button in buttons:
        text_button, action_button = list_button
        dialog.add_action_button(text_button, action=action_button)
    dialog.open()

    return dialog
示例#7
0
 def show_error_dialog(self, errors):
     content = MDLabel(text='\n\n' + '\n'.join(errors),
                       padding=(10, 10),
                       theme_text_color='Error')
     dialog = MDDialog(title='Errors', content=content, size_hint=(.75, .5))
     dialog.add_action_button('close', dialog.dismiss)
     dialog.open()
示例#8
0
    def set_address_dialog(self):
        def save_apply_address(*args):

            m = re.match(r'([0-9a-zA-Z\.]+):([0-9]+)', addr_field.text)

            if m is not None:
                self.set_scoreboard_address(addr_field.text)
                dialog.dismiss()
            else:
                # don't know what to do
                pass

        addr_field = MDTextField(hint_text='adress:port')
        if self._unformatted_address is not None:
            addr_field.text = self._unformatted_address
        contents = addr_field

        dialog = MDDialog(title='Set Scoreboard Address',
                          content=contents,
                          size_hint=(0.5, 0.5),
                          auto_dismiss=True)

        dialog.add_action_button("Save & Apply", action=save_apply_address)

        dialog.open()
示例#9
0
def error_pop(matter):
	content = MDLabel(font_style='Body1',theme_text_color='Secondary',text=matter,size_hint_y=None,valign='top')
	content.bind(texture_size=content.setter('size'))
	dialog2 = MDDialog(title="Error",content=content,size_hint=(.8, None),height=dp(200),auto_dismiss=False)
	dialog2.add_action_button("Dismiss",action=lambda *x:dialog2.dismiss())
	dialog2.open()
#This PC\Lenovo K8 Plus\SanDisk SD card\Android\data\org.coursera.android\files\Download
示例#10
0
    def add_user(self):
        con = sqlite3.connect(self.mainwid.DB_PATH)
        cursor = con.cursor()
        d1 = self.ids.usr_field.text
        d2 = self.ids.email_field.text
        d3 = self.ids.pwd_field.text
        d4 = self.ids.calendar_field.text
        a1 = (d1, d2, d3, d4)
        s1 = 'INSERT INTO user(Usuario, Email, Senha, Data)'
        s2 = 'VALUES("%s", "%s", "%s", %s)' % a1

        try:
            cursor.execute(s1 + ' ' + s2)
            con.commit()
            con.close()
            self.mainwid.transition.direction = 'right'
            self.mainwid.goto_start()
            self.dialogs()
        except Exception as e:
            dialog = MDDialog(
                title='Oops',
                size_hint=(.8, .4),
                text='Certifique-se que os dados fornecidos estao corretos',
                events_callback=self.close_dialog)
            dialog.open()
            con.close()
示例#11
0
文件: tmdb.py 项目: Arias800/exode
 def connect(self):
     dialog = MDDialog(
         title='Connexion',
         size_hint=(.8, .3),
         text_button_ok='Yes',
         text="Votre navigateur va s'ouvrir pour autoriser la connexion",
         text_button_cancel='Cancel',
         events_callback=self.getToken)
     dialog.open()
class CalculatorApp(App):
    theme_cls = ThemeManager()
    theme_cls.theme_style = 'Dark'
    nav_drawer = ObjectProperty()
    
           
    def build(self):
        self.content_widgets = Content()
        return self.content_widgets

    def get_value(self, text):
        self.value = text
        calculator = ComplexCalculator()
       
        result,initial_expression = calculator.calculate(text)
        
        if(result == False):
           self.error_dialog()
        else:
            expression_show = ' '.join([str(elem) for elem in initial_expression ])   
            self.success_dialog(result,expression_show)
    

    def success_dialog(self,result,expression_show):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Expresion ingresada:  "+str(expression_show),
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Resultado:  "+str(result),
                               content=content,
                               size_hint=(.8, None),
                               height=100,
                               auto_dismiss=False)

        self.dialog.add_action_button("Cerrar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        
    def error_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Error al ingresar la expresión",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Error",
                               content=content,
                               size_hint=(.8, None),
                               height=100,
                               auto_dismiss=False)

        self.dialog.add_action_button("Cerrar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#13
0
 def show_dialog(self):
     my_dialog = MDDialog(
         title='About the App',
         text=
         'This app is for level advisers only, it enables communication between student and their respective level coodinators',
         size_hint=[.8, .4],
         auto_dismiss=False,
         events_callback=self.my_callback,
         text_button_ok='I understand')
     my_dialog.open()
示例#14
0
 def show_dialoghelp(self):
     my_dialog = MDDialog(
         title='What is this ?',
         text=
         'To send a message, you have to provide the receivers username, you can also send to multiple users by seperating their usernames with a comma (,)',
         size_hint=[.8, .4],
         auto_dismiss=False,
         events_callback=self.my_callback,
         text_button_ok='Ok perfect !')
     my_dialog.open()
示例#15
0
class Patron(ToolbarScreen):
    def __init__(self, **opt):
        super(Patron, self).__init__(**opt)

    def show_dialog(self, *args):
        button = MDFlatButton(text='OK')
        self.dialog = MDDialog(size_hint=(0.5, 0.4),
                               auto_dismiss=False,
                               pos_hint={"center_x": 0.5},
                               title="Material to be returned",
                               content=button)
        button.bind(on_press=self.dialog.dismiss)
        self.dialog.open()
示例#16
0
class DisposalList(MDList):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.refresh_list()

    def refresh_list(self):
        #обновление списка задач
        try:
            res = GetResult('getDisposalList', {'readed': 0}, [
                'Number', 'Theme', 'ShortTask', 'Sender_id', 'Receiver_id',
                'Task', 'isExecute'
            ])

            for i in res:
                # текст задачи
                if i[2] != '':
                    disposal_text = i[2]
                else:
                    disposal_text = 'ПУСТО'
                # иконка выполнения
                if i[6] == '0':
                    icon_text = 'clock'
                else:
                    icon_text = 'calendar-check'

                # номер + тема задачи
                theme_text = (i[0] + ' ' + i[1])
                if len(theme_text) > 30:
                    theme_text = theme_text[:27] + '...'

                item = DisposalItem(text=theme_text,
                                    secondary_text=disposal_text,
                                    icon_text=icon_text,
                                    data=i)
                self.add_widget(item)
        except:
            #сообщение об ошибке
            content = MDLabel(font_style='Body1',
                              text='Не подключения, проверьте настройки!',
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="Внимание",
                                   content=content,
                                   size_hint=(.8, None),
                                   height=dp(200))

            self.dialog.add_action_button(
                "ОК", action=lambda *x: self.dialog.dismiss())
            self.dialog.open()
示例#17
0
def dialog(font_style='Body1',
           theme_text_color='Secondary',
           title='Title',
           text='Text',
           valign='top',
           dismiss=True,
           buttons=None,
           use_check=False,
           text_check='',
           height=300,
           size_hint=(.85, None),
           ref_callback=None,
           check_callback=None):
    '''Вывод диалоговых окон.'''

    if buttons is None:
        buttons = []

    text_dialog = MDLabel(font_style=font_style,
                          theme_text_color=theme_text_color,
                          text=text,
                          valign=valign,
                          markup=True,
                          size_hint_y=None)
    dialog = MDDialog(title=title,
                      content=text_dialog,
                      size_hint=size_hint,
                      auto_dismiss=dismiss,
                      height=dp(height))

    text_dialog.bind(texture_size=text_dialog.setter('size'))
    if ref_callback:
        text_dialog.bind(on_ref_press=ref_callback)

    if use_check:
        selection = Selection(text=text_check)
        if check_callback:
            selection.callback = check_callback
        dialog.children[0].children[1].add_widget(selection)

    for list_button in buttons:
        text_button, action_button = list_button
        dialog.add_action_button(text_button, action=action_button)
    dialog.open()

    return dialog
示例#18
0
class TelaVisualizarContato(Screen):
    cheaderwidget = ObjectProperty()
    contato = ObjectProperty()

    def __init__(self, contato_id, **kwargs):
        self.app = App.get_running_app()
        self.contato = ContatoModel[contato_id]

        super(TelaVisualizarContato, self).__init__(**kwargs)

    def on_pre_enter(self, *args):
        toolbar = self.app.root.ids['toolbar']
        toolbar.title = s.perfil.capitalize()
        toolbar.left_action_items = [[
            'arrow-left',
            lambda x: self.app.root.switch_to(TELAS.LISTA_CONTATO)
        ]]
        toolbar.right_action_items = [[
            'delete', lambda x: self.delete_contact()
        ]]

    def delete_contact(self):
        content = MDLabel(
            text=
            "Tem certeza que quer excluir este contato?\nEsta ação não tem retorno.",
            font_style='Caption',
            size_hint_y=None,
            valign='center')
        self.dialog = MDDialog(title="Excluir Contato.",
                               content=content,
                               size_hint=(0.8, None),
                               height=dp(300),
                               auto_dismiss=True)
        self.dialog.add_action_button("Confirmar",
                                      action=lambda *x: self.confirm_delete())
        self.dialog.add_action_button("Cancelar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def confirm_delete(self):
        self.dialog.dismiss()
        db(ContatoModel.id == self.contato.id).delete()
        self.app.root.switch_to(TELAS.LISTA_CONTATO)
示例#19
0
    def login(self):
        con = sqlite3.connect(self.mainwid.DB_PATH)
        cursor = con.cursor()
        d1 = self.ids.user_field.text
        d2 = self.ids.pwd_field.text
        a1 = (d1, d2)
        s1 = 'SELECT * FROM user WHERE Usuario = ? and Senha = ?'

        cursor.execute(s1, a1)
        result = cursor.fetchall()
        if result:
            self.mainwid.transition.direction = 'left'
            self.mainwid.goto_list_item()
        else:
            dialog = MDDialog(
                title='Oops',
                size_hint=(.8, .3),
                text="[color=#FF0000] Usuario ou Senha Invalido [/color]",
                events_callback=self.close_dialog)
            dialog.open()
示例#20
0
 def Popup(self, *args):
     Isinput = args[0]
     if Isinput != True:
         popup = MDDialog(
             title=f'{args[1]}',
             text=f'[color=%s][b]{args[2]}[/b][/color]' %
             get_hex_from_color(main.KivyGUI.theme_cls.primary_color),
             events_callback=self.callback,
             size_hint=(.5, .5),
             text_button_ok='Ok',
             text_button_cancel='Cancel')
         popup.open()
     elif Isinput == True:
         popup = MDInputDialog(title=f'{args[1]}',
                               events_callback=self.callback,
                               size_hint=(.8, .4),
                               text_button_ok='Sent',
                               hint_text='Hint text')  # .8, .4
         self.open2ndScreen("screen_main")
         popup.open()
示例#21
0
文件: tmdb.py 项目: Arias800/exode
    def getToken(self, *args):
        if args[0] == 'Yes':
            import webbrowser

            url = 'https://api.themoviedb.org/3/authentication/token/new?api_key=%s' % (
                self.api_key)

            req = requests.get(url)
            results = req.json()
            if results['request_token']:
                self.request_token = results['request_token']
                url = 'https://www.themoviedb.org/authenticate/' + self.request_token
                webbrowser.open(url)

                dialog = MDDialog(title='Connexion',
                                  size_hint=(.8, .3),
                                  text_button_ok='Yes',
                                  text="Ete vous connecter ?",
                                  text_button_cancel='Cancel',
                                  events_callback=self.callback)
                dialog.open()
示例#22
0
class BodyScanApp(App):
	theme_cls = ThemeManager()
	nav_drawer = ObjectProperty()
	username = StringProperty("")
	rights = StringProperty("")

	def showAddUserdialog(self):
		content = AddUserContent()
		self.dialog = MDDialog(title="Add Friend/Coach",
								content=content,
								size_hint=(.8, None),
								height=dp(200),
								auto_dismiss=False)
		self.dialog.add_action_button("Dismiss",
										action=lambda
										*x: self.dialog.dismiss())
		self.dialog.open()

	def build(self):
		self.nav_drawer = BodyScanNavDrawer()
		self.theme_cls.primary_palette = "Blue"
		self.theme_cls.primary_hue = "500"
示例#23
0
class QuoteButton(TwoLineListItem):
    def __init__(self, **kwargs):
        super(QuoteButton, self).__init__(**kwargs)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            if touch.is_double_tap:
                print('doouble')
            else:
                content = MDLabel(font_style='Body1',
                                  theme_text_color='Secondary',
                                  text="{}".format(self.secondary_text),
                                  valign='top')

                content.bind(size=content.setter('text_size'))
                self.dialog = MDDialog(title="{}".format(self.text),
                                       content=content,
                                       size_hint=(.9, None),
                                       height=dp(200),
                                       auto_dismiss=False)

                self.dialog.add_action_button(
                    "Dismiss", action=lambda *x: self.dialog.dismiss())
                self.dialog.add_action_button("Share",
                                              action=lambda *x: self.share())
                self.dialog.open()
        super(QuoteButton, self).on_touch_down(touch)

    def share(self):
        print 'sharing'
        intent = Intent()
        intent.setAction(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_TEXT,
                        String('{}'.format(self.secondary_text)))
        intent.setType('text/plain')
        chooser = Intent.createChooser(intent, String('Share...'))
        PythonActivity.mActivity.startActivity(chooser)
示例#24
0
class AddCommentButton(MDFloatingActionButton):

    def commit(self):
        if self.dialog.content.text.strip() != "":
            GetResult('SendComment', {'disposal_id': int(self.parent.parent.ids.number.text), 'comment': self.dialog.content.text.strip()}, [])
            self.dialog.dismiss()
            self.parent.parent.load_comments()

    def on_press(self):
        content = MDTextField()
        content.multiline = True
        content.hint_text = "Введите комментарий"
        content.focus = True
        self.dialog = MDDialog(title="Новый комментарий",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(400))

        self.dialog.add_action_button("Сохранить",
                                      action=lambda *x: self.commit())
        self.dialog.add_action_button("Отмена",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#25
0
    def assign_game_id_dialog(self):
        def apply_game_id(*args):
            # do apply
            gid = id_field.text

            # do some processing
            if len(id_field.text) == 0:
                return

            self.assign_game_user_id(gid)
            dialog.dismiss()

        id_field = MDTextField(hint_text='Identifier')

        if self._user_id is not None:
            id_field.text = self._user_id

        dialog = MDDialog(title='Set Game Identifier',
                          content=id_field,
                          size_hint=(0.5, 0.5),
                          auto_dismiss=True)
        dialog.add_action_button('Apply', action=apply_game_id)

        dialog.open()
示例#26
0
class MyApp(App):
    theme_cls = ThemeManager()
    nav_drawer = ObjectProperty()

    def build(self):
        print('here we start')
        # self.theme_cls.theme_style = 'Dark'
        # self.show_example_dialog()
        # self.show_menu()
        return RootScreen()

    def test(self):
        print('here we go')

    def show_menu(self):
        self.nav_drawer = MyNavDrawer()
        self.nav_drawer.toggle()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                               "That's pretty awesome right!",
                          valign='top')

        content.bind(size=content.setter('text_size'))
        self.dialog = MDDialog(title="This is a pretty dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda
                                          *x: self.dialog.dismiss())
        self.dialog.open()
示例#27
0
class KitchenSink(App, Screens):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Blue'
    previous_date = ObjectProperty()
    title = "Kitchen Sink"
    theme_cls.primary_palette = 'Blue'

    # theme_cls.theme_style = 'Dark'

    def __init__(self, **kwargs):
        super(KitchenSink, self).__init__(**kwargs)

        self.menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Example item %d' % i,
            'callback': self.callback_for_menu_items
        } for i in range(15)]
        self.Window = Window
        self.manager = None
        self.md_theme_picker = None
        self.long_dialog = None
        self.input_dialog = None
        self.alert_dialog = None
        self.ok_cancel_dialog = None
        self.long_dialog = None
        self.dialog = None
        self.manager_open = False
        self.cards_created = False
        self.user_card = None
        self.bs_menu_1 = None
        self.bs_menu_2 = None
        self.tick = 0
        self.create_stack_floating_buttons = False
        self.previous_text =\
            "Welcome to the application [b][color={COLOR}]Kitchen Sink"\
            "[/color][/b].\nTo see [b][color={COLOR}]KivyMD[/color][/b] "\
            "examples, open the menu and select from the list the desired "\
            "example\n\n"\
            ""\
            ""\
            "Author - [b][color={COLOR}]Andrés Rodríguez[/color][/b]\n"\
            "[u][b][color={COLOR}][email protected][/color]"\
            "[/b][/u]\n\n"\
            "Author this Fork - [b][color={COLOR}]Ivanov Yuri[/color][/b]\n"\
            "[u][b][color={COLOR}][email protected][/color]"\
            "[/b][u]".format(COLOR=get_hex_from_color(
                self.theme_cls.primary_color))
        self.names_contacts = ('Alexandr Taylor', 'Yuri Ivanov',
                               'Robert Patric', 'Bob Marley', 'Magnus Carlsen',
                               'Jon Romero', 'Anna Bell', 'Maxim Kramerer',
                               'Sasha Gray', 'Vladimir Ivanenko')
        Window.bind(on_keyboard=self.events)
        crop_image(
            (Window.width, int(dp(Window.height * 35 // 100))),
            '{}/assets/guitar-1139397_1280.png'.format(self.directory),
            '{}/assets/guitar-1139397_1280_crop.png'.format(self.directory))

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        if not os.path.exists(os.path.join(self.directory,
                                           path_to_crop_image)):
            size = (int(size[0]), int(size[1]))
            path_to_origin_image = path_to_crop_image.replace('_tile_crop', '')
            crop_image(size, path_to_origin_image, path_to_crop_image)
        instance.source = path_to_crop_image

    def theme_picker_open(self):
        if not self.md_theme_picker:
            from kivymd.theme_picker import MDThemePicker
            self.md_theme_picker = MDThemePicker()
        self.md_theme_picker.open()

    def example_add_stack_floating_buttons(self):
        from kivymd.stackfloatingbuttons import MDStackFloatingButtons

        def set_my_language(instance_button):
            toast(instance_button.icon)

        if not self.create_stack_floating_buttons:
            screen = self.main_widget.ids.scr_mngr.get_screen('stack buttons')
            screen.add_widget(
                MDStackFloatingButtons(icon='lead-pencil',
                                       floating_data={
                                           'Python': 'language-python',
                                           'Php': 'language-php',
                                           'C++': 'language-cpp'
                                       },
                                       callback=set_my_language))
            self.create_stack_floating_buttons = True

    def set_accordion_list(self):
        from kivymd.accordionlistitem import MDAccordionListItem

        def callback(text):
            toast('{} to {}'.format(text, content.name_item))

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.accordion_list.ids.anim_list.add_widget(
                MDAccordionListItem(content=content,
                                    icon='assets/kivymd_logo.png',
                                    title=name_contact))

    def set_chevron_back_screen(self):
        """Sets the return chevron to the previous screen in ToolBar."""

        self.main_widget.ids.toolbar.right_action_items = [[
            'dots-vertical', lambda x: self.root.toggle_nav_drawer()
        ]]

    def download_progress_hide(self, instance_progress, value):
        """Hides progress progress."""

        self.main_widget.ids.toolbar.right_action_items =\
            [['download',
              lambda x: self.download_progress_show(instance_progress)]]

    def download_progress_show(self, instance_progress):
        self.set_chevron_back_screen()
        instance_progress.open()
        instance_progress.animation_progress_from_fade()

    def show_example_download_file(self, interval):
        from kivymd.progressloader import MDProgressLoader

        def get_connect(host="8.8.8.8", port=53, timeout=3):
            import socket
            try:
                socket.setdefaulttimeout(timeout)
                socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
                    (host, port))
                return True
            except (TimeoutError, ConnectionError, OSError):
                return False

        if get_connect():
            link = 'https://www.python.org/ftp/python/3.5.1/'\
                   'python-3.5.1-embed-win32.zip'
            progress = MDProgressLoader(
                url_on_image=link,
                path_to_file=os.path.join(self.directory, 'python-3.5.1.zip'),
                download_complete=self.download_complete,
                download_hide=self.download_progress_hide)
            progress.start(self.download_file.ids.box_flt)
        else:
            toast('Connect error!')

    def download_complete(self):
        self.set_chevron_back_screen()
        toast('Done')

    def file_manager_open(self):
        from kivymd.filemanager import MDFileManager
        from kivymd.dialog import MDDialog

        def open_file_manager(text_item, dialog):
            previous = False if text_item == 'List' else True
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(exit_manager=self.exit_manager,
                                              select_path=self.select_path,
                                              previous=previous)
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(self.user_data_dir)
            self.manager_open = True
            self.manager.open()

        MDDialog(title='Title',
                 size_hint=(.8, .4),
                 text_button_ok='List',
                 text="Open manager with 'list' or 'previous' mode?",
                 text_button_cancel='Previous',
                 events_callback=open_file_manager).open()

    def select_path(self, path):
        """It will be called when you click on the file name
        or the catalog selection button.

        :type path: str;
        :param path: path to the selected directory or file;

        """

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        """Called when the user reaches the root of the directory tree."""

        self.manager.dismiss()
        self.manager_open = False
        self.set_chevron_menu()

    def set_chevron_menu(self):
        self.main_widget.ids.toolbar.left_action_items = [[
            'menu', lambda x: self.root.toggle_nav_drawer()
        ]]

    def events(self, instance, keyboard, keycode, text, modifiers):
        """Called when buttons are pressed on the mobile device.."""

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True

    def callback_for_menu_items(self, *args):
        toast(args[0])

    def add_cards(self, instance_grid_card):
        from kivymd.cards import MDCardPost

        def callback(instance, value):
            if value is None:
                toast('Delete post %s' % str(instance))
            elif isinstance(value, int):
                toast('Set like in %d stars' % value)
            elif isinstance(value, str):
                toast('Repost with %s ' % value)
            elif isinstance(value, list):
                toast(value[1])

        if not self.cards_created:
            self.cards_created = True
            menu_items = [{
                'viewclass': 'MDMenuItem',
                'text': 'Example item %d' % i,
                'callback': self.callback_for_menu_items
            } for i in range(2)]
            buttons = ['facebook', 'vk', 'twitter']

            instance_grid_card.add_widget(
                MDCardPost(text_post='Card with text',
                           swipe=True,
                           callback=callback))
            instance_grid_card.add_widget(
                MDCardPost(
                    right_menu=menu_items,
                    swipe=True,
                    text_post='Card with a button to open the menu MDDropDown',
                    callback=callback))
            instance_grid_card.add_widget(
                MDCardPost(likes_stars=True,
                           callback=callback,
                           swipe=True,
                           text_post='Card with asterisks for voting.'))

            instance_grid_card.add_widget(
                MDCardPost(
                    source="./assets/kitten-1049129_1280.png",
                    tile_text="Little Baby",
                    tile_font_style="Headline",
                    text_post="This is my favorite cat. He's only six months "
                    "old. He loves milk and steals sausages :) "
                    "And he likes to play in the garden.",
                    with_image=True,
                    swipe=True,
                    callback=callback,
                    buttons=buttons))

    def update_screen(self, instance):
        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.update_spinner.ids.upd_lbl.text = "New string"
                Clock.unschedule(update_screen)

        Clock.schedule_interval(update_screen, 1)

    main_widget = None

    def build(self):
        self.main_widget = Builder.load_string(main_widget_kv)
        # self.bottom_navigation_remove_mobile(self.main_widget)
        return self.main_widget

    def set_popup_screen(self, content_popup):
        popup_menu = ContentForAnimCard()
        popup_menu.add_widget(Widget(size_hint_y=None, height=dp(150)))
        popup_screen = self.popup_screen.ids.popup_screen
        popup_screen.screen = popup_menu
        popup_screen.background_color = [.3, .3, .3, 1]
        popup_screen.max_height = content_popup.ids.image.height + dp(5)

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_user_example_animation_card(self):
        from kivymd.useranimationcard import MDUserAnimationCard

        def main_back_callback():
            toast('Close card')

        if not self.user_card:
            self.user_card = MDUserAnimationCard(
                user_name="Lion Lion",
                path_to_avatar="./assets/guitar-1139397_1280.png",
                callback=main_back_callback)
            self.user_card.box_content.add_widget(ContentForAnimCard())
        self.user_card.open()

    def show_example_snackbar(self, snack_type):
        from kivymd.snackbars import Snackbar

        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()

    def show_example_input_dialog(self):
        def result(text_button, instance):
            toast(instance.text_field.text)

        if not self.input_dialog:
            from kivymd.dialog import MDInputDialog

            self.input_dialog = MDInputDialog(title='Title',
                                              hint_text='Hint text',
                                              size_hint=(.8, .4),
                                              text_button_ok='Ok',
                                              events_callback=result)
        self.input_dialog.open()

    def show_example_alert_dialog(self):
        if not self.alert_dialog:
            from kivymd.dialog import MDDialog

            self.alert_dialog = MDDialog(
                title='Title',
                size_hint=(.8, .4),
                text_button_ok='Ok',
                text="This is Alert dialog",
                events_callback=self.callback_for_menu_items)
        self.alert_dialog.open()

    def show_example_ok_cancel_dialog(self):
        if not self.ok_cancel_dialog:
            from kivymd.dialog import MDDialog

            self.ok_cancel_dialog = MDDialog(
                title='Title',
                size_hint=(.8, .4),
                text_button_ok='Ok',
                text="This is Ok Cancel dialog",
                text_button_cancel='Cancel',
                events_callback=self.callback_for_menu_items)
        self.ok_cancel_dialog.open()

    def show_example_long_dialog(self):
        if not self.long_dialog:
            from kivymd.dialog import MDDialog

            self.long_dialog = MDDialog(
                text="Lorem ipsum dolor sit amet, consectetur adipiscing "
                "elit, sed do eiusmod tempor incididunt ut labore et "
                "dolore magna aliqua. Ut enim ad minim veniam, quis "
                "nostrud exercitation ullamco laboris nisi ut aliquip "
                "ex ea commodo consequat. Duis aute irure dolor in "
                "reprehenderit in voluptate velit esse cillum dolore eu "
                "fugiat nulla pariatur. Excepteur sint occaecat "
                "cupidatat non proident, sunt in culpa qui officia "
                "deserunt mollit anim id est laborum.",
                title='Title',
                size_hint=(.8, .4),
                text_button_ok='Yes',
                events_callback=self.callback_for_menu_items)
        self.long_dialog.open()

    def get_time_picker_data(self, instance, time):
        self.pickers.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        from kivymd.time_picker import MDTimePicker

        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.get_time_picker_data)

        if self.pickers.ids.time_picker_use_previous_time.active:
            try:
                time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.pickers.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        from kivymd.date_picker import MDDatePicker

        if self.pickers.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        from kivymd.bottomsheet import MDListBottomSheet

        if not self.bs_menu_1:
            self.bs_menu_1 = MDListBottomSheet()
            self.bs_menu_1.add_item(
                "Here's an item with text only", lambda x: self.
                callback_for_menu_items("Here's an item with text only"))
            self.bs_menu_1.add_item("Here's an item with an icon",
                                    lambda x: self.callback_for_menu_items(
                                        "Here's an item with an icon"),
                                    icon='clipboard-account')
            self.bs_menu_1.add_item(
                "Here's another!",
                lambda x: self.callback_for_menu_items("Here's another!"),
                icon='nfc')
        self.bs_menu_1.open()

    def show_example_grid_bottom_sheet(self):
        if not self.bs_menu_2:
            from kivymd.bottomsheet import MDGridBottomSheet

            self.bs_menu_2 = MDGridBottomSheet()
            self.bs_menu_2.add_item(
                "Facebook",
                lambda x: self.callback_for_menu_items("Facebook"),
                icon_src='./assets/facebook-box.png')
            self.bs_menu_2.add_item(
                "YouTube",
                lambda x: self.callback_for_menu_items("YouTube"),
                icon_src='./assets/youtube-play.png')
            self.bs_menu_2.add_item(
                "Twitter",
                lambda x: self.callback_for_menu_items("Twitter"),
                icon_src='./assets/twitter.png')
            self.bs_menu_2.add_item(
                "Da Cloud",
                lambda x: self.callback_for_menu_items("Da Cloud"),
                icon_src='./assets/cloud-upload.png')
            self.bs_menu_2.add_item(
                "Camera",
                lambda x: self.callback_for_menu_items("Camera"),
                icon_src='./assets/camera.png')
        self.bs_menu_2.open()

    def set_appbar(self):
        from kivymd.toolbar import MDBottomAppBar

        def press_button(inctance):
            toast('Press Button')

        self.md_app_bar = MDBottomAppBar(
            md_bg_color=self.theme_cls.primary_color,
            left_action_items=[['menu', lambda x: x], ['clock', lambda x: x],
                               ['dots-vertical', lambda x: x]],
            anchor='right',
            callback=press_button)

    def move_item_menu(self, anchor):
        md_app_bar = self.md_app_bar
        if md_app_bar.anchor != anchor:
            if len(md_app_bar.right_action_items):
                md_app_bar.left_action_items.append(
                    md_app_bar.right_action_items[0])
                md_app_bar.right_action_items = []
            else:
                left_action_items = md_app_bar.left_action_items
                action_items = left_action_items[0:2]
                md_app_bar.right_action_items = [left_action_items[-1]]
                md_app_bar.left_action_items = action_items

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def add_icon_item(self, name_icon):
        self.main_widget.ids.scr_mngr.get_screen(
            'md icons').ids.rv.data.append({
                'viewclass':
                'MDIconItemForMdIconsList',
                'icon':
                name_icon,
                'text':
                name_icon,
                'callback':
                self.callback_for_menu_items
            })

    def set_list_md_icons(self, text='', search=False):
        self.main_widget.ids.scr_mngr.get_screen('md icons').ids.rv.data = []
        for name_icon in md_icons.keys():
            if search:
                if text in name_icon:
                    self.add_icon_item(name_icon)
            else:
                self.add_icon_item(name_icon)

    def on_pause(self):
        return True

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
示例#28
0
class KitchenSink(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "KivyMD Kitchen Sink"

    menu_items = [
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        main_widget.ids.text_field_error.bind(
            on_text_validate=self.set_error_message,
            on_focus=self.set_error_message)
        self.bottom_navigation_remove_mobile(main_widget)
        return main_widget

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_example_snackbar(self, snack_type):
        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(
                text=
                "This is a very very very very very very very long snackbar!"
            ).show()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                          "That's pretty awesome right!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def show_example_long_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Lorem ipsum dolor sit amet, consectetur "
                          "adipiscing elit, sed do eiusmod tempor "
                          "incididunt ut labore et dolore magna aliqua. "
                          "Ut enim ad minim veniam, quis nostrud "
                          "exercitation ullamco laboris nisi ut aliquip "
                          "ex ea commodo consequat. Duis aute irure "
                          "dolor in reprehenderit in voluptate velit "
                          "esse cillum dolore eu fugiat nulla pariatur. "
                          "Excepteur sint occaecat cupidatat non "
                          "proident, sunt in culpa qui officia deserunt "
                          "mollit anim id est laborum.",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a long test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def get_time_picker_data(self, instance, time):
        self.root.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        self.time_dialog = MDTimePicker()
        self.time_dialog.bind(time=self.get_time_picker_data)
        if self.root.ids.time_picker_use_previous_time.active:
            try:
                self.time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        self.time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.root.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon",
                    lambda x: x,
                    icon='clipboard-account')
        bs.add_item("Here's another!", lambda x: x, icon='nfc')
        bs.open()

    def show_example_grid_bottom_sheet(self):
        bs = MDGridBottomSheet()
        bs.add_item("Facebook",
                    lambda x: x,
                    icon_src='./assets/facebook-box.png')
        bs.add_item("YouTube",
                    lambda x: x,
                    icon_src='./assets/youtube-play.png')
        bs.add_item("Twitter", lambda x: x, icon_src='./assets/twitter.png')
        bs.add_item("Da Cloud",
                    lambda x: x,
                    icon_src='./assets/cloud-upload.png')
        bs.add_item("Camera", lambda x: x, icon_src='./assets/camera.png')
        bs.open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass
示例#29
0
class ExportTable1(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    export_object = Export()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None
    data_in_page = None

    def __init__(self, **kwargs):
        super(ExportTable1, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def delete_data(self, id):
        try:
            self.export_object.id = id
            self.export_object.delete_export()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"
        except _mysql_exceptions.IntegrityError:
            Snackbar(text=str("You Cannot Delete This Record")).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def pagination_next(self, page=1):
        self.current = int(page)
        no_pages = int(
            math.ceil(
                float(self.export_object.count_export()) / float(self.offset)))
        if self.current <= no_pages:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.export_object.get_exports_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = False
        if self.current >= no_pages:
            deactivate = True
            self.current = no_pages
        else:
            deactivate = False
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        if self.current > 0:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.export_object.get_exports_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
            self.current = 1
        if self.current == 1:
            deactivate = True
        else:
            deactivate = False
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.data_in_page.get(key)['id'])
            date = str(self.data_in_page.get(key)['date'])
            status = self.data_in_page.get(key)['status']
            destination = self.data_in_page.get(key)['destination']

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=destination))
            self.d.add_widget(DataLabel(text=date))
            self.d.add_widget(DataLabel(text=status))
            self.d.add_widget(option)

            super(ExportTable1, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, destination, date, status):
        self.export_object.id = id
        self.export_object.destination = destination
        self.export_object.date = date
        self.export_object.status = status
        self.export_object.update_export()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        dest = self.data_in_page.get(id)['destination']
        dat = str(self.data_in_page.get(id)['date'])
        stat = self.data_in_page.get(id)['status']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        destination = DialogTextInput(dest)
        date = DialogTextInput(dat)
        status = DialogTextInput(stat)

        b.add_widget(
            MDLabel(id='destination',
                    text="Destination",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(destination)
        b.add_widget(MDLabel(text="Date", size_hint_x=None, width="90px"))
        b.add_widget(date)
        b.add_widget(
            MDLabel(id='date', text="Status", size_hint_x=None, width="90px"))
        b.add_widget(status)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(id, destination.text, date.
                                                    text, status.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def add_data(self, destination, date, status):
        self.export_object.destination = destination
        self.export_object.date = date
        self.export_object.status = status
        if destination != '' and date != '' and status != '':
            self.export_object.insert_export()
        else:
            Snackbar(text=" You Need To Fill All Fields ").show()
        self.call_load()
示例#30
0
class mainapp(BoxLayout):
    def __init__(self, **kwargs):
        BoxLayout.__init__(self, **kwargs)
        self.orientation = "vertical"
        self.numpad = Builder.load_string(calc)
        self.add_widget(self.numpad)

        #Buttons
        self.out = self.numpad.ids['out']
        self.rout = self.numpad.ids['real_time_update']
        self.rout_2 = self.numpad.ids['real_time_update_2']
        self.delbutton = self.numpad.ids['cancel_but']
        self.equalbutton = self.numpad.ids['equal_but']
        self.differnbutton = self.numpad.ids['differentiate']
        self.integrabutton = self.numpad.ids['integrate']
        self.simplifybutton = self.numpad.ids['simplify']
        self.factorisebutton = self.numpad.ids['factorise']
        self.expandbutton = self.numpad.ids['expand']
        self.fractog = self.numpad.ids['fractog']
        self.solvebutton = self.numpad.ids['solve']

        #Binds
        self.delbutton.bind(on_release=self.delholdclr, on_press=self.delbut)
        self.equalbutton.bind(on_release=self.equal_call)
        self.differnbutton.bind(on_release=self.differentiate)
        self.integrabutton.bind(on_release=self.integral)
        self.simplifybutton.bind(on_release=self.simplify)
        self.factorisebutton.bind(on_release=self.factorise)
        self.expandbutton.bind(on_release=self.expand)
        self.out.bind(text=self.rout_update)
        self.rout_2.bind(text=self.rout_update)
        self.fractog.bind(active=self.rout_update)
        self.solvebutton.bind(on_release=self.solver)

        #Clock
        Clock.schedule_interval(self.outputloop, 0)

        # Coloring
        self.numpad.ids['arrow'].md_bg_color = (0.1, 0, 0, 0.1)

        for x in self.numpad.ids['basic_buts'].children:
            x.md_bg_color = (1, 0, 0, 0.2)

        for x in self.numpad.ids['functions_but'].children:
            x.md_bg_color = (0.1, 0, 0, 0.2)

        self.numpad.ids['inv'].md_bg_color = (0, 0.5, 0.5, 0.2)

        for x in self.numpad.ids['inv_tri'].children:
            x.md_bg_color = (0, 0.5, 0.5, 0.2)

        self.numpad.ids['back'].md_bg_color = (0.1, 0, 0, 0.2)

        # init() of matrix
        self.mat_init()

        # init() of limit
        self.limit_init()

        # extras
        self.pretex = '..'
        self.expr = 0

    def outputloop(self, dt):
        tex = self.out.text
        if tex == '':
            tex = '0'

        elif len(tex) > 1 and tex[:1] == '0':
            tex = tex[1:]
        self.out.text = tex

    def delbut(self, ins):
        tex = self.out.text
        tex = tex[:-1]
        self.out.text = tex
        Clock.schedule_once(self.clearall, 1)

    def clearall(self, ins):
        self.out.text = '0'

    def delholdclr(self, ins):
        Clock.unschedule(self.clearall)

    def equal_call(self, ins, out=None):
        if out == None:
            self.ou = self.out
        else:
            self.ou = out
        special_expr = False
        final_expr_str = self.out.text.replace('^', '**')
        try:
            expr = sympy.N(
                parse_expr(final_expr_str, transformations=transformations))
            try:
                expr = float(expr)
            except:
                pass

            if expr != expr.doit():
                self.out.text = str(expr.doit())
                spx = str(expr) + " = " + str(expr.doit())
                special_expr = 'Eq(' + str(expr) + ', ' + str(
                    expr.doit()) + ')'
                if sympy.sympify(special_expr) == True:
                    special_expr = False
                print("special expr", special_expr)
                self.out.text = str(expr.doit())
            self.expr = expr
        except Exception as e:
            print(e)
            expr = final_expr_str
        try:
            tex = str(eval(str(expr)))
        except:
            tex = expr
        if out == None:
            self.ou.text = str(tex).replace('**', '^')
        else:
            self.ou.text = str(tex)
            if special_expr:
                self.ou.text = special_expr
        self.out.text = self.out.text.replace('**', '^')

    def equalcall_old(self, ins, out=None):
        try:
            expr = N(
                parse_expr(self.out.text,
                           transformations=transformations,
                           evaluate=True))
            tex = str(expr)
            self.out.text = tex
        except:
            pass

    def rout_update(self, *args):
        exprg = self.expgen()
        if exprg != False:
            newtext = sympy.pretty(self.expgen())
            self.rout.text = newtext

    def differentiate(self, ins):
        try:
            expr = self.expgen()
            diff_expr = diff(expr, x)
            self.finaloutstr(diff_expr)

        except Exception as e:
            print(e)

    def integral(self, ins):
        try:
            expr = self.expgen()
            int_expr = integrate(expr, x)
            self.finaloutstr(int_expr)

        except Exception as e:
            print(e)

    def simplify(self, ins):
        try:
            expr = self.expgen()
            simplified_expr = simplify(expr)
            self.finaloutstr(simplified_expr)

        except Exception as e:
            print(e)

    def factorise(self, ins):
        try:
            expr = self.expgen()
            simplified_expr = sympy.factor(expr)
            self.finaloutstr(simplified_expr)

        except Exception as e:
            print(e)

    def expand(self, ins):
        try:
            expr = self.expgen()
            expand_expr = sympy.expand(expr)
            self.finaloutstr(expand_expr)

        except Exception as e:
            print(e)
            print(self.rout.text)

    def expgen(self):
        try:
            final_expr_str = self.out.text.replace('^', '**')
            if not self.fractog.active:
                expr = N(
                    parse_expr(final_expr_str,
                               transformations=transformations))
            else:
                expr = (parse_expr(final_expr_str,
                                   transformations=transformations))

            print("Generated Expr ", expr)
            return expr

        except Exception as e:
            print("Expression generated Error! \n", e)
            return False

    def finaloutstr(self, expr):
        tmps = str(expr)
        tmps.replace('**', '^').replace('(pi/180)', u'\u00b0')
        print(tmps)
        self.out.text = tmps
        self.equalcall(None)

    def solver(self, *args):
        try:
            expr = self.expgen()
            Logger.info(expr)
            eq = sympy.Eq(expr, 0, evaluate=False)
            finalcc = '\n\nExpression : \n' + sympy.pretty(eq)

            for symbol in list(expr.atoms(sympy.Symbol)):
                Logger.info(symbol)
                os.environ['dbg'] = '1'

                solved = sympy.solveset(eq, symbol)
                os.environ['dbg'] = '0'

                Logger.info(solved)
                solved_pretty = sympy.pretty(solved,
                                             use_unicode=True,
                                             num_columns=4000)
                top_content = '\n \n Solution for ' + str(symbol) + ':\n\n'
                finalc = (top_content + solved_pretty)
                try:
                    finalc.encode('utf-8')
                except:
                    pass
                finally:
                    print(finalc)
                print('creating button')
                finalcc += finalc
            self.make_dialog('Solve', finalcc)
            print('button created')

        except Exception as e:
            print(e)

    def make_dialog(self, title, finalc):
        content = Button(text=finalc,
                         padding=(0, 0),
                         font_name='Hack-Regular',
                         halign='left',
                         size_hint=(None, None),
                         color=[0, 0, 0, 1],
                         background_normal='./transparent.png',
                         background_down='./transparent.png')
        content.bind(size=lambda x, y: Logger.info(y))
        content.bind(
            texture_size=lambda obj, t: content.setter('size')(obj, t))
        bx = ScrollView(size_hint=(1, None),
                        size=(Window.width * 0.7, Window.height * 0.6))
        bx.add_widget(content)
        bx.bind(size=lambda obj, x: Logger.info(x))
        self.dialog = MDDialog(title=title, content=bx, size_hint=(0.8, 0.8))
        self.dialog.add_action_button('Dismiss',
                                      lambda *args: self.dialog.dismiss())
        self.dialog.open()

    ## MATRIX

    def mat_init(self):
        self.rows = self.numpad.ids['row']
        self.rows_2 = self.numpad.ids['row2']
        self.columns = self.numpad.ids['col']
        self.columns_2 = self.numpad.ids['col2']
        self.matrixgrid = self.numpad.ids['matrix_grid']
        self.matrixgrid2 = self.numpad.ids['matrix_grid_2']
        self.rrefbut = self.numpad.ids['rref']
        self.matrixmenu = self.numpad.ids['Matrix_menu']

        self.rrefbut.bind(on_release=self.rref_call)
        self.rows.bind(on_release=self.matup1)
        self.columns.bind(on_release=self.matup1)
        self.rows_2.bind(on_release=self.matup2)
        self.columns_2.bind(on_release=self.matup2)
        self.matupdate(1)
        self.matupdate(no=2)

        self.matrixgrid.bind(minimum_height=self.matrixgrid.setter('height'))
        self.matrixgrid2.bind(minimum_height=self.matrixgrid2.setter('height'))

        self.matrix1 = self.matrix2 = None

    def matup1(self, *args):
        self.matupdate(1)

    def matup2(self, *args):
        self.matupdate(no=2)

    def matupdate(self, no, *args):
        try:
            if no == 1:
                self.matrixgrid.cols = int(self.columns.text)
                self.matgridform(rows=int(self.rows.text),
                                 cols=int(self.columns.text),
                                 matgrid=self.matrixgrid)

            elif no == 2:
                self.matrixgrid2.cols = int(self.columns_2.text)
                self.matgridform(rows=int(self.rows_2.text),
                                 cols=int(self.columns_2.text),
                                 matgrid=self.matrixgrid2)

        except:
            pass

    def matgridform(self, rows, cols, matgrid):
        try:
            if len(matgrid.children) > rows * cols:
                for x in range((len(matgrid.children)) - rows * cols):
                    matgrid.remove_widget(matgrid.children[-1])

            else:
                for x in range(rows * cols - (len(matgrid.children))):
                    matgrid.add_widget(self.matblock())

        except Exception as e:
            print(e)

    def matblock(self):
        b = MDTextField(text='0', hint_text='0', padding_x=20)
        b.bind(text=self.checktext)

        return b

    def checktext(self, obj, text):
        if text == '':
            obj.text = '0'

        elif len(text) > 1 and text[:1] == '0':
            obj.text = text[1:]

    def make_matrix(self, cols, matgrid, mat):
        try:
            mat_list = []
            tmpl = []
            for x in matgrid.children:
                print(x.text)
                tmpl.append(
                    parse_expr(str(x.text), transformations=transformations))
            tmpl = tmpl[::-1]
            Logger.info(tmpl)
            try:
                mat_list = [
                    tmpl[i:i + cols] for i in xrange(0, len(tmpl), cols)
                ]
                print(mat_list)

            except:
                mat_list = [
                    tmpl[i:i + cols] for i in range(0, len(tmpl), cols)
                ]
                print(mat_list)

            mat = sympy.Matrix(mat_list)
            Logger.info(mat_list)
            print(mat_list)
            return mat

        except Exception as e:
            Logger.error(e)
            print(e)
            return False

    def rref_call(self, matno=1, *args):
        if matno == 2:
            matrix = self.matrix2
            matgrid = self.matrixgrid2
            cols = int(self.columns_2.text)

        else:
            matrix = self.matrix1
            matgrid = self.matrixgrid
            cols = int(self.columns.text)

        for x in matgrid.children:
            print(x.text)

        matrix = self.make_matrix(cols=cols, matgrid=matgrid, mat=matrix)
        print(matrix)
        if matrix == None or matrix == False:
            return

        rref = matrix.rref()[0]
        count = 0
        for x in matgrid.children:
            count -= 1
            x.text = str(rref[count])

        self.make_dialog(title='RREF',
                         finalc=sympy.pretty(sympy.Eq(matrix,
                                                      rref,
                                                      evaluate=False),
                                             use_unicode=True))

    ## LIMIT

    def limit_init(self):
        self.func = self.numpad.ids['f(x)']
        self.x0 = self.numpad.ids['X0']
        self.Sign = self.numpad.ids['sign']
        self.doit = self.numpad.ids['do_it']
示例#31
0
class ImportSearchTable2(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = ImportDetail()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None

    search_result = data_object.get_import_details()

    _filter_import_id = False
    _filter_product_id = False
    _product_id_search = " AND product_id = {} "
    _filter_quantity = False
    _quantity_search = " AND quantity LIKE {} "
    _filter_unitprice = False
    _unitprice_search = " AND unitprice LIKE {} "

    def __init__(self, **kwargs):
        super(ImportSearchTable2, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()
        try:
            self.k_id = sorted([int(x) for x in self._data])[-1] + 1
            print self.parent
        except:
            print "Error"

    def activate_import_id(self, state):
        if state == 'down':
            self._filter_import_id = True
        else:
            self._filter_import_id = False
            self.search_result = self.data_object.get_import_details()
            self.pagination_next()

    def activate_product_id(self, state):
        if state == 'down':
            self._filter_product_id = True
        else:
            self._filter_product_id = False

    def activate_quantity(self, state):
        if state == 'down':
            self._filter_quantity = True
        else:
            self._filter_quantity = False

    def activate_unitprice(self, state):
        if state == 'down':
            self._filter_unitprice = True
        else:
            self._filter_unitprice = False

    def filter(self, import_import_search_id_text, import_product_search_id,
               import_search_quantity, import_search_unit_price):
        if self._filter_import_id:
            if import_import_search_id_text != '':
                self.sql = "SELECT * FROM import_details WHERE import_id = {} ".format(
                    import_import_search_id_text)
            else:
                self.sql = "SELECT * FROM import_details WHERE import_id LIKE '%%' "
            if self._filter_product_id and import_product_search_id != '':
                self.sql += self._product_id_search.format(
                    import_product_search_id)
            if self._filter_quantity and import_search_quantity != '':
                self.sql += self._quantity_search.format(
                    import_search_quantity)
            if self._filter_unitprice and import_search_unit_price != '':
                self.sql += self._unitprice_search.format(
                    import_search_unit_price)
            s = self.data_object.execute(self.sql)
            name = dict()
            for val in s:
                name[val['import_id']] = val
            self.search_result = name
        else:
            self.search_result = self.data_object.get_import_details()

        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.import_id = id
            self.data_object.delete_import_detail()
            self.pagination_next(self.current)
        except KeyError:
            Snackbar(text=" Key Not Found ").show()
        except _mysql_exceptions.IntegrityError:
            Snackbar(
                text=
                "Cannot delete or update a parent row: a foreign key constraint fails"
            ).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        import_data_object = Import()
        import_data_dict = import_data_object.get_imports()
        product_data_object = Product()
        product_data_dict = product_data_object.get_products()
        # print product_data_dict
        # print self._data
        for key in self._data:

            id = str(self.search_result.get(key)['id'])
            import_id = import_data_dict.get(
                str(self.search_result.get(key)
                    ['import_id']))['receipt_number']
            product_id = product_data_dict.get(
                str(self.search_result.get(key)['product_id']))['brandname']
            # print str(self.data_object.get_import_details().get(key)['product_id']) , "=>" , product_id
            quantity = str(self.search_result.get(key)['quantity'])
            unitprice = str(self.search_result.get(key)['unitprice'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=import_id))
            self.d.add_widget(DataLabel(text=product_id))
            self.d.add_widget(DataLabel(text=quantity))
            self.d.add_widget(DataLabel(text=unitprice))
            self.d.add_widget(option)

            super(ImportSearchTable2, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, import_id, product_id, quantity, unitprice):
        self.data_object.id = id
        self.data_object.import_id = import_id
        self.data_object.product_id = product_id
        self.data_object.quantity = quantity
        self.data_object.status = unitprice
        self.data_object.update_import_detail()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        import_id = str(
            self.data_object.get_import_details().get(id)['import_id'])
        product_id = str(
            self.data_object.get_import_details().get(id)['product_id'])
        quantity = str(
            self.data_object.get_import_details().get(id)['quantity'])
        unitprice = str(
            self.data_object.get_import_details().get(id)['unitprice'])
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        imp_id = DialogTextInput(import_id)
        prod_id = DialogTextInput(product_id)
        qty = DialogTextInput(quantity)
        uprice = DialogTextInput(unitprice)

        b.add_widget(
            MDLabel(id='destination',
                    text="Import ID",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(imp_id)
        b.add_widget(MDLabel(text="Product ID", size_hint_x=None,
                             width="90px"))
        b.add_widget(prod_id)
        b.add_widget(
            MDLabel(id='date', text="Quantity", size_hint_x=None,
                    width="90px"))
        b.add_widget(qty)
        b.add_widget(
            MDLabel(id='date',
                    text="Unit Price",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(uprice)

        self.dialog = MDDialog(title="Update Import",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(
                id, imp_id.text, prod_id.text, qty.text, uprice.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#32
0
class CategoriesSearchTable(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Category()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 11
    _data = None
    search_result = dict()
    sql = ''

    def __init__(self, **kwargs):
        kwargs['size_hint_y'] = None
        super(CategoriesSearchTable, self).__init__(**kwargs)
        self.bind(minimum_height=self.setter('height'))
        self.pagination_next()
        self.call_load()

    def filter(self, name):
        self.sql = "SELECT * FROM categories WHERE name REGEXP '{}' ORDER BY name".format(
            name)
        s = self.data_object.execute(self.sql)
        name = dict()
        for val in s:
            name[val['name']] = val
        self.search_result = name
        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_category()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"

    def generate_pdf(self, dt):
        sorted_list = sorted(self.search_result)
        th = Thread(target=generate_pdf,
                    args=(sorted_list, self.search_result))
        th.start()

    def generate_excel_sheet(self, dt):
        id = list()
        name = list()

        # result = list(sup.execute('SELECT * FROM suppliers'))

        # print self.search_result.values()

        for v in self.search_result.values():
            id.append(int(v.get('id')))
            name.append(v.get('name'))

        data_dict = {
            # '1_ID': id,
            '2_Name': name,
        }

        # generate_excel(data_dict, excel_file_name="supplier_report4")

        th = Thread(
            target=generate_excel,
            args=(data_dict,
                  "ExcelReports\\categories_report\\categories_report_" +
                  str(datetime.today()).replace(" ", "_").replace(":", "_")))
        th.start()

    def make_excel(self):
        Clock.schedule_once(self.generate_excel_sheet)

    def make_report(self):
        Clock.schedule_once(self.generate_pdf)

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        # self.pages = list(self.data_object.get_categories())
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        # self.pages = list(self.data_object.get_categories())
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.search_result.get(key)['id'])
            name = str(self.search_result.get(key)['name'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=name))
            self.d.add_widget(option)

            super(CategoriesSearchTable, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, name):
        self.data_object.id = id
        self.data_object.name = name
        self.data_object.update_category()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        name = self.data_object.get_categories().get(id)['name']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        name_wid = DialogTextInput(name)

        b.add_widget(
            MDLabel(id='Name', text="Name", size_hint_x=None, width="90px"))
        b.add_widget(name_wid)

        self.dialog = MDDialog(title="Update Category",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save", action=lambda *x: self.save_edited_data(id, name_wid.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        self.pagination_next()
        self.call_load()
示例#33
0
class KitchenSink(App):
    theme_cls = ThemeManager()

    menu_items = [
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        main_widget.ids.text_field.bind(on_text_validate=self.set_error_message, on_focus=self.set_error_message)
        return main_widget

    def show_example_snackbar(self, type):
        if type == "simple":
            Snackbar.make("This is a snackbar!")
        elif type == "button":
            Snackbar.make("This is a snackbar", button_text="with a button!", button_callback=lambda *args: 2)
        elif type == "verylong":
            Snackbar.make("This is a very very very very very very very long " "snackbar!", button_text="Hello world")

    def show_example_dialog(self):
        content = MDLabel(
            font_style="Body1",
            theme_text_color="Secondary",
            text="This is a dialog with a title and some text. That's pretty awesome right!",
            valign="top",
        )

        content.bind(size=content.setter("text_size"))
        self.dialog = MDDialog(
            title="This is a test dialog", content=content, size_hint=(0.8, None), height=dp(200), auto_dismiss=False
        )

        self.dialog.add_action_button("Dismiss", action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def theme_swap(self):
        self.theme_cls.theme_style = "Dark" if self.theme_cls.theme_style == "Light" else "Light"

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon", lambda x: x, icon="md-cast")
        bs.add_item("Here's another!", lambda x: x, icon="md-nfc")
        bs.open()

    def show_example_grid_bottom_sheet(self):
        bs = MDGridBottomSheet()
        bs.add_item("Facebook", lambda x: x, icon_src="./assets/facebook-box.png")
        bs.add_item("YouTube", lambda x: x, icon_src="./assets/youtube-play.png")
        bs.add_item("Twitter", lambda x: x, icon_src="./assets/twitter.png")
        bs.add_item("Da Cloud", lambda x: x, icon_src="./assets/cloud-upload.png")
        bs.add_item("Camera", lambda x: x, icon_src="./assets/camera.png")
        bs.open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field.text) == 0:
            self.root.ids.text_field.error = True
            self.root.ids.text_field.error_message = "Some text is required"
        else:
            self.root.ids.text_field.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass