Exemple #1
0
    def __init__(self, **kwargs):
        """Set up the CardDisplays."""
        FloatLayout.__init__(self, **kwargs)
        self.main = BoxLayout(orientation="vertical", pos_hint={'x':0, 'y':0})
        self.slots = []
        for i in range(len(self.board)):  # for card in board iterates all sides
            layout = BoxLayout()
            side_slots = []
            for card in self.board[i]:
                display = CardDisplay(card=card)
                side_slots.append(display)
                layout.add_widget(display)
            self.slots.append(side_slots)
            self.main.add_widget(layout)
        self.add_widget(self.main)

        # Prep the next round prompt widget for later
        self._next_round_prompt = BoxLayout(size_hint=(1, .125))
        self._next_round_prompt.add_widget(Button(text="Replay",
                                           on_release=self.rescore_prompted))
        self._next_round_prompt.add_widget(Widget())  # spacer
        self._next_round_prompt.add_widget(Button(text="Continue",
                                           on_release=self.next_round_prompted))

        # Prep for powerup overlays
        self.powerup_anchor = AnchorLayout(anchor_x='right', anchor_y='top',
                                           size_hint=(1, 1),
                                           pos_hint={'x':0, 'y':0})
        self.add_widget(self.powerup_anchor)
Exemple #2
0
    def __init__(self, **kwargs):
        super(RhythmScreen, self).__init__(**kwargs)

        self.orientation = 'vertical'
        self.spacing = 10

        titleLayout = BoxLayout(size_hint_y=0.05)

        self.poemTitle = Label(size_hint_x=0.9, font_size='18sp')

        titleLayout.add_widget(self.poemTitle)
        self.add_widget(titleLayout)


        topbox = BoxLayout(
            orientation='horizontal', 
            size_hint_y=0.4)

        
        self.rhythm_length_slider = VCSSlider(
            min=1,
            max=48,
            step=1,
            show_value=True,
            osc_address='/rhythm_length',
            size_hint_x=0.2)

        topbox.add_widget(self.rhythm_length_slider)

        self.rhythm_display = RhythmDisplay(
            on_button_pressed=self.rhythm_btn_pressed)

        topbox.add_widget(self.rhythm_display)

        self.add_widget(topbox)


        poem_controls = BoxLayout(size_hint_y=0.1, spacing=2)

        self.entryBox = EntryBox(
            size_hint_x=14)

        poem_controls.add_widget(self.entryBox)

        poem_controls.add_widget(IconButton(
            #text='enter',
            size_hint=[None, None],
            size=['48dp', '48dp'],
            up_image='images/ret-no-alpha.png',
            down_image='images/ret-no-alpha-glitch-inv.png',
            on_release=self.enter_pressed))

        self.add_widget(poem_controls)

        self.add_widget(RhythmKeyboard(
            size_hint_y=0.55, 
            on_keyboard_up=self.keyboard_btn_released))

        app = kivy.app.App.get_running_app()        
        app.bind(rhythm_position=self.rhythm_position_changed)
class MainWindow(BoxLayout):

    def __init__(self, **kwargs):
        kwargs['orientation'] = 'vertical'
        super(MainWindow, self).__init__(**kwargs)

        spinner = Spinner(
            # default value shown
            text='Home',
            # available values
            values=('Home', 'Test', 'AddWord'),
            # just for positioning in our example
            size_hint=(1, None),
            size=(100, 44),
            pos_hint={'center_x': .5, 'center_y': .5})

        spinner.bind(text=self.set_page_vidget)

        self.add_widget(spinner)

        self.work_area = BoxLayout()
        self.work_area.add_widget(Home())
        self.add_widget(self.work_area)

    def set_page_vidget(self, _, name):
        self.work_area.clear_widgets()
        vidget = globals()[name]
        self.work_area.add_widget(vidget())
Exemple #4
0
	def __init__(self, title='', duration='', author='', view_count='',
				 thumbnail='', source_videos=None, source_audios=None, **kwargs):
		super(YoutubeDisplayLayout, self).__init__(**kwargs)
		self.source_videos = source_videos  # contain all source pafy video
		self.source_audios = source_audios  # contain all source pafy audio
		self.title = Label(text=title)
		self.duration = Label(text=u'Độ Dài : ' + str(duration))
		self.author = Label(text=u'Người Đăng : ' + author)
		self.view_count = Label(text=u'Lượt Xem : ' + str(view_count))

		other_info_box = BoxLayout()
		other_info_box.add_widget(self.duration)
		other_info_box.add_widget(self.author)
		other_info_box.add_widget(self.view_count)

		info_box = BoxLayout(orientation='vertical')
		info_box.add_widget(self.title)
		info_box.add_widget(other_info_box)

		self.thumbnail = AsyncImage(source=thumbnail, size_hint=(.2, 1))
		self.add_widget(self.thumbnail)
		self.add_widget(info_box)

		self.register_event_type('on_click')  # register an event for the layout
		self.register_event_type('on_db_click')  # register an event for the layout

		with self.canvas.before:  # define the selection animation
			self.color = Color(rgba=(0, 0, 0, 0))
			self.rect = Rectangle(size=self.size, pos=self.pos)
		self.bind(pos=self.updateRect, size=self.updateRect)
Exemple #5
0
    def __init__(self, parent, titleheader="Title", message="Message", options={"OK": ""}, size=(400, 400)):

        def popup_callback(instance):
            "callback for button press"
            self.retvalue = instance.text
            self.popup.dismiss()

        self.parent = parent
        self.retvalue = None
        self.titleheader = titleheader
        self.message = message
        self.options = options
        self.size = size
        box = GridLayout(orientation='vertical', cols=1)
        box.add_widget(Label(text=self.message, font_size=16))
        b_list = []
        buttonbox = BoxLayout(orientation='horizontal')
        for b in self.options:
            b_list.append(Button(text=b, size_hint=(1,.35), font_size=20))
            b_list[-1].bind(on_press=popup_callback)
            buttonbox.add_widget(b_list[-1])
        box.add_widget(buttonbox)
        self.popup = Popup(title=titleheader, content=box, size_hint=(None, None), size=self.size)
        self.popup.open()
        self.popup.bind(on_dismiss=self.OnClose)
Exemple #6
0
    def do_email(self, popup, address, filename, widget):
        thread = SenderThread(address, filename)
        thread.daemon = True
        thread.start()
        popup.dismiss()

        layout = BoxLayout(orientation='vertical')
        label = Label(
            text='Just sent this image to:\n\n{}'.format(address),
            font_size=30)
        button = Button(
            text='Awesome!',
            font_size=30,
            background_color=(0, 1, 0, 1))
        layout.add_widget(label)
        layout.add_widget(button)

        popup = Popup(
            title='Just thought you should know...',
            content=layout,
            size_hint=(.5, .5))

        button.bind(on_release=popup.dismiss)
        from kivy.core.window import Window

        Window.release_all_keyboards()
        self.reset_email_textinput()
        popup.open()
Exemple #7
0
 def add_column(self, widget, lista):
     bl = BoxLayout(orientation="vertical")
     for element in lista[0]:
         lab = ListaNumeros(text=str(element))
         lista[1].append(lab)
         bl.add_widget(lab)
     widget.add_widget(bl)
Exemple #8
0
    def show_wifi_scans(self):
        stack = self.ids['scan_layout']
        stack.clear_widgets()
        wifi_scans = wifi.names.keys()
        for name in wifi_scans:
            content = ""
            items = wifi._get_network_info(name)
            for key, value in items.iteritems():
                content += "{}:    {} \n".format(key, value)

            popup = self._create_popup(name, content)
            boxl = BoxLayout(orientation='horizontal')
            button = Button(
                text=name,
                size_hint=(1, 1),
                height='40dp',
                on_release=popup.open,
            )
            button_connect = Button(
                text="Connect",
                size_hint_x=.2,
                on_release=partial(self.connect, name))

            boxl.add_widget(button)
            boxl.add_widget(button_connect)
            stack.add_widget(boxl)
Exemple #9
0
    def _create_popup(self, instance):
        # create popup layout
        content = BoxLayout(orientation='vertical', spacing=5)
        popup_width = min(0.95 * Window.width, dp(500))
        self.popup = popup = Popup(
            title=self.title, content=content, size_hint=(None, 0.9),
            width=popup_width)

        # create the filechooser
        self.textinput = textinput = FileChooserListView(
            path=self.value, size_hint=(1, 1), dirselect=True)
        textinput.bind(on_path=self._validate)
        self.textinput = textinput

        # construct the content
        content.add_widget(textinput)
        content.add_widget(SettingSpacer())

        # 2 buttons are created for accept or cancel the current value
        btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
        btn = Button(text='Ok')
        btn.bind(on_release=self._validate)
        btnlayout.add_widget(btn)
        btn = Button(text='Cancel')
        btn.bind(on_release=self._dismiss)
        btnlayout.add_widget(btn)
        content.add_widget(btnlayout)

        # all done, open the popup !
        popup.open()
Exemple #10
0
    def build(self):
        wid = Widget()

        label = Label(text='0')

        btn_add100 = Button(text='+ 100 rects',
                            on_press=partial(self.add_rects, label, wid, 100))

        btn_add500 = Button(text='+ 500 rects',
                            on_press=partial(self.add_rects, label, wid, 500))

        btn_reset = Button(text='Reset',
                           on_press=partial(self.reset_rects, label, wid))

        layout = BoxLayout(size_hint=(1, None), height=50)
        layout.add_widget(btn_add100)
        layout.add_widget(btn_add500)
        layout.add_widget(btn_reset)
        layout.add_widget(label)

        root = BoxLayout(orientation='vertical')
        root.add_widget(wid)
        root.add_widget(layout)

        return root
Exemple #11
0
    def show_view_list_path(self, *args, **kwargs):
        
        self.clear_widgets()
        color = ColorLayout()
        boxl = BoxLayout(orientation= 'vertical',anchor_y= "top")
        grid = GridLayout(cols=1, size_hint_y=None)
        grid.bind(minimum_height=grid.setter('height')) 
        scroll = ScrollView(size_hint=(None, None))
        scroll.size = (Window.width, Window.height)
        scroll.center = Window.center
        #2 Space added but button go back ocuppies space and first value hidden.
        l_space = MultiLineLabel(text='',font_size="16dp", background_color=(255,255,255,255), markup=True)
        grid.add_widget(l_space)
        l_space = MultiLineLabel(text='',font_size="16dp", background_color=(255,255,255,255), markup=True)
        grid.add_widget(l_space)
        
        for i in args[0]:
            text = '[color=333333]'+'  '+i['text'] + '[/color]'+'  '
            #~ l = MultiLineLabel(text=text,font_size="16dp",markup=True)
            l = MultiLineLabel(text=text,font_size="16dp", background_color=(255,255,255,255), markup=True)
            i['stations'] and l.bind(on_press = partial(self.show_list_stations, i['stations'],args[0]))
            grid.add_widget(l)
            
        button_back = Button(text="Go Back", auto_dismiss=False, size_hint=(None, None), pos_hint= {'center_x':.5, 'center_y':.7})
        button_back.height="50dp"
        button_back.width="100dp"
        button_back.bind(on_press = lambda widget: self.show_option_view())

        scroll.add_widget(grid)
        boxl.add_widget(scroll)
        boxl.add_widget(button_back)
        color.add_widget(boxl)
        self.add_widget(color)
class TwistedClientApp(App):
    connection = None

    def build(self):
        root = self.setup_gui()
        self.connect_to_server()
        return root

    def setup_gui(self):
        self.textbox = TextInput(size_hint_y=.1, multiline=False)
        self.textbox.bind(on_text_validate=self.send_message)
        self.label = Label(text='connecting...\n')
        self.layout = BoxLayout(orientation='vertical')
        self.layout.add_widget(self.label)
        self.layout.add_widget(self.textbox)
        return self.layout

    def connect_to_server(self):
        reactor.connectTCP('localhost', 8000, EchoFactory(self))

    def on_connection(self, connection):
        self.print_message("connected succesfully!")
        self.connection = connection

    def send_message(self, *args):
        msg = self.textbox.text
        if msg and self.connection:
            self.connection.write(str(self.textbox.text))
            self.textbox.text = ""

    def print_message(self, msg):
        self.label.text += msg + "\n"
Exemple #13
0
    def __init__(self, **kwargs):
        super(Schedule, self).__init__(**kwargs)

        self.app = App.get_running_app()
        self.rows = self.app.config_settings.getint('schedule', 'coursesaday')

        self.orientation = 'vertical'

        self.schedule_buttons = dict()
        self.size = self.parent.size
        self.schedule_scroll_view = ScrollView(size_hint_x=1, size_hint_y=None,
                                               size=(self.size[0], self.size[1] - dp(55)),
                                               do_scroll_x=False)

        # self.schedule = GridLayout(col_default_width='55dp', col_force_default=True, cols=7, row_default_height='1cm',
        #                            row_force_default_height=True)
        self.schedule = BoxLayout(orientation='vertical')
        self._fill_schedule()
        self.schedule_scroll_view.add_widget(self.schedule)

        self.add_widget(self.schedule_scroll_view)
        self.add_widget(SettingSpacer())

        button_box = BoxLayout(orientation='horizontal', size_hint_y=None, height='50dp')
        button_box.add_widget(Button(text=u'Add {}'.format(_(strings.text['course'])), on_release=self.on_add_course))
        button_box.add_widget(Button(text=cap_first_letter(_(strings.text['close'])), on_release=self.on_close))

        self.add_widget(button_box)
Exemple #14
0
    def _create_popup(self, instance):
        ''' create popup layout  '''
        content = BoxLayout(orientation='vertical', spacing='5dp')
        self.popup = popup = Popup(title=self.title,content=content, size_hint=(0.9, 0.9))

        # Create the slider used for numeric input
        self.colorpicker = colorpicker = ColorPicker()

        content.add_widget(colorpicker)
        content.add_widget(SettingSpacer())

        # 2 buttons are created for accept or cancel the current value
        btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
        btn = cMultiLineButton(text=ReplaceVars('$lvar(5008)'), halign='center', valign='middle')
        btn.bind(on_release=self._validate)
        btnlayout.add_widget(btn)
        btn = cMultiLineButton(text=ReplaceVars('$lvar(5009)'), halign='center', valign='middle')
        btn.bind(on_release=self._dismiss)
        btnlayout.add_widget(btn)
        content.add_widget(btnlayout)
        colorpicker.bind(color= self.On_Color)
        # all done, open the popup !

        colorpicker.hex_color = self.value

        popup.open()
    def build(self):
        self.title = "MOONBOARD"
        parent = BoxLayout(size=(Window.width, Window.height))
        self.gridsDisplay = MoonboardAppLayout()
        parent.add_widget(self.gridsDisplay)

        return parent
Exemple #16
0
class MyApp(App):
    def build(self):
        self.modes = (
            '%I:%m:%S',
            '%H:%m:%S %P',
            '%S:',
        )
        self.mode = 0
        self.main_box = BoxLayout(orientation='vertical')

        self.button = Button(text='label', font_size=100)
        self.main_box.add_widget(self.button)

        self.button.bind(on_press=self.tap)
        Clock.schedule_interval(self.timer, 0.01)

        return self.main_box

    def tap(self, button):
        if self.mode +1 == len(self.modes):
            self.mode = 0
        else:
            self.mode +=1

    def timer(self, dt):
        now = datetime.datetime.now()
        self.button.text = now.strftime(self.modes[self.mode])
        if self.mode == 2:
            self.button.text += str(now.microsecond)[:3]
Exemple #17
0
    def _create_popup(self, instance):
        ''' create popup layout '''
        content = BoxLayout(orientation='vertical', spacing=5)
        self.popup = popup = Popup(title=self.title, content=content, size_hint=(0.95, 0.95))

        # create the filechooser
        uRoot, uName = split(self.value)  # pylint: disable=unused-variable
        uRoot = ReplaceVars( uRoot)
        self.textinput = textinput = FileBrowser( select_string     = ReplaceVars('$lvar(563)'),\
                                                  cancel_string     = ReplaceVars('$lvar(5009)'),\
                                                  libraries_string  = ReplaceVars('$lvar(5018)'),\
                                                  favorites_string  = ReplaceVars('$lvar(5019)'),\
                                                  computer_string   = ReplaceVars('$lvar(5020)'),\
                                                  location_string   = ReplaceVars('$lvar(5021)'),\
                                                  listview_string   = ReplaceVars('$lvar(5022)'),\
                                                  iconview_string   = ReplaceVars('$lvar(5023)'),\
                                                  path              = uRoot,dirselect=False,\
                                                  transition        = FadeTransition(),\
                                                  size_hint         = (1, 1),\
                                                  favorites         = [(oORCA.uAppPath, 'ORCA')],\
                                                  show_fileinput    = False,\
                                                  show_filterinput  = False\
                                                  )

        # construct the content
        content.add_widget(textinput)
        textinput.bind(on_success=self._validate,on_canceled=self._dismiss)

        # all done, open the popup !
        popup.open()
Exemple #18
0
 def selection_buttons(self, d_btn_state, r_btn_state):
     direct_btn = MyButton(text="Dus", on_press=self.direct_selected, state=d_btn_state)
     reverse_btn = MyButton(text="Intors", on_press=self.reverse_selected, state=r_btn_state)
     selection_btns = BoxLayout(size_hint_y=None, height="50dp")
     selection_btns.add_widget(direct_btn)
     selection_btns.add_widget(reverse_btn)
     return selection_btns
    def build(self):
        # create root widget
        root_widget = FloatLayout()
        box = BoxLayout(orientation='vertical',
                        size_hint=(None, None),
                        size=(400, 200),
                        spacing=dp(20),
                        padding=dp(20),
                        pos_hint={'center_x': .5, 'center_y':.5})

        # create the labels and the textinputs
        lbl_user =  Label(text='User Name:')
        lbl_password = Label(text='Password')
        ti_user = TextInput()
        ti_password = TextInput(password=True)
        
        # create the containers for the labels and textinputs
        grid_user_pass = GridLayout(rows=2, cols=2, spacing=dp(20))
        # create the ok button
        my_but_is_ok = Button(text='OK')
        my_but_is_ok.bind(on_release=lambda *args: self.check_user(ti_user.text, ti_password.text))

        # add the labels and input fields to the container 
        grid_user_pass.add_widget(lbl_user)
        grid_user_pass.add_widget(ti_user)
        grid_user_pass.add_widget(lbl_password)
        grid_user_pass.add_widget(ti_password)

        # add the grid_container into it's container
        box.add_widget(grid_user_pass)
        root_widget.add_widget(box)
        # add the ok button at the bottom of the grid
        box.add_widget(my_but_is_ok)

        return root_widget
Exemple #20
0
	def readme_pop(self):
		""" Readme """

		popup = Popup(title='README')
		b=BoxLayout(orientation='vertical')
		s = ScrollView()
		global tslabel
		tslabel=Label(size_hint_y=None,line_height=1.5,valign="top",
					  text= "Copyright (C) 2015 Revathy Narayanan\n" +
					  "The TimeTracker is a Python application \n that will keep"+
					  " track of time spent\n in day-to-day activities.\n\n"+
"The Application will have features \n"+
"* Start/Stop watch \n * Log Task\n * Add Comments\n"+
"* Generate & View Timesheet\n * Mail Timesheet\n\n "+
"The code is licensed under MIT License(MIT).\n "+
"Please see the file license in this distribution\n for license terms in the link below :\n"+
"https://github.com/rev20/Time-Tracker/blob/master/LICENSE \n\n"+
"Following is the link for the repository: \n"+
"https://github.com/rev20/Time-Tracker/")

		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)
Exemple #21
0
	def throw_button(self, in_message):
		self.ids.result_grid.clear_widgets()
		
		native_lang  = 'en'
		to_lang = 'en'
		from_lang = 'en'
		translation = in_message
		out_message = ''

		self.ids.steps_progbar.value = 0

		for index in range(20):
			self.ids.steps_progbar.value += 1 

			rand_int = r.randint(0,len(self.lang_array)-1)
			to_lang = self.lang_array[rand_int][1]
			translation = self.translate(translation, to_lang, from_lang)[0]
			from_lang = to_lang

			line_box = BoxLayout()
			line_box.add_widget(Image(source = 'Art/Flags/' + self.lang_array[rand_int][1] + '.png', size_hint_x = 0.1))
			step_text = TextInput(text = translation, readonly = True)
			line_box.add_widget(step_text)
			self.ids.result_grid.add_widget(line_box)
		out_message = self.translate(translation, native_lang, from_lang)[0]
		self.ids.popup.dismiss()
		self.ids.out_message.text = out_message
Exemple #22
0
    def __init__(self, text_):
        super(RoachWarningBox, self).__init__(orientation='vertical', size_hint=(1,1))

        top_padding = BoxLayout(size_hint=(1,1))
        self.square_label = Label(text = text_)
        bottom_padding = BoxLayout(size_hint=(1,1))
        buttons = BoxLayout(orientation='horizontal', size_hint=(1, 1))

        ok_button = Button(text='Yes',  size_hint=(1,0.2))
        ok_button.bind(on_press=self.selection_yes)
        cancel_button = Button(text='No', size_hint=(1, 0.2))
        cancel_button.bind(on_press=self.selection_no)

        buttons.add_widget(ok_button)
        buttons.add_widget(cancel_button)

        self.add_widget(top_padding)
        self.add_widget(self.square_label)
        self.add_widget(bottom_padding)
        self.add_widget(buttons)

        self.choosen_name = ''
        self.popup = None

        self.continues = True
        self.choise = True
Exemple #23
0
 def __init__(self, **kwargs):
     Screen.__init__(self, **kwargs)
     main = BoxLayout(orientation="vertical")
     main.add_widget(ActionBar(size_hint=(1, .125)))
     carousel = Carousel(direction='right')
     layout = GridLayout(rows=2)
     i, c = 0, 0
     for card in self.definition.cards(App.get_running_app().achievements,
                                       use_blocks=False):
         color = (1, 1, 1, 1)
         if str(card) in self.definition.blocked_cards:
             color = (.5, 0, 0, 1)
         layout.add_widget(CardSelect(card=card,
                                      color=color,
                                      callback=self._card_detail,
                                      args=(card,)))
         i += 1
         c += 1
         if i == 10:
             carousel.add_widget(layout)
             layout = GridLayout(rows=2)
             i = 0
     if c < 50 + len(self.definition.specials):
         layout.add_widget(CardSelect(card=self.LOCKED_CARD))
     carousel.add_widget(layout)
     main.add_widget(carousel)
     self.add_widget(main)
Exemple #24
0
 def build(self):
     layout = BoxLayout(orientation='vertical')
     layout.width = WINDOW_WIDTH
     layout.height = WINDOW_HEIGHT
     layout.add_widget(ScorePanel())
     layout.add_widget(GamePanel(self.current_level.score.notes))
     return layout
Exemple #25
0
class GUI:
    root = None
    _properties = None
    _window = None
    
    def __init__(self, kvFile):
        self.root = BoxLayout()
        Builder.load_file(kvFile)
        self._properties = {}
        
    def setWindow(self, window):
        self.root.clear_widgets()
        self._window = window()
        self._window.setProperty(self._properties)
        self.root.add_widget(self._window)
    
    def getWindow(self):
        return self._window.__class__
    
    def setProperty(self, key, value):
        self._properties[key] = value
        if self._window <> None: self._window.setProperty({key:value})
    
    def getProperty(self, key):
        return self._properties[key]
Exemple #26
0
    def build(self):
        root = BoxLayout(orientation='horizontal', padding=20, spacing=20)
        tree = TreeView(
            size_hint=(None, 1), width=200, hide_root=True, indent_level=0)

        def create_tree(text):
            return tree.add_node(TreeViewLabel(
                text=text, is_open=True, no_selection=True))

        def attach_node(text, n):
            tree.add_node(TreeViewLabel(text=text), n)

        tree.bind(selected_node=self.on_select_node)
        n = create_tree('Widgets')
        attach_node('Standard widgets', n)
        attach_node('Complex widgets', n)
        attach_node('Scatters', n)
        attach_node('Treeviews', n)
        attach_node('Popup', n)
        n = create_tree('Layouts')
        attach_node('Anchor Layout', n)
        attach_node('Box Layout', n)
        attach_node('Float Layout', n)
        attach_node('Grid Layout', n)
        attach_node('Stack Layout', n)
        root.add_widget(tree)
        self.content = content = BoxLayout()
        root.add_widget(content)
        sc = Showcase()
        sc.content.add_widget(root)
        self.content.add_widget(StandardWidgets())
        return sc
	def build(self):
		root = BoxLayout(orientation='vertical')
		c = Imglayout()
		parent = BoxLayout(orientation='horizontal')
		painter = MyPaintWidget()
		
		# create clear button
		clearbtn = Button(text='Clear', size_hint=(1,5))
		parent.add_widget(clearbtn)
		def clear_canvas(obj):
			painter.canvas.clear()
		clearbtn.bind(on_release=clear_canvas)
		
		# create save button
		savebtn = Button(text='Save and send to email', size_hint=(1,5))
		parent.add_widget(savebtn)
		def save_pic(obj):
		  root.remove_widget(parent)
		  root.export_to_png(email)
		  app.Exit()
		savebtn.bind(on_release=save_pic)
		root.add_widget(self.im) 
		root.add_widget(painter)
		root.add_widget(c)
		root.add_widget(parent)
		
		return root
Exemple #28
0
def PopupAudit(audit_obj, key):
    def on_close(*args):
        def _on_close(*args):
            Window.rotation = 0
        Clock.schedule_once(_on_close, .25)

    assert isinstance(audit_obj, AuditResult) or audit_obj is None
    if audit_obj is None:
        text = "No audit attribute found for %s" % key
    else:
        text = str(audit_obj)
    btnclose = Button(text='Continue', size_hint_y=None, height='50sp')
    content = BoxLayout(orientation='vertical')
##    lbl = TextInput(text=text, font_size='12sp', auto_indent=True,
##            readonly=True, disabled=True,
##            font_name='fonts'+os.sep+'DroidSansMono.ttf')
    lbl = ScrollableText(text=text)
    content.add_widget(lbl)
    content.add_widget(btnclose)
    p = Popup(title='Audit of "%s"' % key, content=content,
                #size=('300dp', '300dp'),
                size_hint=(.95, .75))
    btnclose.bind(on_release=p.dismiss)
    p.bind(on_open=lbl.go_top)
    # See if this is a pretty long audit, so we will display long ways
    if max([len(a) for a in text.split('\n')]) > 30:
        p.bind(on_dismiss=on_close) and None
        p.size_hint = (.95, .95)
        Window.rotation = 90
    p.open()
Exemple #29
0
    def Load(self):
        """
        Load from the Disk
        Button > Load()
        """
        from functools import partial
        from kivy.uix import filechooser
        from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
        main = ModalView(size_hint=(.8,.8)) # everything on this Modal is 80%
        BL = BoxLayout(portrait="vertical")
        
        FLV = FileChooserListView(path="coreEngine/Saved",)
        
        

        def cTexloader(instance):
            Selected = FLV.selection
            Selected_Attr = Selected
            LStoString = str(Selected_Attr[0])
            self.Loader_NoErr(ctexSaved=LStoString,fixedPath=LStoString)
            
            
            


        

        Load_Btn = Button(text="Load this File")
        Load_Btn.bind(on_press=cTexloader)
        main.add_widget(BL)
        BL.add_widget(FLV) 
        BL.add_widget(Load_Btn)       

        main.open()
Exemple #30
0
	def timesheet_pop(self):
		"""Popup to display the Timesheet"""

		popup = Popup(title='Timesheet')
		b=BoxLayout(orientation='vertical')
		s = ScrollView()
		global tslabel
		tslabel=Label(size_hint_y=None,line_height=1.5,valign="top",
					  text="|_ID_|______DATE______|___TIME_SPENT____|_____TASK_________|")
		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)

		con=lite.connect('TimeTracker.db')
		with con:
				cur=con.cursor()
				cur.execute("SELECT ID, TASK_DATE, TIME, TASK FROM Timesheet")
				rows = cur.fetchall()
				for row in rows:
				  tslabel.text=tslabel.text+"\n   "
				  tslabel.text+=str(row[0]).center(4)+"      "+str(row[1])
				  tslabel.text+="  "+str(row[2]).center(34)+"  "+str(row[3])
		if con:
				con.close()
    def enter_state(self, context=None):
        print 'ShowingSearchScreen/enter_state'

        if not 'Search' in self.statechart.app.sm.screen_names:

            self.search_results = []

            self.app = self.statechart.app

            self.search_criteria = {}

            view = BoxLayout(orientation='vertical', spacing=10)

            toolbar = BoxLayout(size_hint=(1.0, None), height=50)

            button = Button(text='Lists')
            button.bind(on_press=self.go_to_lists)
            toolbar.add_widget(button)

            label = Label(text='Search', color=[.8, .8, .8, .8], bold=True)
            toolbar.add_widget(label)

            button = Button(text='Data')
            button.bind(on_press=self.go_to_data)
            toolbar.add_widget(button)

            button = Button(text='Detail')
            button.bind(on_press=self.go_to_detail)
            toolbar.add_widget(button)

            view.add_widget(toolbar)

            body_view = BoxLayout()

            left_view = BoxLayout(size_hint=(0.7, 1.0), orientation='vertical')

            left_view.add_widget(
                Label(size_hint=(1.0, 0.2),
                      text="""[b]Search Criteria:[/b]

    Enter the lower and upper bounds of search criteria in the text
    entry boxes. Each time you hit the [i]ENTER[/i] key in a text entry box,
    the search results shown in the list on the right will be updated.""",
                      markup=True))

            search_criteria_view = BoxLayout(orientation='vertical')

            props = [
                prop for prop in self.statechart.data['Apple']
                if prop != 'name'
            ]

            for prop in sorted(props):
                search_box_view = BoxLayout(size_hint=(1.0, None), height=40)

                text_input = TextInput(text='', multiline=False)
                text_input.id = "<: {0}".format(prop)
                text_input.bind(on_text_validate=self.criterion_entered)
                search_box_view.add_widget(text_input)

                search_box_view.add_widget(Label(text="> {0} <".format(prop)))

                text_input = TextInput(text='', multiline=False)
                text_input.id = ">: {0}".format(prop)
                text_input.bind(on_text_validate=self.criterion_entered)
                search_box_view.add_widget(text_input)

                search_criteria_view.add_widget(search_box_view)

            left_view.add_widget(search_criteria_view)

            body_view.add_widget(left_view)

            right_view = BoxLayout(size_hint=(0.3, 1.0),
                                   orientation='vertical')

            right_view.add_widget(
                Label(size_hint=(1.0, 0.2), text="Search Results (red):"))

            self.all_fruits = sorted(self.statechart.data.keys())

            self.results_fruits_dict_adapter = DictAdapter(
                sorted_keys=self.all_fruits,
                data=self.statechart.data,
                args_converter=self.list_item_args_converter,
                selection_mode='none',
                allow_empty_selection=True,
                cls=ListItemLabel)

            right_view.add_widget(
                ListView(size_hint=(1.0, 0.8),
                         adapter=self.results_fruits_dict_adapter))

            body_view.add_widget(right_view)

            view.add_widget(body_view)

            screen = Screen(name='Search')
            screen.add_widget(view)

            self.app.sm.add_widget(screen)

        if self.app.sm.current != 'Search':
            self.app.sm.current = 'Search'
Exemple #32
0
    def gauge_dial_menu(self, *largs):
        """
            Changes dial style of the gauge
        """
        dial_menu = BoxLayout(size_hint=(.25, (0.05 * 9)),
                              orientation='vertical')

        BD1 = Button(text='WHITE')
        BD1.bind(on_release=self.dial_1)
        BD2 = Button(text='PURPLE')
        BD2.bind(on_release=self.dial_2)
        BD3 = Button(text='BLACK')
        BD3.bind(on_release=self.dial_3)
        BD4 = Button(text='YELLOW')
        BD4.bind(on_release=self.dial_4)
        BD5 = Button(text='BLUE')
        BD5.bind(on_release=self.dial_5)
        BD6 = Button(text='GREEN')
        BD6.bind(on_release=self.dial_6)
        BD7 = Button(text='RED')
        BD7.bind(on_release=self.dial_7)
        BD8 = Button(text='ORANGE')
        BD8.bind(on_release=self.dial_8)

        back = Button(text='[ BACK ]', color=(0, 1, 0, 1))
        back.bind(on_release=self.back_to_menu)
        close = Button(text='[ CLOSE ]', color=(1, 0.5, 0, 1))
        close.bind(on_release=self.close_menus)

        dial_menu.add_widget(back)
        dial_menu.add_widget(BD1)
        dial_menu.add_widget(BD2)
        dial_menu.add_widget(BD3)
        dial_menu.add_widget(BD4)
        dial_menu.add_widget(BD5)
        dial_menu.add_widget(BD6)
        dial_menu.add_widget(BD7)
        dial_menu.add_widget(BD8)
        dial_menu.add_widget(close)

        dial_menu.pos = self.Scat.pos

        self.Parent.appLayout.remove_widget(self.gmenu)
        self.gmenu = dial_menu
        self.Parent.appLayout.add_widget(dial_menu)
Exemple #33
0
    def gauge_background_menu(self, *largs):
        """
            Changes background image of the gauge
        """
        bg_menu = BoxLayout(size_hint=(0.25, (0.05 * 9)),
                            orientation='vertical')

        BG1 = Button(text='WHITE')
        BG1.bind(on_release=self.bg_1)
        BG2 = Button(text='PURPLE')
        BG2.bind(on_release=self.bg_2)
        BG3 = Button(text='BLACK')
        BG3.bind(on_release=self.bg_3)
        BG4 = Button(text='YELLOW')
        BG4.bind(on_release=self.bg_4)
        BG5 = Button(text='BLUE')
        BG5.bind(on_release=self.bg_5)
        BG6 = Button(text='GREEN')
        BG6.bind(on_release=self.bg_6)
        BG7 = Button(text='RED')
        BG7.bind(on_release=self.bg_7)

        back = Button(text='[ BACK ]', color=(0, 1, 0, 1))
        back.bind(on_release=self.back_to_menu)
        close = Button(text='[ CLOSE ]', color=(1, 0.5, 0, 1))
        close.bind(on_release=self.close_menus)

        bg_menu.add_widget(back)
        bg_menu.add_widget(BG1)
        bg_menu.add_widget(BG2)
        bg_menu.add_widget(BG3)
        bg_menu.add_widget(BG4)
        bg_menu.add_widget(BG5)
        bg_menu.add_widget(BG6)
        bg_menu.add_widget(BG7)
        bg_menu.add_widget(close)

        bg_menu.pos = self.Scat.pos

        self.Parent.appLayout.remove_widget(self.gmenu)
        self.gmenu = bg_menu
        self.Parent.appLayout.add_widget(bg_menu)
Exemple #34
0
    def preset_themes_menu(self, *largs):
        """
            Changes overall theme of gauge
        """
        theme_menu = BoxLayout(size_hint=(0.25, (0.05 * 9)),
                               orientation='vertical')

        B1 = Button(text='Style 1')
        B1.bind(on_release=self.style_1)
        B2 = Button(text='Style 2')
        B2.bind(on_release=self.style_2)
        B3 = Button(text='Style 3')
        B3.bind(on_release=self.style_3)
        B4 = Button(text='Style 4')
        B4.bind(on_release=self.style_4)
        B5 = Button(text='Style 5')
        B5.bind(on_release=self.style_5)
        B6 = Button(text='Style 6')
        B6.bind(on_release=self.style_6)
        B7 = Button(text='Style 7')
        B7.bind(on_release=self.style_7)

        back = Button(text='[ BACK ]', color=(0, 1, 0, 1))
        back.bind(on_release=self.back_to_menu)
        close = Button(text='[ CLOSE ]', color=(1, 0.5, 0, 1))
        close.bind(on_release=self.close_menus)

        theme_menu.add_widget(back)
        theme_menu.add_widget(B1)
        theme_menu.add_widget(B2)
        theme_menu.add_widget(B3)
        theme_menu.add_widget(B4)
        theme_menu.add_widget(B5)
        theme_menu.add_widget(B6)
        theme_menu.add_widget(B7)
        theme_menu.add_widget(close)

        theme_menu.pos = self.Scat.pos

        self.Parent.appLayout.remove_widget(self.gmenu)
        self.gmenu = theme_menu
        self.Parent.appLayout.add_widget(theme_menu)
Exemple #35
0
class TrackerApp(App):
    _ui_context: UIContext
    _data_saver: DataSaver
    _num_buttons: int
    _next_page_button: int

    _pages: Sequence[Sequence[str]]
    _page_ind: int

    _layout: Layout
    _row_layouts: List[Layout]
    _counts: List[Label]
    _lasts: List[Label]
    _buttons: Sequence[Widget]

    def __init__(self, ui_context: UIContext,
                 data_saver: DataSaver,
                 num_buttons: int,
                 next_page_button: int,
                 pages: Sequence[Sequence[str]]):
        super().__init__()
        self._ui_context = ui_context
        self._data_saver = data_saver
        self._num_buttons = num_buttons
        assert 0 <= next_page_button < num_buttons
        self._next_page_button = next_page_button
        self._pages = pages
        for page in self._pages:
            assert len(page) <= num_buttons
        self._page_ind = 0

    def __enter__(self) -> None:
        self._ui_context.__enter__()
        # self._data_saver.__enter__()

    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        # TODO I don't think this is quite right
        self._ui_context.__exit__(exc_type, exc_val, exc_tb)
        # self._data_saver.__exit__(exc_type, exc_val, exc_tb)

    def build(self) -> Widget:
        font_size = self._ui_context.font_size()
        self._layout = BoxLayout(orientation='vertical')
        self._layout.add_widget(BoxLayout(orientation='horizontal', size_hint=(1.0, 0.2)))  # offset
        self._row_layouts = [BoxLayout(orientation='horizontal') for _ in range(self._num_buttons)]
        self._counts = [Label(font_size=font_size, text=str(i)) for i in range(self._num_buttons)]
        self._lasts = [Label(font_size=font_size, text=str(i)) for i in range(self._num_buttons)]
        self._buttons = self._ui_context.create_buttons(self._num_buttons, font_size, self.process_button_ind)
        for i, (layout, count, last, button) in enumerate(zip(self._row_layouts, self._counts, self._lasts,
                                                              self._buttons)):
            self._layout.add_widget(layout)
            layout.add_widget(count)
            layout.add_widget(last)
            layout.add_widget(button)
        self._setup_page()
        return self._layout

    def process_button_ind(self, button: int) -> None:
        if self._ui_context.is_screen_on():
            if button == self._next_page_button:
                self._page_ind = (self._page_ind + 1) % len(self._pages)
            else:
                if button > self._next_page_button:
                    button_ind = button - 1
                else:
                    button_ind = button
                label = self._pages[self._page_ind][button_ind]
                with self._data_saver:
                    self._data_saver.insert_event(label)
        else:
            self._page_ind = 0  # always reset the page
        self._ui_context.turn_on_screen()
        self._setup_page()

    def _setup_page(self) -> None:
        button_ind = 0
        with self._data_saver:
            event_to_last = self._data_saver.get_last_occurrences(self._pages[self._page_ind])
            event_to_count = self._data_saver.get_num_in_last_24_hours(self._pages[self._page_ind])
        for i in range(len(self._buttons)):
            if i == self._next_page_button:
                self._counts[i].text = f'Page {self._page_ind + 1} / {len(self._pages)}'
                self._lasts[i].text = ''
                self._buttons[i].text = 'Next page'
            else:
                label = self._pages[self._page_ind][button_ind]
                self._counts[i].text = f'In last 24 hours: {event_to_count[label]}'
                last = 'Never' if event_to_last[label] is None else event_to_last[label].strftime('%m/%d: %H:%M')
                self._lasts[i].text = f'Last: {last}'
                self._buttons[i].text = label
                button_ind += 1
Exemple #36
0
class SOptionElement(BoxLayout):

    formulaId = None
    paraDesc = None
    paraDict = None
    paraStrDict = None
    paraList = None

    def __init__(self, paramDict, **kwargs):
        super(SOptionElement, self).__init__(**kwargs)

        optionDict = paramDict.get("OptionDict")
        self.formulaId = optionDict.get("FormulaID")
        self.paraDesc = optionDict.get("ParaDesc")
        self.paraDict = {}
        self.paraStrDict = {}
        self.paraList = optionDict.get("ParameterList")
        for aDict in self.paraList:
            self.paraDict[aDict.get("Name")] = aDict

        self._objDict = {}
        self.size_hint = (1, .98)
        self.orientation = "horizontal"

        self._isSelected_id = CheckBox()
        self._isSelected_id.active = False
        self._isSelected_id.size_hint = (.1, 1)
        self._isSelected_id.color = colorHex("#000000")
        self.add_widget(self._isSelected_id)

        self.add_widget(BoxLayout(size_hint=(.01, 1)))

        self.contentLayout = BoxLayout(size_hint=(.89, 1),
                                       orientation="horizontal")
        self.add_widget(self.contentLayout)

        if self.hasFunc(self.paraDesc):
            strList = self.paraDesc.split(" ")
            for astr in strList:
                if self.hasFunc(astr):
                    paraName = astr[astr.find("#") + 1:]
                    self.paraStrDict[paraName] = astr
                    _atextInput = SOptionTextInput(paraName=paraName,
                                                   size_hint=(None, 1))
                    _atextInput.text = self.paraDict.get(paraName).get("Def")
                    _atextInput.width = 60
                    self.contentLayout.add_widget(_atextInput)
                    self._objDict[paraName] = _atextInput
                else:
                    _alabel = SLabel(text=astr, size_hint=(None, 1))
                    _alabel.width = self.calcStrWidth(astr)
                    _alabel.color = colorHex("#000000")
                    self.contentLayout.add_widget(_alabel)
        else:
            _alabel = SLabel(text=self.paraDesc, size_hint=(1, 1))
            _alabel.color = colorHex("#000000")
            self.contentLayout.add_widget(_alabel)

    def hasFunc(self, paraDesc):
        if paraDesc.find("#") != -1:
            return True
        else:
            return False

    def calcStrWidth(self, astr):
        strWidth = 0
        for i in range(len(astr)):
            if astr[i].isascii():
                strWidth += 10
            else:
                strWidth += 16
        return strWidth

    def isSelected(self):
        return self._isSelected_id.active

    def setToDefaultValue(self):
        self._isSelected_id.active = False
        if len(self._objDict) != 0:
            aObj = None
            for aKey in self._objDict.keys():
                aObj = self._objDict.get(aKey)
                aObj.text = self.paraDict.get(aObj.paraName).get("Def")

    def getOptionDesc(self):
        if len(self._objDict) == 0:
            return self.paraDesc
        result = self.paraDesc
        aObj = None
        for aKey in self._objDict.keys():
            aObj = self._objDict.get(aKey)
            paraStr = self.paraStrDict.get(aObj.paraName)
            result = result.replace(paraStr, aObj.text)
        return result

    def getValueDict(self):
        valueDict = {}
        paraStr = ""
        for adict in self.paraList:
            nameStr = adict.get("Name")
            atextInput = self._objDict.get(nameStr)
            if atextInput == None:
                paraStr += adict.get("Def")
                paraStr += "|"
            else:
                paraStr += atextInput.text
                paraStr += "|"
        if paraStr != "":
            paraStr = paraStr[:-1]
        valueDict["FormulaID"] = int(self.formulaId)
        valueDict["Parameter"] = paraStr
        return valueDict
Exemple #37
0
    def fire_popup(self):
        # this builds the interface inside the popup, then makes it appear on the screen
        f_widget = BoxLayout(orientation='vertical')
        self.pops.content = f_widget
        timeblock = BoxLayout(orientation='horizontal',
                              size_hint_y=None,
                              height=30)
        insInput1 = TextInput(multiline=False,
                              size_hint=(None, None),
                              height=30,
                              width=50,
                              input_filter='int',
                              hint_text='YYYY')
        insInput2 = TextInput(multiline=False,
                              size_hint=(None, None),
                              height=30,
                              width=30,
                              input_filter='int',
                              hint_text='M')
        insInput3 = TextInput(multiline=False,
                              size_hint=(None, None),
                              height=30,
                              width=30,
                              input_filter='int',
                              hint_text='D')
        insInput4 = TextInput(multiline=False,
                              size_hint=(None, None),
                              height=30,
                              width=30,
                              input_filter='int',
                              hint_text='h')
        insInput5 = TextInput(multiline=False,
                              size_hint=(None, None),
                              height=30,
                              width=30,
                              input_filter='int',
                              hint_text='m')
        insInput6 = TextInput(multiline=False,
                              size_hint=(None, None),
                              height=30,
                              width=30,
                              input_filter='int',
                              hint_text='s')
        if self.hasDate:
            insInput1.text = str(self.timeChunk1)
            insInput2.text = str(self.timeChunk2)
            insInput3.text = str(self.timeChunk3)
            insInput4.text = str(self.timeChunk4)
            insInput5.text = str(self.timeChunk5)
            insInput6.text = str(self.timeChunk6)
        else:
            insInput1.text = ""
            insInput2.text = ""
            insInput3.text = ""
            insInput4.text = ""
            insInput5.text = ""
            insInput6.text = ""
        cuteLabel1 = Label(text="Date", height=30)
        cuteLabel2 = Label(text="Time", height=30)

        timeblock.add_widget(cuteLabel1)
        timeblock.add_widget(insInput1)
        timeblock.add_widget(insInput2)
        timeblock.add_widget(insInput3)
        timeblock.add_widget(cuteLabel2)
        timeblock.add_widget(insInput4)
        timeblock.add_widget(insInput5)
        timeblock.add_widget(insInput6)
        f_widget.add_widget(Label())
        f_widget.add_widget(timeblock)
        f_widget.add_widget(Label())
        f_button1 = Button(text='submit button', on_press=self.pop_submit)
        f_button2 = Button(text='cancel button', on_press=self.pop_cancel)
        f_widget.add_widget(f_button1)
        f_widget.add_widget(f_button2)
        self.pops.open()
Exemple #38
0
class LeagueBase(Screen):
    """Base widget for football league summary screen."""
    leaguename = StringProperty("")

    def __init__(self, league, **kwargs):
        self.leagueid = league
        super(LeagueBase, self).__init__(**kwargs)
        self.leaguename = "Retrieving league information."
        self.running = False
        self.timer = None
        self.nextupdate = 0
        self.leaguestack = None
        self.newbox = None
        self.leaguebox = self.ids.league_box
        self.spacer = False
        self.h = 0

    def on_enter(self):
        """Works out if we're due an update or not and schedules the refesh as
           appropriate.
        """
        if not self.running:
            Clock.schedule_once(self.getLeagueObject, 0.5)

        tm = time.time()

        if tm > self.nextupdate:
            dt = 0.5
        else:
            dt = self.nextupdate - tm

        self.timer = Clock.schedule_once(self.update, dt)

    def on_leave(self):
        Clock.unschedule(self.timer)

    def getLeagueObject(self, *args):
        """Creates the league object if we don't have one yet."""
        if not self.running:
            self.leagueobject = League(self.leagueid, detailed=False)
            self.running = True
        self.checkscreen()

    def update(self, *args):
        # Reresh the league object data.
        self.leagueobject.Update()

        # Schedule the next update
        if self.leagueobject.HasFinished or not self.leagueobject:
            dt = 60 * 60
        else:
            dt = 30

        self.nextupdate = time.time() + dt
        self.timer = Clock.schedule_once(self.update, dt)

        # Update the screen.
        self.checkscreen()

    def checkscreen(self):
        """Updates the screen depending on the state of the league object."""
        # If there are league matches, clear the screen
        if self.leagueobject:
            self.leaguename = self.leagueobject.LeagueName
            if self.newbox:
                self.newbox.clear_widgets()
            else:
                self.newbox = BoxLayout(orientation="vertical",
                                        size_hint_y=0.8)
                self.leaguebox.add_widget(self.newbox)

            # Get the stack of league matches
            self.leaguestack = self.createStack()

            # And work out how to place it in the middle of the screen.
            if self.spacer:
                sph = ((self.parent.height * .8) - self.h) / 2.0
                self.newbox.add_widget(Widget(size_hint=(1, None), height=sph))

            self.newbox.add_widget(self.leaguestack)

            if self.spacer:
                self.newbox.add_widget(Widget(size_hint=(1, None), height=sph))

        # No league matches
        else:
            if self.newbox:
                self.leaguebox.remove_widget(self.newbox)
            self.leaguename = "No league matches found."

    def createStack(self):
        """Works out how to display the league matches.

        Layout depends on the number of matches found.
        """
        matches = self.leagueobject.LeagueMatches
        x = len(matches)

        # Single column, no scrolling
        if x <= 10:
            self.spacer = True
            w = 1
            scroll = False
            self.h = 42 * x

        # Dual columns, no scrolling
        elif x <= 20:
            self.spacer = False
            w = 0.5
            scroll = False
            self.h = round(x / 2.0) * 42

        # Dual columns, scrolling
        else:
            self.spacer = False
            w = 0.5
            scroll = True
            self.h = round(x / 2.0) * 42

        # Create a stack layout
        stack = StackLayout(orientation="tb-lr",
                            size_hint_y=None,
                            height=self.h)

        stack.bind(minimum_height=stack.setter('height'))

        # Add the league matches to it.
        for l in matches:
            lg = LeagueGame(match=l, size_hint=(w, None))
            stack.add_widget(lg)

        # Create a scroll view
        scroll = ScrollView(size_hint=(1, 1))
        scroll.add_widget(stack)

        return scroll

    def notifyEvent(self, event_type=EVT_HALF_TIME):
        """Animation for incident notifications."""
        t = EVT_LOOKUP[event_type]
        g = FootballEvent(eventtext=t["text"])
        self.ids.base_float.add_widget(g)
        in_anim = Animation(font_size=t["size"], d=1, t="out_back")
        in_anim &= Animation(bgcolour=[0, 0, 0, 1], d=1, t="out_expo")
        out_anim = Animation(font_size=0, d=1, t="out_back")
        out_anim &= Animation(bgcolour=[0, 0, 0, 0], d=1, t="out_expo")
        anim = in_anim + Animation(d=2.) + out_anim
        anim.bind(on_complete=self.notifyComplete)
        anim.start(g)

    def notifyComplete(self, anim, widget):
        anim.unbind()
        self.ids.base_float.remove_widget(widget)

    def showDetail(self, mo):
        pass
Exemple #39
0
    def choiceDrink(self, *args):
        self.readPumpConfiguration()
        if len(self.drinkOnScreen) - 1 < args[0]:
            print("no drinks found.")
            return

        ## Start Script to create Invoice
        print("start lnd-invoicetoqr.sh")
        subprocess.call("lnd/lnd-invoicetoqr.sh")
        print("end lnd-invoicetoqr.sh")

        root = BoxLayout(orientation='vertical')
        root2 = BoxLayout()
        root2.add_widget(Image(source='lnd/temp/tempQRCode.png'))
        root2.add_widget(
            Label(
                text=
                'Please be sure\n that a glass \nwith min 200 ml \nis placed onto the black fixture.',
                font_size='30sp'))
        root.add_widget(root2)

        ## This was commented out to be sure the user only gets a drink after paying the bill.
        #contentOK = Button(text='OK', font_size=60, size_hint_y=0.15)
        #root.add_widget(contentOK)

        contentCancel = Button(text='Cancel', font_size=60, size_hint_y=0.15)
        root.add_widget(contentCancel)

        popup = Popup(title='Not your coins, not your cocktail :-)',
                      content=root,
                      auto_dismiss=False)

        ## This was commented out to be sure the user only gets a drink after paying the bill.
        #def closeme(button):
        #    popup.dismiss()
        #    Clock.schedule_once(partial(self.doGiveDrink, args[0]), .01)

        ## This was commented out to be sure the user only gets a drink after paying the bill.
        #contentOK.bind(on_press=closeme)

        def cancelme(button):
            print("cancel button pressed")
            popup.dismiss()

        #Button cancel payment, is not working right now
        contentCancel.bind(on_press=cancelme)

        ## Beginn Function to periodically check the payment using lnd-checkinvoice1.sh
        def checkPayment(parent):

            print("start check script")

            ## while loop to check if lnd-checkinvoice1.sh returns SETTLED, if not wait for a second and start over
            paymentSettled = False
            counter = 0
            while paymentSettled == False:
                ## run lnd-checkinvoice1.sh and write output to variable s
                s = subprocess.check_output(["sh", "lnd/lnd-checkinvoice1.sh"])
                print(s)
                counter += 1
                print(counter)

                ## check if s is 'SETTLED', if so, close popup and start doGiveDrink
                if (b'SETTLED' in s):
                    paymentSettled = True
                    popup.dismiss()
                    Clock.schedule_once(partial(self.doGiveDrink, args[0]),
                                        .01)
                elif (counter > 60):
                    paymentSettled = True
                    popup.dismiss()
                    Clock.schedule_once(partial(self.doGiveDrink, args[0]),
                                        .01)
                else:
                    ## if not 'SETTLED' wait a second and start over
                    paymentSettled = False
                    time.sleep(1)
                pass
            pass

            print("end check script")
            ## End Function to periodically check the payment using lnd-checkinvoice1.sh

        ## start 'checkPayment-loop' when loading popup
        popup.bind(on_open=checkPayment)

        popup.open()
    def popupfunc(self, event):
        """
        creates a popup asking if the user wishes to swap a character from team to subs
        then proceeds to allow user to choose who swaps
        """
        def subscroll(self):
            """
            opens scroll list of substitute characters in a popup
            """
            for btn in SMApp.teamlist:
                if btn.state == 'down':
                    SMApp.nameOff = btn
                    btn.state = 'normal'

            curs.execute('SELECT * FROM Subs')
            layout2 = GridLayout(cols=2, spacing=10, size_hint_y=None)
            layout2.bind(minimum_height=layout2.setter('height'))
            for row in curs:
                btn = ToggleButton(text=str(row[0]),
                                   size_hint_y=None,
                                   height=40)
                if row[1] == 1:
                    btn.background_color = (0.5, 1, 0.9, 1)
                layout2.add_widget(btn)
                btn.bind(on_press=subChar)
                SMApp.sublist.append(btn)
                lbl = Label(text=str(row[2]), size_hinty=None, height=40)
                layout2.add_widget(lbl)
            root = ScrollView(size_hint=(None, None), size=(400, 400))
            root.add_widget(layout2)
            SMApp.popup2 = Popup(content=root,
                                 size=(7, 10),
                                 size_hint=(0.55, 0.8),
                                 title="list of subs")

            SMApp.popup2.open()

        def DismissPopup1(self):
            popup1.dismiss()
            for btn in SMApp.teamlist:
                if btn.state == 'down':
                    btn.state = 'normal'

        box = BoxLayout()
        btn1 = Button(text='yeah ok')
        btn2 = Button(text='nope')
        popup1 = Popup(content=box,
                       size=(10, 10),
                       size_hint=(0.3, 0.3),
                       title="substitute from team?")
        btn2.bind(on_press=DismissPopup1)
        btn1.bind(on_press=subscroll)
        box.add_widget(btn1)
        box.add_widget(btn2)

        popup1.open()

        def subChar(self):
            for btn in SMApp.sublist:
                if btn.state == 'down':
                    if btn.background_color == SMApp.nameOff.background_color:
                        SMApp.nameOn = btn.text
                        btn.state = 'normal'
                        add(SMApp.nameOn, 'Team')
                        remove(SMApp.nameOn, 'Subs')
                        add(SMApp.nameOff.text, 'Subs')
                        remove(SMApp.nameOff.text, 'Team')
                        popup1.dismiss()
                        SMApp.popup2.dismiss()
                    else:
                        btn.state = 'normal'
                        popupNO = Popup(
                            title=
                            'you cannot swap characters of different tiers!',
                            size_hint=(0.3, 0.3))
                        popupNO.open()
                        SMApp.popup2.dismiss()
                        popup1.dismiss()
Exemple #41
0
 def _draw_form(self):
     """
     Encompasses the drawing of a form with a textual label onto the card.
     """
     inner_layout = BoxLayout(orientation="vertical")
     label_layout = BoxLayout(orientation="vertical", size_hint=(1, 0.2))
     self.form_label = Label(
         text=self.text, font_size=self.font_size, markup=True
     )
     self.form_label.color = list(self.text_color)
     self.form_label.valign = "top"
     self.form_label.halign = "left"
     label_layout.add_widget(self.form_label)
     form_layout = BoxLayout(orientation="vertical")
     form_layout.padding = 10
     filler = None
     if self.form == Inputs.TEXTBOX:
         self.textbox = TextInput(text="", multiline=False)
         self.textbox.font_size = self.font_size
         form_layout.size_hint = (1, 0.2)
         form_layout.add_widget(self.textbox)
         filler = BoxLayout(orientation="vertical", size_hint=(1, 0.6))
     elif self.form == Inputs.TEXTAREA:
         self.textarea = TextInput(text="")
         self.textarea.font_size = self.font_size
         form_layout.add_widget(self.textarea)
     elif self.form == Inputs.MULTICHOICE:
         self.multichoice = []
         for item in self.options:
             button = ToggleButton(text=item)
             button.font_size = self.font_size
             form_layout.add_widget(button)
             self.multichoice.append(button)
     elif self.form == Inputs.SELECT:
         self.select = []
         for item in self.options:
             button = ToggleButton(text=item, group=self.title)
             button.font_size = self.font_size
             form_layout.add_widget(button)
             self.select.append(button)
     elif self.form == Inputs.SLIDER:
         min_val = self.options[0]
         max_val = self.options[1]
         if len(self.options) == 3:
             step = self.options[2]
         else:
             step = 1
         self.slider = Slider(
             value_track=True, min=min_val, max=max_val, step=step
         )
         self.slider_label = Label(text="0", font_size=64)
         self.slider.bind(value=self._slider_change)
         form_layout.add_widget(self.slider)
         form_layout.add_widget(self.slider_label)
     inner_layout.add_widget(label_layout)
     inner_layout.add_widget(form_layout)
     if filler:
         inner_layout.add_widget(filler)
     self.layout.add_widget(inner_layout)
Exemple #42
0
    def __init__(self, **kwargs):
        super(AttributesTab, self).__init__(**kwargs)
        strength_box = BoxLayout(orientation='horizontal',
                                 size_hint=(1.5, .5),
                                 pos_hint={
                                     'center_x': .5,
                                     'center_y': .5
                                 },
                                 spacing=5)
        strength_label = Label(text='Strength', size_hint=(.4, 1))
        strength_score = TextInput(multiline=False)
        strength_enh_mod = TextInput(multiline=False)
        strength_misc_mod = TextInput(multiline=False)
        strength_temp_score = Label(text='0', size_hint=(.3, 1))
        strength_box.add_widget(strength_label)
        strength_box.add_widget(strength_score)
        strength_box.add_widget(strength_enh_mod)
        strength_box.add_widget(strength_misc_mod)
        strength_box.add_widget(strength_temp_score)

        dexterity_box = BoxLayout(orientation='horizontal',
                                  size_hint=(1.5, .5),
                                  pos_hint={
                                      'center_x': .5,
                                      'center_y': .5
                                  },
                                  spacing=5)
        dexterity_label = Label(text='Dexterity', size_hint=(.4, 1))
        dexterity_score = TextInput(multiline=False)
        dexterity_enh_mod = TextInput(multiline=False)
        dexterity_misc_mod = TextInput(multiline=False)
        dexterity_temp_score = Label(text='0', size_hint=(.3, 1))
        dexterity_box.add_widget(dexterity_label)
        dexterity_box.add_widget(dexterity_score)
        dexterity_box.add_widget(dexterity_enh_mod)
        dexterity_box.add_widget(dexterity_misc_mod)
        dexterity_box.add_widget(dexterity_temp_score)

        constitution_box = BoxLayout(orientation='horizontal',
                                     size_hint=(1.5, .5),
                                     pos_hint={
                                         'center_x': .5,
                                         'center_y': .5
                                     },
                                     spacing=5)
        constitution_label = Label(text='Constitution', size_hint=(.4, 1))
        constitution_score = TextInput(multiline=False)
        constitution_enh_mod = TextInput(multiline=False)
        constitution_misc_mod = TextInput(multiline=False)
        constitution_temp_score = Label(text='0', size_hint=(.3, 1))
        constitution_box.add_widget(constitution_label)
        constitution_box.add_widget(constitution_score)
        constitution_box.add_widget(constitution_enh_mod)
        constitution_box.add_widget(constitution_misc_mod)
        constitution_box.add_widget(constitution_temp_score)

        intelligence_box = BoxLayout(orientation='horizontal',
                                     size_hint=(1.5, .5),
                                     pos_hint={
                                         'center_x': .5,
                                         'center_y': .5
                                     },
                                     spacing=5)
        intelligence_label = Label(text='Intelligence', size_hint=(.4, 1))
        intelligence_score = TextInput(multiline=False)
        intelligence_enh_mod = TextInput(multiline=False)
        intelligence_misc_mod = TextInput(multiline=False)
        intelligence_temp_score = Label(text='0', size_hint=(.3, 1))
        intelligence_box.add_widget(intelligence_label)
        intelligence_box.add_widget(intelligence_score)
        intelligence_box.add_widget(intelligence_enh_mod)
        intelligence_box.add_widget(intelligence_misc_mod)
        intelligence_box.add_widget(intelligence_temp_score)

        wisdom_box = BoxLayout(orientation='horizontal',
                               size_hint=(1.5, .5),
                               pos_hint={
                                   'center_x': .5,
                                   'center_y': .5
                               },
                               spacing=5)
        wisdom_label = Label(text='Wisdom', size_hint=(.4, 1))
        wisdom_score = TextInput(multiline=False)
        wisdom_enh_mod = TextInput(multiline=False)
        wisdom_misc_mod = TextInput(multiline=False)
        wisdom_temp_score = Label(text='0', size_hint=(.3, 1))
        wisdom_box.add_widget(wisdom_label)
        wisdom_box.add_widget(wisdom_score)
        wisdom_box.add_widget(wisdom_enh_mod)
        wisdom_box.add_widget(wisdom_misc_mod)
        wisdom_box.add_widget(wisdom_temp_score)

        charisma_box = BoxLayout(orientation='horizontal',
                                 size_hint=(1.5, .5),
                                 pos_hint={
                                     'center_x': .5,
                                     'center_y': .5
                                 },
                                 spacing=5)
        charisma_label = Label(text='Charisma', size_hint=(.4, 1))
        charisma_score = TextInput(multiline=False)
        charisma_enh_mod = TextInput(multiline=False)
        charisma_misc_mod = TextInput(multiline=False)
        charisma_temp_score = Label(text='0', size_hint=(.3, 1))
        charisma_box.add_widget(charisma_label)
        charisma_box.add_widget(charisma_score)
        charisma_box.add_widget(charisma_enh_mod)
        charisma_box.add_widget(charisma_misc_mod)
        charisma_box.add_widget(charisma_temp_score)

        ability_score_box = BoxLayout(orientation='vertical',
                                      size_hint=(.35, .3),
                                      pos_hint={
                                          'center_x': .28,
                                          'center_y': .725
                                      })

        ability_score_box.add_widget(strength_box)
        ability_score_box.add_widget(dexterity_box)
        ability_score_box.add_widget(constitution_box)
        ability_score_box.add_widget(intelligence_box)
        ability_score_box.add_widget(wisdom_box)
        ability_score_box.add_widget(charisma_box)

        ability_score_names = BoxLayout(orientation='horizontal',
                                        pos_hint={
                                            'center_x': .25,
                                            'center_y': .9
                                        },
                                        size_hint=(.40, .5),
                                        spacing=100)
        ability_score_names.add_widget(Label(text='Ability'))
        ability_score_names.add_widget(Label(text='Score'))
        ability_score_names.add_widget(Label(text='Enh Mod'))
        ability_score_names.add_widget(Label(text='Misc Mod'))
        ability_score_names.add_widget(Label(text='Temp Score'))

        hp_box = BoxLayout(orientation='horizontal',
                           size_hint=(.6, .25),
                           pos_hint={
                               'center_x': .25,
                               'center_y': .55
                           },
                           spacing=5)
        hp_label = Label(text='HP',
                         size_hint=(.8, .2),
                         text_size=self.size,
                         halign='right',
                         valign='middle')
        hp_total = TextInput(multiline=False, size_hint=(.8, .2))
        hp_current = TextInput(multiline=False, size_hint=(.8, .2))
        hp_current = TextInput(multiline=False, size_hint=(.8, .2))
        hp_non_lethal_damage = TextInput(multiline=False, size_hint=(.8, .2))
        hp_hit_dice = TextInput(multiline=False, size_hint=(.8, .2))
        hp_damage_reduction = TextInput(multiline=False, size_hint=(.8, .2))

        hp_box.add_widget(hp_label)
        hp_box.add_widget(hp_total)
        hp_box.add_widget(hp_current)
        hp_box.add_widget(hp_non_lethal_damage)
        hp_box.add_widget(hp_hit_dice)
        hp_box.add_widget(hp_damage_reduction)

        hp_names = BoxLayout(orientation='horizontal',
                             pos_hint={
                                 'center_x': .3,
                                 'center_y': .5
                             },
                             size_hint=(.5, .5),
                             spacing=5)
        hp_names.add_widget(Label(text='Total'))
        hp_names.add_widget(Label(text='Current HP'))
        hp_names.add_widget(Label(text='Nonlethal Damage'))
        hp_names.add_widget(Label(text='Hit Dice'))
        hp_names.add_widget(Label(text='Damage Reduction'))

        ac_box = BoxLayout(orientation='horizontal',
                           size_hint=(.6, .25),
                           pos_hint={
                               'center_x': .29,
                               'center_y': .45
                           })
        ac_label = Label(text='AC',
                         size_hint=(.8, .2),
                         text_size=self.size,
                         halign='center',
                         valign='middle')
        ac_total = TextInput(multiline=False, size_hint=(.8, .2))
        ac_armor = TextInput(multiline=False, size_hint=(.8, .2))
        ac_sheild = TextInput(multiline=False, size_hint=(.8, .2))
        ac_mod = TextInput(multiline=False, size_hint=(.8, .2))
        ac_size = TextInput(multiline=False, size_hint=(.8, .2))
        ac_deflect = TextInput(multiline=False, size_hint=(.8, .2))
        ac_natural = TextInput(multiline=False, size_hint=(.8, .2))
        ac_dodge = TextInput(multiline=False, size_hint=(.8, .2))
        ac_misc = TextInput(multiline=False, size_hint=(.8, .2))
        ac_box.add_widget(ac_label)
        ac_box.add_widget(ac_total)
        ac_box.add_widget(ac_armor)
        ac_box.add_widget(ac_sheild)
        ac_box.add_widget(ac_mod)
        ac_box.add_widget(ac_size)
        ac_box.add_widget(ac_deflect)
        ac_box.add_widget(ac_natural)
        ac_box.add_widget(ac_dodge)
        ac_box.add_widget(ac_misc)

        ac_names = BoxLayout(orientation='horizontal',
                             pos_hint={
                                 'center_x': .31,
                                 'center_y': .4
                             },
                             size_hint=(.55, .5))
        ac_names.add_widget(Label(text='Total'))
        ac_names.add_widget(Label(text='Armor'))
        ac_names.add_widget(Label(text='Shield'))
        ac_names.add_widget(Label(text='Mod'))
        ac_names.add_widget(Label(text='Size'))
        ac_names.add_widget(Label(text='Deflect'))
        ac_names.add_widget(Label(text='Natural'))
        ac_names.add_widget(Label(text='Dodge'))
        ac_names.add_widget(Label(text='Misc'))

        initiative_box = BoxLayout(orientation='horizontal',
                                   size_hint=(.3, .25),
                                   pos_hint={
                                       'center_x': .15,
                                       'center_y': .33
                                   })
        initiative_label = Label(text='Initiative',
                                 size_hint=(.8, .2),
                                 text_size=self.size,
                                 halign='center',
                                 valign='middle')
        initiative_total = TextInput(multiline=False, size_hint=(.8, .2))
        initiative_dex = TextInput(multiline=False, size_hint=(.8, .2))
        initiative_misc = TextInput(multiline=False, size_hint=(.8, .2))
        initiative_speed = TextInput(multiline=False, size_hint=(.8, .2))
        initiative_armor_type = TextInput(multiline=False, size_hint=(.8, .2))
        initiative_box.add_widget(initiative_label)
        initiative_box.add_widget(initiative_total)
        initiative_box.add_widget(initiative_dex)
        initiative_box.add_widget(initiative_misc)
        initiative_box.add_widget(initiative_speed)
        initiative_box.add_widget(initiative_armor_type)

        initiative_names = BoxLayout(orientation='horizontal',
                                     pos_hint={
                                         'center_x': .17,
                                         'center_y': .28
                                     },
                                     size_hint=(.26, .5))
        initiative_names.add_widget(Label(text='Total'))
        initiative_names.add_widget(Label(text='Dex'))
        initiative_names.add_widget(Label(text='Misc'))
        initiative_names.add_widget(Label(text='Speed'))
        initiative_names.add_widget(Label(text='Armor Type'))

        fortitude_box = BoxLayout(orientation='horizontal',
                                  size_hint=(1.5, .2),
                                  pos_hint={
                                      'center_x': .5,
                                      'center_y': .5
                                  },
                                  spacing=5)
        fortitude_label = Label(text='Fortitude',
                                size_hint=(.8, .2),
                                text_size=self.size,
                                halign='center',
                                valign='middle')
        fortitude_total = TextInput(multiline=False, size_hint=(.8, .4))
        fortitude_base = TextInput(multiline=False, size_hint=(.8, .4))
        fortitude_ability_mod = TextInput(multiline=False, size_hint=(.8, .4))
        fortitude_magic_mod = TextInput(multiline=False, size_hint=(.8, .4))
        fortitude_misc_mod = TextInput(multiline=False, size_hint=(.8, .4))
        fortitude_temp = TextInput(multiline=False, size_hint=(.8, .4))
        fortitude_box.add_widget(fortitude_label)
        fortitude_box.add_widget(fortitude_total)
        fortitude_box.add_widget(fortitude_base)
        fortitude_box.add_widget(fortitude_ability_mod)
        fortitude_box.add_widget(fortitude_magic_mod)
        fortitude_box.add_widget(fortitude_misc_mod)
        fortitude_box.add_widget(fortitude_temp)

        reflex_box = BoxLayout(orientation='horizontal',
                               size_hint=(1.5, .2),
                               pos_hint={
                                   'center_x': .5,
                                   'center_y': .5
                               },
                               spacing=5)
        reflex_label = Label(text='Reflex',
                             size_hint=(.8, .4),
                             text_size=self.size,
                             halign='center',
                             valign='middle')
        reflex_total = TextInput(multiline=False, size_hint=(.8, .4))
        reflex_base = TextInput(multiline=False, size_hint=(.8, .4))
        reflex_ability_mod = TextInput(multiline=False, size_hint=(.8, .4))
        reflex_magic_mod = TextInput(multiline=False, size_hint=(.8, .4))
        reflex_misc_mod = TextInput(multiline=False, size_hint=(.8, .4))
        reflex_temp = TextInput(multiline=False, size_hint=(.8, .4))
        reflex_box.add_widget(reflex_label)
        reflex_box.add_widget(reflex_total)
        reflex_box.add_widget(reflex_base)
        reflex_box.add_widget(reflex_ability_mod)
        reflex_box.add_widget(reflex_magic_mod)
        reflex_box.add_widget(reflex_misc_mod)
        reflex_box.add_widget(reflex_temp)

        will_box = BoxLayout(orientation='horizontal',
                             size_hint=(1.5, .2),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .5
                             },
                             spacing=5)
        will_label = Label(text='Will',
                           size_hint=(.8, .4),
                           text_size=self.size,
                           halign='center',
                           valign='middle')
        will_total = TextInput(multiline=False, size_hint=(.8, .4))
        will_base = TextInput(multiline=False, size_hint=(.8, .4))
        will_ability_mod = TextInput(multiline=False, size_hint=(.8, .4))
        will_magic_mod = TextInput(multiline=False, size_hint=(.8, .4))
        will_misc_mod = TextInput(multiline=False, size_hint=(.8, .4))
        will_temp = TextInput(multiline=False, size_hint=(.8, .4))
        will_box.add_widget(will_label)
        will_box.add_widget(will_total)
        will_box.add_widget(will_base)
        will_box.add_widget(will_ability_mod)
        will_box.add_widget(will_magic_mod)
        will_box.add_widget(will_misc_mod)
        will_box.add_widget(will_temp)

        saving_throws_box = BoxLayout(orientation='vertical',
                                      size_hint=(.3, .4),
                                      pos_hint={
                                          'center_x': .77,
                                          'center_y': .75
                                      })
        saving_throws_box.add_widget(fortitude_box)
        saving_throws_box.add_widget(reflex_box)
        saving_throws_box.add_widget(will_box)

        base_attack_box = BoxLayout(orientation='horizontal',
                                    size_hint=(1, .5),
                                    pos_hint={
                                        'center_x': .5,
                                        'center_y': .5
                                    })
        base_attack_label = Label(text='Base Attack')
        base_attack_input = TextInput(multiline=False)
        base_attack_box.add_widget(base_attack_label)
        base_attack_box.add_widget(base_attack_input)

        cmb_box = BoxLayout(orientation='horizontal',
                            size_hint=(.2, .25),
                            pos_hint={
                                'center_x': .8,
                                'center_y': .5
                            })
        cmb_label = Label(text='CMB',
                          size_hint=(.1, .2),
                          text_size=self.size,
                          halign='center',
                          valign='middle')
        cmb_input = TextInput(multiline=False, size_hint=(.1, .2))
        cmb_box.add_widget(cmb_label)
        cmb_box.add_widget(cmb_input)

        cmd_box = BoxLayout(orientation='horizontal',
                            size_hint=(.2, .25),
                            pos_hint={
                                'center_x': .8,
                                'center_y': .4
                            })
        cmd_label = Label(text='CMD',
                          size_hint=(.1, .2),
                          text_size=self.size,
                          halign='center',
                          valign='middle')
        cmd_input = TextInput(multiline=False, size_hint=(.1, .2))
        cmd_box.add_widget(cmd_label)
        cmd_box.add_widget(cmd_input)

        content = FloatLayout()
        content.add_widget(ability_score_box)
        content.add_widget(ability_score_names)
        content.add_widget(hp_box)
        content.add_widget(hp_names)
        content.add_widget(ac_box)
        content.add_widget(ac_names)
        content.add_widget(saving_throws_box)
        content.add_widget(initiative_box)
        content.add_widget(initiative_names)
        content.add_widget(cmd_box)
        content.add_widget(cmb_box)

        self.content = content
        self.text = 'Attributes'
from Controllers.SpiceSelection import SpiceSelection
from Controllers.Banner import Banner


# Initial Configuration
Config.set('graphics', 'width', '800')
Config.set('graphics', 'height', '480')
Config.set('graphics', 'resizable', 0)

# Load File from Views
Builder.load_file("Views/Homepage.kv")
Builder.load_file("Views/SpiceSelection.kv")
Builder.load_file("Views/Banner.kv")
# Add to screen manager
screenManager = ScreenManager(transition=FadeTransition())
screenManager.add_widget(Homepage(name='Homepage'))
screenManager.add_widget(SpiceSelection(name='SpiceSelection'))

layout = BoxLayout(orientation='vertical')
# layout.add_widget(Banner())
layout.add_widget(screenManager)


class SpiceMixerApp(App):
    def build(self):
        return layout


if __name__ == '__main__':
    SpiceMixerApp().run()
Exemple #44
0
class Card:
    """
    Represents a "card" in the application. This is a node in a series of
    possible UI states. Transitions between states are generally facilitated by
    button presses with either an associated string containing the title of the
    target card, or a function (containing "business logic") which returns a
    string identifying the next card.

    Each node has pre-defined attributes which describe the appearance of
    the card and the behaviour for transitioning to other cards in the
    application. These are set and verified upon initialisation.

    :param str title: The unique meaningful title/id of the card.
    :param str text: The textual content of the card.
    :param str text_color: The colour of the textual content of the card.
    :param int text_size: The font size of the textual content of the card.
    :param Inputs form: The form input element to display on the card.
    :param tuple options: The form input element's multiple options.
    :param str sound: The path to the sound file to play with the card.
    :param bool sound_repeat: A flag to indicate if the card's sound loops.
    :param str background: Either a colour or path to background image.
    :param list buttons: A list containing button definitions as
        dictionaries containing label and transition attributes with optional
        text_size, text_color and background_color attributes.
    :param float auto_advance: The number of seconds to wait before
        advancing to the auto_target card.
    :param auto_target: Either a string or function returning a string
        referencing the target card for auto-advancement.
    :raises ValueError: If the states passed in are inconsistent.
    """

    def __init__(
        self,
        title,
        text=None,
        text_color=None,
        text_size=48,
        form=None,
        options=None,
        sound=None,
        sound_repeat=False,
        background=None,
        buttons=None,
        auto_advance=0,
        auto_target=None,
    ):
        """
        Initialise and check the state of the Card. Will raise an exception if
        the passed in state is inconsistent.
        """
        self.title = title
        if text_color is None:
            self.text_color = palette("white")
        if isinstance(text_color, str):
            self.text_color = palette(text_color)
        if isinstance(background, str):
            try:
                # Check if / use when the background is the name of a colour.
                background = palette(background)
            except ValueError:
                # Assume the background string is a reference to an image file.
                pass
        if buttons is None:
            buttons = []
        self.text = text
        self.text_size = text_size
        self.form = form
        self.options = options
        self.sound = sound
        self.sound_repeat = sound_repeat
        self.background = background
        self.buttons = buttons
        self.auto_advance = auto_advance
        self.auto_target = auto_target
        # Will contain references to any buttons used by the card.
        self.button_widgets = []
        # Will become a reference to any scheduled auto advance transition.
        self.auto_event = None
        self._verify()

    def _verify(self):
        """
        Ensure the combination of attributes given for this card are compatible
        and valid. Will raise a helpful exception if there are problems.

        :raises ValueError: if inconsistencies in the form's attributes are
        found.
        """
        if self.form and not self.text:
            # A form MUST have a descriptive textual label (instructions).
            raise ValueError(f"Card '{self.title}' must have a form label.")
        if self.form == Inputs.MULTICHOICE or self.form == Inputs.SELECT:
            # There must be an options list for multichoice or select forms.
            if isinstance(self.options, tuple) or isinstance(
                self.options, list
            ):
                # All options must be strings.
                if not all(isinstance(item, str) for item in self.options):
                    raise ValueError(
                        f"Card '{self.title}' form options must be strings."
                    )
            else:
                raise ValueError(
                    f"Card '{self.title}' form must have an options list."
                )
        if self.form == Inputs.SLIDER:
            # Slider must have options containing min, max and optional step.
            if isinstance(self.options, tuple) or isinstance(
                self.options, list
            ):
                length = len(self.options)
                if length == 2 or length == 3:
                    # All options must be integers.
                    if not all(
                        isinstance(item, (int, float)) for item in self.options
                    ):
                        raise ValueError(
                            f"Card '{self.title}' form options must be "
                            "integers."
                        )
                else:
                    raise ValueError(
                        f"Card '{self.title}' form must have no less than "
                        "two, or more than three options to define the range "
                        "of slider."
                    )
            else:
                raise ValueError(
                    f"Card '{self.title}' form must have options for min, max "
                    "and step range of slider."
                )
        if self.buttons:
            # Ensure every button is defined by a dictionary with the
            # expected attributes and values.
            for button in self.buttons:
                if isinstance(button, dict):
                    # Buttons must be expressed as dictionaries.
                    if "label" in button and "target" in button:
                        # Buttons must contain "label" and "target" attributes.
                        if not isinstance(button["label"], str):
                            # Labels must be strings.
                            raise ValueError(
                                f"Card '{self.title}' has a button whose "
                                "label is not a string."
                            )
                        if not (
                            isinstance(button["target"], str)
                            or callable(button["target"])
                        ):
                            # Targets must be strings or callables.
                            raise ValueError(
                                f"Card '{self.title}' has a button whose "
                                "target is not a string or function."
                            )
                    else:
                        raise ValueError(
                            f"Card '{self.title}' has a button definition "
                            "that does not contain the expected 'label' and "
                            "'target' keys."
                        )
                else:
                    raise ValueError(
                        f"Card '{self.title}' has a button definition that is "
                        "not expressed as a dictionary."
                    )
        if self.auto_advance and not self.auto_target:
            # If there's an auto_advance value, there must be a target card.
            raise ValueError(
                f"Card '{self.title}' must have a duration and target to "
                "auto-advance to the next card."
            )

    def screen(self, screen_manager, data_store):
        """
        Return a screen instance containing all the necessary UI items that
        have been associated with the expected event handlers.

        :param kivy.uix.screenmanager.ScreenManager screen_manager: The UI
            stack of screens which controls which card is to be displayed.
        :param dict data_store: A dictionary containing application state.
        :return: A graphical representation of the card.
        """
        # References to app related objects.
        self.screen_manager = screen_manager
        self.data_store = data_store
        # The Kivy Screen instance used to draw the UI.
        screen = Screen(name=self.title)
        # Bind event handlers to life-cycle events.
        screen.bind(on_enter=self._enter)
        screen.bind(on_pre_enter=self._pre_enter)
        screen.bind(on_pre_leave=self._leave)
        # The main layout that defines how UI elements are drawn.
        self.layout = BoxLayout(orientation="vertical")
        screen.add_widget(self.layout)
        # The sound player for this card.
        self.player = None
        # Text font size for the Screen instance.
        self.font_size = "{}sp".format(self.text_size)
        if self.form:
            self._draw_form()
        elif self.text:
            self._draw_text()
        else:
            # For padding purposes.
            self.layout.add_widget(Label(text=" "))
        if self.sound:
            self.player = SoundLoader.load(self.sound)
            self.player.loop = self.sound_repeat
        if self.background:
            self.layout.bind(size=self._update_rect, pos=self._update_rect)
            with self.layout.canvas.before:
                if isinstance(self.background, tuple):
                    Color(*self.background)
                    self.rect = Rectangle(
                        size=self.layout.size, pos=self.layout.pos
                    )
                else:
                    self.rect = Rectangle(
                        source=self.background,
                        size=self.layout.size,
                        pos=self.layout.pos,
                    )
        if self.buttons:
            self._draw_buttons()
        return screen

    def _draw_text(self):
        """
        Encompasses the drawing of a single textual block onto the card.
        """
        self.text_label = Label(
            text=self.text, font_size=self.font_size, markup=True
        )
        self.text_label.color = list(self.text_color)
        self.text_label.padding = 10, 10
        self.text_label.text_size = (Window.width, Window.height)
        self.text_label.valign = "middle"
        self.text_label.halign = "center"
        self.layout.add_widget(self.text_label)

    def _draw_form(self):
        """
        Encompasses the drawing of a form with a textual label onto the card.
        """
        inner_layout = BoxLayout(orientation="vertical")
        label_layout = BoxLayout(orientation="vertical", size_hint=(1, 0.2))
        self.form_label = Label(
            text=self.text, font_size=self.font_size, markup=True
        )
        self.form_label.color = list(self.text_color)
        self.form_label.valign = "top"
        self.form_label.halign = "left"
        label_layout.add_widget(self.form_label)
        form_layout = BoxLayout(orientation="vertical")
        form_layout.padding = 10
        filler = None
        if self.form == Inputs.TEXTBOX:
            self.textbox = TextInput(text="", multiline=False)
            self.textbox.font_size = self.font_size
            form_layout.size_hint = (1, 0.2)
            form_layout.add_widget(self.textbox)
            filler = BoxLayout(orientation="vertical", size_hint=(1, 0.6))
        elif self.form == Inputs.TEXTAREA:
            self.textarea = TextInput(text="")
            self.textarea.font_size = self.font_size
            form_layout.add_widget(self.textarea)
        elif self.form == Inputs.MULTICHOICE:
            self.multichoice = []
            for item in self.options:
                button = ToggleButton(text=item)
                button.font_size = self.font_size
                form_layout.add_widget(button)
                self.multichoice.append(button)
        elif self.form == Inputs.SELECT:
            self.select = []
            for item in self.options:
                button = ToggleButton(text=item, group=self.title)
                button.font_size = self.font_size
                form_layout.add_widget(button)
                self.select.append(button)
        elif self.form == Inputs.SLIDER:
            min_val = self.options[0]
            max_val = self.options[1]
            if len(self.options) == 3:
                step = self.options[2]
            else:
                step = 1
            self.slider = Slider(
                value_track=True, min=min_val, max=max_val, step=step
            )
            self.slider_label = Label(text="0", font_size=64)
            self.slider.bind(value=self._slider_change)
            form_layout.add_widget(self.slider)
            form_layout.add_widget(self.slider_label)
        inner_layout.add_widget(label_layout)
        inner_layout.add_widget(form_layout)
        if filler:
            inner_layout.add_widget(filler)
        self.layout.add_widget(inner_layout)

    def _draw_buttons(self):
        """
        Encompasses the drawing of buttons onto the card.
        """
        button_layout = BoxLayout(orientation="horizontal", size_hint=(1, 0.2))
        for button in self.buttons:
            b = Button(text=button["label"])
            b.bind(on_press=self._button_click(button["target"]))
            if "text_size" in button:
                b.font_size = button["text_size"]
            else:
                b.font_size = 24
            if "text_color" in button:
                b.color = palette(button["text_color"])
            else:
                b.color = palette("white")
            if "background_color" in button:
                b.background_color = palette(button["background_color"])
            else:
                b.background_color = palette("grey")
            self.button_widgets.append(b)
            button_layout.add_widget(b)
        self.layout.add_widget(button_layout)

    def form_value(self):
        """
        Return the value obtained from the user via the form associated with
        this card. Return None if no form is specified.

        :return: The value currently set for this card's form.
        """
        if self.form and self.layout:  # There must be rendered form widgets.
            if self.form == Inputs.TEXTBOX:
                return self.textbox.text
            elif self.form == Inputs.TEXTAREA:
                return self.textarea.text
            elif self.form == Inputs.MULTICHOICE:
                return [
                    toggle.text
                    for toggle in self.multichoice
                    if toggle.state == "down"
                ]
            elif self.form == Inputs.SELECT:
                for button in self.select:
                    if button.state == "down":
                        return button.text
                return None
            elif self.form == Inputs.SLIDER:
                return float(self.slider_label.text)
        else:
            return None

    def _pre_enter(self, card):
        """
        Called immediately before the card is displayed to the user. Ensure
        that all the UI elements containing textual values are formatted with
        values from the data_store dictionary.
        """
        if self.form:
            self.form_label.text = self.text.format(**self.data_store)
        elif self.text:
            self.text_label.text = self.text.format(**self.data_store)
        for i in range(len(self.button_widgets)):
            self.button_widgets[i].text = self.buttons[i]["label"].format(
                **self.data_store
            )

    def _enter(self, card):
        """
        Called when the card is displayed to the user. Ensure that any sound
        associated with the card starts to play and, if necessary, auto_advance
        is scheduled.
        """
        if self.player:
            self.player.play()
            self.player.seek(0)
        if self.auto_advance:
            self.auto_event = Clock.schedule_once(
                self._next_card, self.auto_advance
            )

    def _leave(self, card):
        """
        Called when the card is hidden from the user. Ensure that any sound
        associated with the card is stopped.
        """
        if self.player:
            self.player.stop()
        if self.auto_event:
            self.auto_event.cancel()
            self.auto_event = None

    def _update_rect(self, instance, value):
        """
        Ensure that the rectangle (containing the background image, if set) is
        resized if the application is resized.
        """
        self.rect.pos = instance.pos
        self.rect.size = instance.size

    def _button_click(self, target):
        """
        Return a callable to handle a button click that correctly transitions
        to the next card given the value of the target argument.

        If target is a string, transition to the card identified by that
        string.

        If target is a callable, call the function and transition to the card
        identified by the string result.
        """

        def on_click(button):
            if callable(target):
                next_card = target(self.data_store, self.form_value())
            else:
                next_card = target
            self.screen_manager.current = next_card

        return on_click

    def _slider_change(self, slider, value):
        """
        An event handler to ensure the slider's label always displays the
        current slider value.
        """
        self.slider_label.text = str(float(value))

    def _next_card(self, time_taken):
        """
        Transition to the next card according to the value of auto_target.

        If auto_target is a string, transition to the card identified by that
        string.

        If auto_target is a callable, call the function and transition to the
        card identified by the string result.
        """
        if callable(self.auto_target):
            next_card = self.auto_target(self.data_store, self.form_value())
        else:
            next_card = self.auto_target
        self.screen_manager.current = next_card
class LoginMenu(BoxLayout):
    # Login Menu with all the input and button widgets where main login box is
    def logincheck(self, instance):
        # check whether the user have access to further application
        self.query = "SELECT * FROM logindetails WHERE username = '******' AND acctype='{}' ".format(
            self.UN.I.text, self.AS.acc.text)
        cursor.execute(self.query)
        self.validcheck = cursor.fetchone()
        if self.PW.I.text == '' or self.validcheck == None:
            self.p = PopUp()
            self.p.set()
            self.p.open()
        else:
            if self.PW.I.text == self.validcheck[1]:
                if self.AS.acc.text == 'Admin':
                    self.admin = True
                self.LoginT = True
                self.username = self.UN.I.text
            else:
                self.p = PopUp()
                self.p.set()
                self.p.open()

    def signupcheck(self, instance):
        #flag to check whether user have pressed the sign up button
        self.SignUpT = True
        print(self.SignUpT, 'SignUpT')

    def set(self):
        #It arrange all the elements of Login menu
        self.LoginT = False
        self.admin = False
        self.SignUpT = False
        self.padding = (10, 10)
        self.pos_hint = {'center_x': 0.5, 'center_y': 0.5}
        self.aw(
            Label(text='Login', color=(0, 0, 0, 1), bold=True, font_size=25))
        self.AS = UP()
        self.AS.aset()
        self.aw(self.AS)
        self.UN = UP()
        self.UN.oset('Username', False)
        self.username = self.UN.I.text
        self.aw(self.UN)
        self.PW = UP()
        self.PW.oset('Password', True)
        self.aw(self.PW)
        self.lg = Button(text='Login',
                         background_normal='',
                         background_color=(1, .4392, .2627, 1),
                         color=(0, 0, 0, 1))
        self.lg.bind(on_press=self.logincheck)
        self.aw(self.lg)
        self.signup = BoxLayout(orientation='horizontal',
                                padding=(5, 5),
                                spacing=10)
        self.orl = Label(text='Or', size_hint=(.3, 1), color=(0, 0, 0, 1))
        self.signupb = Button(on_press=self.signupcheck,
                              text='Sign Up',
                              size_hint=(.7, 1),
                              background_normal='',
                              background_color=(1, .4392, .2627, 1),
                              color=(0, 0, 0, 1))
        self.signup.add_widget(self.orl)
        self.signup.add_widget(self.signupb)
        self.aw(self.signup)

    def aw(self, ob):
        self.add_widget(ob)
        def build(self):
            layout = BoxLayout(orientation='vertical')

            graph_theme = {
                'label_options': {
                    'color': rgb('444444'),  # color of tick labels and titles
                    'bold': True
                },
                'background_color':
                rgb('f8f8f2'),  # back ground color of canvas
                'tick_color': rgb('808080'),  # ticks and grid
                'border_color': rgb('808080')
            }  # border drawn around each graph

            x_values = list(range(100))
            y_values = [123.0 + random() for x in x_values]
            end_date = date(2017, 2, 1)
            one_day = timedelta(1)
            date_values = [end_date - one_day * i for i in x_values]
            date_values.reverse()
            time_series = zip(x_values, y_values)

            graph1 = TimeSeriesGraph(
                date_values,
                date_label_format='%b',
                xlabel='example 1',
                ylabel='some y labels',
                #x_ticks_minor=5,
                x_ticks_major='month',
                y_ticks_major=0.1,
                y_grid_label=True,
                x_grid_label=True,
                padding=5,
                xlog=False,
                ylog=False,
                x_grid=True,
                y_grid=True,
                #xmin=-50,
                #xmax=50,
                ymin=123,
                ymax=124,
                font_size='12sp',
                **graph_theme)

            plot1 = SmoothLinePlot(color=rgb('7dac9f'))
            plot1.points = time_series
            graph1.add_plot(plot1)

            plot3 = SmoothLinePlot(color=rgb('dc7062'))
            y_values = [123.0 + random() for x in x_values]
            time_series = zip(x_values, y_values)
            plot3.points = time_series
            graph1.add_plot(plot3)

            layout.add_widget(graph1)

            y_values = [123.0 + random() for x in x_values]

            graph2 = TimeSeriesGraph(
                date_values,
                date_label_format='%b-%d',
                xlabel='example 2',
                ylabel='some y labels',
                x_ticks_minor=5,
                x_ticks_major=30,
                y_ticks_major=0.1,
                y_grid_label=True,
                x_grid_label=True,
                padding=5,
                xlog=False,
                ylog=False,
                x_grid=True,
                y_grid=True,
                #xmin=-50,
                #xmax=50,
                ymin=123,
                ymax=124,
                font_size='12sp',
                **graph_theme)

            plot2 = SmoothLinePlot(color=rgb('7dac9f'))
            plot2.points = zip(x_values, y_values)
            graph2.add_plot(plot2)

            layout.add_widget(graph2)

            s = Screen(name="test1")
            s.add_widget(layout)

            sm = ScreenManager()
            sm.add_widget(s)

            return sm
Exemple #47
0
class MyPopup(Popup):
    events_callback = ObjectProperty(_pass)
    '''Пользовательская функция обработки событий окна.'''

    answer_callback = ObjectProperty(_pass)
    '''Встроеная функция обработки событий окна.'''

    progress_callback = ObjectProperty(None)
    '''Функция, вызываемая при старте окна прогресса.'''

    background = StringProperty(
        'atlas://material/images/mypopup/mypopup/decorator'.format(root))
    '''Декоратор окна.'''

    separator_color = ListProperty([0.10, 0.24, 0.29, .8])
    '''Цвет линии-разделителя окна.'''

    title_align = OptionProperty('center')
    '''Выравнивание заголовка окна.'''

    title_color = ListProperty([0.06, 0.20, 0.25, 1.0])
    '''Цвет заголовка окна.'''

    title_size = NumericProperty('15sp')
    '''Размер заголовка окна.'''

    background_image_buttons = DictProperty({
        0:
        'atlas://material/images/mypopup/mypopup/button_ok'.format(root),
        1:
        'atlas://material/images/mypopup/mypopup/button_no'.format(root),
        2:
        'atlas://material/images/mypopup/mypopup/button_cancel'.format(root)
    })
    '''Обычные кнопки, в неактивном состоянии, `No Active`.'''

    background_image_shadows = DictProperty({
        0:
        'atlas://material/images/mypopup/mypopup/button_ok_shadow'.format(
            root),
        1:
        'atlas://material/images/mypopup/mypopup/button_no_shadow'.format(
            root),
        2:
        'atlas://material/images/mypopup/mypopup/button_cancel_shadow'.format(
            root)
    })
    '''Кнопки в нажатом состоянии, `Active`.'''

    base_font_size = NumericProperty('17sp')
    '''Размер шрифта окна.'''

    base_font_name = StringProperty(KIVY_DEFAULT_FONT)
    '''Имя шрифта окна.'''

    base_text_color = ListProperty([0.10, 0.24, 0.29, 1.0])
    '''Цвет текста окна программы.'''

    size_height_window = NumericProperty('220dp')
    '''Высота окна MyPopup, по умолчанию равна `220dp`'''

    mypopup_label_height = NumericProperty('120dp')
    '''Высота текста окна MyPopup, по умолчанию равна `120dp`'''
    def __init__(self, **kwargs):
        super(MyPopup, self).__init__(**kwargs)
        self.box_buttons_select = BoxLayout(size_hint_y=None,
                                            height=dp(40),
                                            spacing=dp(20))
        self.box_root = self.ids.box_root
        self.box_content = self.ids.box_content

        self.message = None

    def show(self,
             text='Text message',
             text_button_ok=None,
             text_button_no=None,
             text_button_cancel=None,
             auto_dismiss=True):
        def create_button(name_button, background_image_normal,
                          background_image_down):
            self.box_buttons_select.add_widget(
                Button(id=name_button,
                       text=name_button,
                       background_normal=background_image_normal,
                       background_down=background_image_down,
                       font_size=sp(17),
                       on_release=self._answer_user))
            return True

        for i, name_button in enumerate(
            [text_button_ok, text_button_no, text_button_cancel]):
            if name_button:
                create_button(name_button, self.background_image_buttons[i],
                              self.background_image_shadows[i])

        self.message = Label(text=text,
                             size_hint_y=None,
                             markup=True,
                             height=self.mypopup_label_height,
                             text_size=(self.width, None),
                             halign='center',
                             padding_x=dp(10),
                             on_ref_press=self.answer_callback,
                             font_size=self.base_font_size,
                             font_name=self.base_font_name,
                             color=self.base_text_color)
        self.box_content.add_widget(self.message)

        # self.box_root.add_widget(Widget())
        self.box_root.add_widget(self.box_buttons_select)

        self.auto_dismiss = auto_dismiss
        self.open()

        if callable(self.progress_callback):
            Clock.schedule_once(self.progress_callback, 0)
        return self

    def _answer_user(self, *args):
        """Вызывается при нажатии управляющих кнопок."""
        self.answer_callback(args[0].text)
        self.dismiss()
Exemple #48
0
class HomePage(Screen):
    def __init__(self, page_controller, user, **kw):
        super().__init__(**kw)

        # instantiate the user
        self.user = user

        # instantiate the controller
        self.controller = page_controller

        # Add app background
        Utils.set_background(self, 'data/home_background.png')

        # Initialize articles directory
        self.articles_dir = 'data/articles'
        self.full_articles_dir = f'{os.getcwd()}/{self.articles_dir}'
        self.article_images_dir = f'{os.getcwd()}/data/article_images'

        # Initialize root widget
        self.root_widget = BoxLayout(orientation="horizontal")
        self.root_widget.spacing = 15
        self.root_widget.padding = 15
        self.add_widget(self.root_widget)

        # Generate articles layout
        self.generate_articles_layout()

        # Generate the preview layout
        self.generate_preview_layout()

        # Generate history, accounts and start box
        self.generate_history_account_start_layout()

    def generate_articles_layout(self):
        articles_layout_box = BoxLayout(orientation='vertical',
                                        spacing=12,
                                        size_hint=(.7, .9))

        refresh_button = Button(text='Change story',
                                font_size=15,
                                size_hint=(1, .3),
                                on_release=self.load_article)
        articles_layout_box.add_widget(refresh_button)

        articles_box = BoxLayout(orientation='vertical',
                                 spacing=12,
                                 size_hint=(1, 1.2))

        change_article_button = Button(text='Change Story', font_size=20)
        # articles_box.add_widget(change_article_button)

        articles_layout_box.add_widget(articles_box)
        Utils.add_empty_space(articles_layout_box, (1, 1))

        self.root_widget.add_widget(articles_layout_box)

    def load_article(self, b):
        self.preview_box.remove_widget(self.preview_box_image)

        random_article_path = random.choice(
            Utils.iter_files('/data/article_images', '.png')[1])
        self.preview_box_image = Image(source=str(random_article_path),
                                       allow_stretch=True,
                                       keep_ratio=False)
        self.preview_box.add_widget(self.preview_box_image)

    def generate_preview_layout(self):
        preview_layout_box = BoxLayout(orientation='vertical',
                                       spacing=15,
                                       size_hint=(1.6, 1))

        preview_label = Label(text='Preview', font_size=25, size_hint=(1, .3))
        preview_layout_box.add_widget(preview_label)

        self.preview_box = BoxLayout(orientation='vertical',
                                     size_hint=(1, 1.3))
        self.generate_article_images()

        random_article_path = random.choice(
            Utils.iter_files('data/article_images', '.png')[1])
        self.preview_box_image = Image(source=random_article_path,
                                       allow_stretch=True,
                                       keep_ratio=False)
        self.preview_box.add_widget(self.preview_box_image)

        preview_layout_box.add_widget(self.preview_box)

        self.root_widget.add_widget(preview_layout_box)

    def generate_article_images(self):
        article_names = Utils.iter_files('data/articles', '.txt')[0]
        for article in article_names:
            article_image_path_to_save = f'{os.getcwd()}/data/article_images/{article}.png'
            if not os.path.exists(article_image_path_to_save):
                article_image = Utils.text_to_image(
                    f'/data/articles/{article}')
                article = str(article).replace('.txt', '')
                article_image.save(
                    fp=f'{os.getcwd()}/data/article_images/{article}.png')

    def generate_history_account_start_layout(self):
        history_account_start_layout_box = BoxLayout(orientation='vertical',
                                                     spacing=12,
                                                     size_hint=(.7, 1))

        history_account_box = BoxLayout(orientation='horizontal', spacing=10)

        history_button = Button(text='History',
                                font_size=20,
                                on_release=self.go_to_history_page)
        accounts_button = Button(text=str(self.user[0]).upper(),
                                 font_size=20,
                                 background_color=Utils.get_color_from_letter(
                                     self.user[0]),
                                 on_release=self.go_to_login_page)
        history_account_box.add_widget(history_button)
        history_account_box.add_widget(accounts_button)
        history_account_start_layout_box.add_widget(history_account_box)

        Utils.add_empty_space(history_account_start_layout_box, (1, 2.4))

        start_button_box = BoxLayout(orientation='vertical')
        start_button = Button(text='start',
                              font_size=25,
                              on_release=self.go_to_typing_page)
        start_button_box.add_widget(start_button)
        history_account_start_layout_box.add_widget(start_button_box)

        Utils.add_empty_space(history_account_start_layout_box, (1, 2.4))

        self.root_widget.add_widget(history_account_start_layout_box)

    def go_to_login_page(self, button):
        self.controller.initialize_login_page()

    def go_to_history_page(self, button):
        self.controller.initialize_history_page(self.user)

    def go_to_typing_page(self, button):

        img_source = self.preview_box_image.source
        img_source = img_source.split('/')[-1].split('.')[0]
        article_path = f'{self.articles_dir}/{img_source}.txt'

        self.controller.initialize_typing_page(self.user, article_path)
Exemple #49
0
 def build(self):
     box = BoxLayout()
     box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
     return box
Exemple #50
0
class MainScreen(Screen):
    """ The Main Screen of the app where the names are inputed and teams are outputed

        Attributes:
            players_dick: dictionary of player names and respective skill rating 
            game_list: matrix of teams where first row is one team and the second row is another 
            current_page: holds which screen (input, output or help) is being currently displayed
            

    """
    def __init__(self, **kwargs):
        '''initilizes attributs and displays input widget on start up'''

        super(MainScreen, self).__init__(**kwargs)  #inializes screen manager

        self.players_dick = {}
        self.game_list = []
        self.current_page = None

        self.input_page()  #adds and displays all widgets related to input

    def input_page(self, *args):
        ''' method adds all relvent items(widgets) to screen, needed for the inputing of names, hence input page'''
        self.current_page = 'input'

        #creates layout structure for widgets
        self.input_page_layout = BoxLayout(
            orientation='vertical')  #main layout
        self.input_layout = GridLayout(
            cols=5, size_hint_y=None)  #layout for input widgets
        self.input_scroll = ScrollView(size_hint=(1, None),
                                       size=(Window.width, Window.height))

        #creates text input widgets

        self.name_input1 = TextInput(text='Name',
                                     size_hint=(1, None),
                                     multiline=False)
        self.skill_input1 = TextInput(text='Skill',
                                      size_hint=(1, None),
                                      multiline=False,
                                      input_filter='int')
        self.separator = Label(text='', size_hint=(0.2, None))
        self.name_input2 = TextInput(text='Name',
                                     size_hint=(1, None),
                                     multiline=False)
        self.skill_input2 = TextInput(text='Skill',
                                      size_hint=(1, None),
                                      multiline=False,
                                      input_filter='int')

        #add widgets to layout for input widgets
        self.input_layout.add_widget(self.name_input1)
        self.input_layout.add_widget(self.skill_input1)
        self.input_layout.add_widget(self.separator)
        self.input_layout.add_widget(self.name_input2)
        self.input_layout.add_widget(self.skill_input2)

        #allows widgets to be scroallble with scroll view
        self.input_layout.bind(
            minimum_height=self.input_layout.setter('height'))
        self.input_scroll.add_widget(self.input_layout)
        self.input_page_layout.add_widget(self.input_scroll)

        self.btns()  # creates button to page

        self.input_page_layout.add_widget(
            self.btn_layout)  #adds btns to main layout
        self.add_widget(self.input_page_layout)  # adds layout to window

    def btns(self):
        '''method creates control buttons'''

        self.btn_layout = BoxLayout()  #layout for btns

        #creates btns
        btn_add_new_players = Button(text='Add New \n players',
                                     size_hint=(1, None))
        btn_view_teams = Button(text='View \n Teams', size_hint=(1, None))
        btn_new_teams = Button(text='Make New \n Teams', size_hint=(1, None))
        btn_help = Button(text='Help', size_hint=(1, None))

        #binds buttons to methods, so that when button is pressed function is called
        btn_add_new_players.bind(on_press=self.new_players)
        btn_add_new_players.bind(on_press=self.update_dick)
        btn_view_teams.bind(on_press=self.make_teams)
        btn_new_teams.bind(on_press=self.new_teams)
        btn_help.bind(on_press=self.to_help)

        #adds btns to layout
        self.btn_layout.add_widget(btn_add_new_players)
        self.btn_layout.add_widget(btn_view_teams)
        self.btn_layout.add_widget(btn_new_teams)
        self.btn_layout.add_widget(btn_help)

    def to_help(self, *args):
        '''method changes screen to the help menu'''

        self.manager.current = 'help'  #calls on the screen manger to set the curent screen to help
        self.current_page = 'help'

    def new_players(self, *args):
        '''adds more text input fields to input page '''

        #creates pop up in case error ocurs
        popup_btn = Button(
            text="Error not able add more players \n\n Click anywhere to close"
        )
        popup = Popup(title='Error', content=popup_btn)
        popup_btn.bind(on_press=popup.dismiss)

        #make sure that the previous text widgets are not blank

        for i in self.players_dick.values():
            if i == '':
                popup.open()  #displays popup
                self.players_dick[i] = 0
                return -1
        for i in self.players_dick.keys():
            if i == '':
                popup.open()
                del self.players_dick[i]
                return -1
        else:

            if len(self.players_dick) != 1 and (
                    self.name_input1.text != 'Name' or self.name_input2.text !=
                    'Name'):  #creates text input widgets
                self.name_input1 = TextInput(text='Name',
                                             size_hint=(1, None),
                                             multiline=False)
                self.skill_input1 = TextInput(text='Skill',
                                              size_hint=(1, None),
                                              multiline=False,
                                              input_filter='int')
                self.label_1 = Label(text='', size_hint=(1, None))
                self.name_input2 = TextInput(text='Name',
                                             size_hint=(1, None),
                                             multiline=False)
                self.skill_input2 = TextInput(text='Skill',
                                              size_hint=(1, None),
                                              multiline=False,
                                              input_filter='int')

                #adds widgets to text input layout
                self.input_layout.add_widget(self.name_input1)
                self.input_layout.add_widget(self.skill_input1)
                self.input_layout.add_widget(self.label_1)
                self.input_layout.add_widget(self.name_input2)
                self.input_layout.add_widget(self.skill_input2)
            else:
                popup_btn = Button(
                    text=
                    "Error unable to add new players \n\n Click anywhere to close"
                )
                popup = Popup(title='Error', content=popup_btn)
                popup_btn.bind(on_press=popup.dismiss)
                popup.open()

    def update_dick(self, *args):
        '''method updates the dictonary of names and skills, with the text from the text input widgets'''

        if self.skill_input1.text != '' and self.skill_input2.text != '':
            self.players_dick.update({
                self.name_input1.text:
                self.skill_input1.text,
                self.name_input2.text:
                self.skill_input2.text
            })
        else:
            self.players_dick = {}
            popup_btn = Button(
                text="Error unable to make teams \n\n Click anywhere to close")
            popup = Popup(title='Error', content=popup_btn)
            popup_btn.bind(on_press=popup.dismiss)
            popup.open()

    def new_teams(self, *args):
        '''methods returns to input page so that user can input names again, making new teams'''

        if self.current_page == 'output':  #makes sure that user is not trying to return to the input page while already at the input page
            self.players_dick = {}
            self.remove_widget(
                self.output_page_layout
            )  #removes output page layout which contains all widgets
            self.input_page()  #adds and displays all widgets related to input
        else:
            #creates and displays pop up when error occurs
            popup_btn = Button(
                text="Already making teams \n\n Click anywhere to close")
            popup = Popup(title='Error', content=popup_btn)
            popup_btn.bind(on_press=popup.dismiss)
            popup.open()

    def make_teams(self, *args):
        '''where the magic happens: method creates the teams'''

        self.update_dick()  #gets most recent dictonary of names
        #print(self.players_dick)

        #creats pop up if error ocurrs
        popup_btn = Button(
            text="Error unable to display teams \n\n Click anywhere to close")
        popup = Popup(title='Error', content=popup_btn)
        popup_btn.bind(on_press=popup.dismiss)

        #make sure that new names and skill rating are not blank
        #fix: skils can be blank
        for i in self.players_dick.values():
            if i == '':
                popup.open()
                self.players_dick[i] = 0
                return -1

        for i in self.players_dick.keys():
            if i == '':
                popup.open()
                del self.players_dick[i]
                return -1

        if len(self.players_dick) != 1 and len(
                self.players_dick
        ) != 0 and self.current_page != 'output':  #make sure that the diconray is not empty and that the input page is being displayed
            #magic
            game = Players(
                self.players_dick
            )  #makes diconry object of players class, see algorthim.py
            self.game_list = game.team_maker(
            )  #calls team_maker method to make teams with players class object

            self.remove_widget(
                self.input_page_layout
            )  # removes the input layout which contains all the input related widgets
            self.output_names()  # displays teams and names
            #print(self.game_list)
        else:
            popup.open()

        return self.game_list  #not sure why its there to afraid to remove

    def output_names(self, *args):
        '''method displays names in their respective teams'''

        self.current_page = 'output'

        #layouts for output page
        self.output_page_layout = BoxLayout(
            orientation='vertical')  #main layout
        self.output_layout = GridLayout(cols=2,
                                        size_hint_y=None)  #layout for labels
        self.output_scroll = ScrollView(size_hint=(1, None),
                                        size=(Window.width, Window.height))

        #creates and adds team name to layout
        shirts_lbl = Label(text="Shirts", size_hint=(1, None))
        skins_lbl = Label(text="Skins", size_hint=(1, None))
        self.output_layout.add_widget(skins_lbl)
        self.output_layout.add_widget(shirts_lbl)

        #splits game_list into its two teams
        self.team1 = self.game_list[0]
        self.team2 = self.game_list[1]

        n = max(len(self.team2), len(
            self.team1))  #see which team is longer, for odd num of names case

        for i in range(n):
            if self.game_list[0][
                    i] == 'Name':  #adds blank label for player with name = 'Name'
                lbl = Label(text='', size_hint=(1, None))
            else:
                lbl = Label(text=self.game_list[0][i],
                            size_hint=(1, None))  #adds name to team
            self.output_layout.add_widget(lbl)  #adds name to display

            if self.game_list[1][
                    i] == 'Name':  #adds blank label for player with name = 'Name'
                lbl1 = Label(text='', size_hint=(1, None))
            else:
                lbl1 = Label(text=self.game_list[1][i],
                             size_hint=(1, None))  #adds name to team
            self.output_layout.add_widget(lbl1)  #adds name to display

        self.output_layout.bind(minimum_height=self.output_layout.setter(
            'height'))  #allows scrollable
        self.output_scroll.add_widget(self.output_layout)
        self.output_page_layout.add_widget(self.output_scroll)

        self.btns()  #creates control btns

        self.output_page_layout.add_widget(
            self.btn_layout)  #adds controls btns to page
        self.add_widget(
            self.output_page_layout)  #displays main layout in window
Exemple #51
0
class SketchySave(Screen):

    def on_enter(self, *args):
        super(SketchySave, self).on_enter(*args)
        if self.savenametextinput.text == '':
            self.savenametextinput.text = str(datetime.datetime.today())
        self.callback_size_y(height=self.height)
        self.callback_size_x(width=self.width)
        self.previous_saves()

    def previous_saves(self):
        self.paddingbox.text = 'Recent Saves:\n'
        sketchybook = shelve.open('data/SketchyBook')
        keys_list = [x for x in sketchybook.keys()]
        keys_list.reverse()
        for save in keys_list:
            self.paddingbox.text += '\n'
            self.paddingbox.text += "{save}".format(save=save)
        sketchybook.close()

    def __init__(self, get_setting, **kwargs):
        super(SketchySave, self).__init__(**kwargs)
        self.previous_auto_save = None

        self.get_setting = get_setting

        self.saveboxlayout = BoxLayout()
        self.saveboxlayout.orientation = 'vertical'

        self.savetextbox = BoxLayout()
        self.savetextbox.orientation = 'horizontal'

        self.labelsavename = labelsavename()
        self.labelsavename.text = 'Name this save file:'
        self.labelsavename.font_size = 25

        self.labelsavestatus = Label()
        self.labelsavestatus.font_size = 25
        self.labelsavestatus.text = ''
        self.labelsavestatus.color = (0, 1, 0, 1)

        self.savenametextinput = TextInput()
        self.savenametextinput.text = ''

        self.paddingbox = Label()
        self.paddingbox.valign = 'top'
        self.paddingbox.padding = (20, 20)
        self.paddingbox.font_size = 20

        self.buttonbox = BoxLayout()

        self.savebutton = Button()
        self.savebutton.text = 'Save'
        self.savebutton.bind(on_release=self.callback_savebutton)

        self.returnbutton = Button()
        self.returnbutton.text = 'Return'
        self.returnbutton.bind(on_release=self.callback_returnbutton)

        self.buttonbox.add_widget(self.savebutton)
        self.buttonbox.add_widget(self.returnbutton)

        self.savetextbox.add_widget(self.labelsavename)
        self.savetextbox.add_widget(self.labelsavestatus)

        self.saveboxlayout.add_widget(self.savetextbox)
        self.saveboxlayout.add_widget(self.savenametextinput)
        self.saveboxlayout.add_widget(self.paddingbox)
        self.saveboxlayout.add_widget(self.buttonbox)

        self.add_widget(self.saveboxlayout)
        self.bind(height=self.callback_size_y)
        self.bind(width=self.callback_size_x)

    def callback_size_y(self, target=None, height=100):
        self.savetextbox.size_hint_y = 120 / height
        self.savenametextinput.size_hint_y = 40 / height
        self.paddingbox.size_hint_y = (height - 220) / height
        self.buttonbox.size_hint_y = 60 / height
        self.paddingbox.text_size = self.paddingbox.size

    def callback_size_x(self, target=None, width=100):
        self.paddingbox.text_size = self.paddingbox.size

    def get_save_data(self):
        data = self.main.save_data()
        return data

    def save_to_book(self, data):
        """

        :type data: list
        """
        sketchybook = shelve.open('data/SketchyBook')
        sketchybook[self.savenametextinput.text] = pickle.dumps(data)
        sketchybook.close()

    def auto_save(self):
        name = str(datetime.datetime.today())
        data = self.get_save_data()
        if not data:
            return False
        elif data == self.previous_auto_save:
            return False

        self.previous_auto_save = data
        sketchybook = shelve.open('data/AutoSaves')
        save_list = [x for x in sketchybook.keys()]
        remaining_saves = len(save_list) - int(self.get_setting('Behavior', 'auto_save_number'))
        if remaining_saves > 0:
            save_list.sort()
            for x in range(remaining_saves):
                if save_list[x] in sketchybook.keys():
                    del sketchybook[save_list[x]]
        sketchybook[name] = pickle.dumps(data)
        sketchybook.close()

    def callback_savebutton(self, target):
        self.save_to_book(self.get_save_data())

        self.labelsavestatus.text = self.savenametextinput.text + '\nSaved!'
        self.labelsavestatus.text += '\n' + str(datetime.datetime.now())
        self.labelsavestatus.color = (0, 1, 0, 1)
        self.previous_saves()

    def callback_returnbutton(self, target):
        #  Return to 'main' window
        self.parent.current = 'main'
        self.labelsavestatus.color = (1, 1, 1, 1)
Exemple #52
0
	def on_enter(self):
		self.clear_widgets
		f = open('carros.txt','r')
		a = f.read()
		f.close()
		a = a.split('\n')
		a.pop()
		for i in range(0,len(a)):
			a[i] = a[i].split(":")
		for i in range(0,len(a)):
			if a[i][0] not in self.flags:
				btn = Button(text=str(a[i][0]), font_size=32)

				box = BoxLayout(orientation="vertical")
				bot = BoxLayout()
				pop = Popup(title='HELP',content=box)

				cancel = Button(text="Return",font_size=32,on_release=pop.dismiss)
				sell = Button(text="Sell",font_size=32)
				bot.add_widget(cancel)
				

				platel = Label(text='Plate:',font_size=30)
				plate = Label(text=a[i][0],font_size=25)
				box.add_widget(platel)
				box.add_widget(plate)

				typel = Label(text='Car:',font_size=30)
				typee = Label(text=a[i][1],font_size=25)
				box.add_widget(typel)
				box.add_widget(typee)

				pricel = Label(text='Price:',font_size=30)
				price = Label(text=a[i][2],font_size=25)
				box.add_widget(pricel)
				box.add_widget(price)

				sep = Label(text='----------------------------------------',font_size=30)
				box.add_widget(sep)

				buyerl = Label(text='Insert Buyer\'s unique ID:', font_size=32)
				buyeri = TextInput(multiline=False)

				box.add_widget(buyerl)
				box.add_widget(buyeri)
				#buttoncallback = partial(self.gratulation, g.text)
				removerino = partial(self.remove, a[i][0],a[i][1],a[i][2])
				sell.bind(on_press=removerino)
				box.add_widget(sell)
				box.add_widget(bot)
				
				btn.bind(on_press=pop.open)


				self.ids.grid.add_widget(btn)
				self.flags.append(a[i][0])
Exemple #53
0
    def fillLifeInsurance(self):
        self.wgt_title.text = "Calcular Score - Seguro de Vida"

        life_insurance_lyt = BoxLayout(orientation='vertical')

        life_insurance_basics_lyt = GridLayout(cols=2,
                                               row_force_default=True,
                                               row_default_height=30,
                                               size_hint=(None, 1),
                                               width=400)

        life_insurance_basics_lyt.cols_minimum[0] = 200
        life_insurance_basics_lyt.cols_minimum[1] = 200

        self.posInputField('Tipo de Cobertura', self.wgt_life_coverage_type,
                           life_insurance_basics_lyt)
        self.posInputField('Tipo sanguíneo', self.wgt_blood_type,
                           life_insurance_basics_lyt)
        self.posInputField('Número de viagens por ano', self.wgt_travels,
                           life_insurance_basics_lyt)

        life_insurance_lyt.add_widget(life_insurance_basics_lyt)

        life_insurance_rules_lyt = GridLayout(cols=6,
                                              row_force_default=True,
                                              row_default_height=30)

        self.posInputField('Pratica esportes radicais?',
                           self.wgt_radical_sports, life_insurance_rules_lyt)
        self.posInputField('É piloto de corrida?', self.wgt_racing_driver,
                           life_insurance_rules_lyt)
        self.posInputField('Utiliza ou já utilizou drogas?',
                           self.wgt_use_drugs, life_insurance_rules_lyt)
        self.posInputField('É portador de doenças graves?',
                           self.wgt_serious_diseases, life_insurance_rules_lyt)
        self.posInputField('Realiza acompanhamento médico periódico?',
                           self.wgt_medical_monitoring,
                           life_insurance_rules_lyt)
        self.posInputField('Já recebeu indenização por invalidez?',
                           self.wgt_invalidity, life_insurance_rules_lyt)
        self.posInputField('É fumante?', self.wgt_smoker,
                           life_insurance_rules_lyt)
        self.posInputField('Faz uso freqüente de bebidas alcoólicas?',
                           self.wgt_alcohol, life_insurance_rules_lyt)
        self.posInputField('Habita em regiões perigosas?',
                           self.wgt_dangerous_zone, life_insurance_rules_lyt)
        self.posInputField(
            'Realiza atividades profissionais\na bordo de aeronaves?',
            self.wgt_airline_crew, life_insurance_rules_lyt)
        self.posInputField('Portador de diabetes', self.wgt_diabetes,
                           life_insurance_rules_lyt)
        self.posInputField('Possui hipertensão arterial',
                           self.wgt_arterial_hypertension,
                           life_insurance_rules_lyt)
        self.posInputField('Pratica esportes regularmente?',
                           self.wgt_sports_practice, life_insurance_rules_lyt)
        self.posInputField('Portador de doença neurológica?',
                           self.wgt_neurological_disease,
                           life_insurance_rules_lyt)
        self.posInputField('Realizou cirurgia de grande porte?',
                           self.wgt_surgery, life_insurance_rules_lyt)
        self.posInputField('Possui marcapasso?', self.wgt_pacemaker,
                           life_insurance_rules_lyt)
        self.posInputField('Portador de doença auto imune?',
                           self.wgt_auto_immune_disease,
                           life_insurance_rules_lyt)
        self.posInputField('Portador de doença cardíaca?',
                           self.wgt_heart_disease, life_insurance_rules_lyt)
        self.posInputField('Portador de câncer?', self.wgt_cancer,
                           life_insurance_rules_lyt)
        self.posInputField('Portador de doença celíaca?', self.wgt_celia,
                           life_insurance_rules_lyt)
        self.posInputField('Intolerância à Lactose?',
                           self.wgt_lactose_intolerance,
                           life_insurance_rules_lyt)
        self.posInputField('Portador de alguma\ndoença em estágio terminal?',
                           self.wgt_terminal_disease, life_insurance_rules_lyt)
        self.posInputField('Viaja para a África?', self.wgt_africa_travel,
                           life_insurance_rules_lyt)
        self.posInputField('Viaja para países em guerra?', self.wgt_war_travel,
                           life_insurance_rules_lyt)
        self.posInputField('Pratica esporte de tiros?',
                           self.wgt_shoot_practice, life_insurance_rules_lyt)
        self.posInputField('Já realizou transplantes?', self.wgt_transplant,
                           life_insurance_rules_lyt)
        self.posInputField('Já teve infarte?', self.wgt_heart_attack,
                           life_insurance_rules_lyt)
        self.posInputField('Já teve AVC?', self.wgt_stroke,
                           life_insurance_rules_lyt)
        self.posInputField('Possui alguma deficiência física?',
                           self.wgt_deficiencies, life_insurance_rules_lyt)
        self.posInputField('Cardiopatia congênita?', self.wgt_heart_congenital,
                           life_insurance_rules_lyt)
        self.posInputField('Artrose?', self.wgt_osteoarthritis,
                           life_insurance_rules_lyt)
        self.posInputField('Faz uso de medicamento controlado?',
                           self.wgt_controlled_medication,
                           life_insurance_rules_lyt)
        self.posInputField(
            'É portador de doença sexualmente\ntransmissível incurável?',
            self.wgt_sexual_disease, life_insurance_rules_lyt)
        self.posInputField('É portador de Hepatite B?', self.wgt_hepatitis,
                           life_insurance_rules_lyt)
        self.posInputField('Possui plano de saúde?', self.wgt_health_plan,
                           life_insurance_rules_lyt)
        self.posInputField('Tomou vacina de poliomelite?',
                           self.wgt_vaccine_polio, life_insurance_rules_lyt)
        self.posInputField('Tomou vacina de meningite?',
                           self.wgt_vaccine_meningite,
                           life_insurance_rules_lyt)
        self.posInputField('Tomou vacina da febre amarela?',
                           self.wgt_vaccine_yellow_fever,
                           life_insurance_rules_lyt)

        life_insurance_lyt.add_widget(life_insurance_rules_lyt)

        self.main_lyt.add_widget(life_insurance_lyt)
Exemple #54
0
 def build(self):
     layout = BoxLayout()
     bt = Button(text='Olá, mundo')
     layout.add_widget(bt)
     return layout
    def __init__(self, the_app):
        super(DetailsFormPersonal, self).__init__()
        self.the_app = the_app

        with self.canvas.before:
            self.rect = Rectangle(source='back3.png')
            self.bind(size=self._update_rect, pos=self._update_rect)

        dict = {}
        self.answers = {}
        store = JsonStore('details.json').get('details')

        for key, value in store.items():
            if key in ['FirstName', 'LastName', 'Email', 'end_button','details_title','Age']:
                dict[key] = value[::-1]
            if key in ['Gender']:
                dict[key] = {}
                for kqa, qa in value.items():
                    if kqa=='text':
                        dict[key][kqa] = qa[::-1]
                    elif kqa == 'default':
                        dict[key][kqa] = qa[::-1]
                    elif kqa != 'ages':
                        dict[key][kqa]=[]
                        for k,v in value[kqa].items():
                           dict[key][kqa].append(v[::-1])
                    else:
                        dict[key][kqa]=[]
                        age=10
                        while age<100:
                            dict[key][kqa].append(str(age))
                            age += 1

        # definitions of all the GUI
        y_size = 0.2

        self.age_text = LoggedTextInput(size_hint_x=0.5, font_size=40, input_filter='int', size_hint_y=y_size)
        self.age_text.bind(text=self.age_text.on_text_change)
        self.age_text.name = 'age'

        self.email_text = LoggedTextInput(size_hint_x=2, font_size=32, size_hint_y=y_size)
        self.email_text.bind(text=self.email_text.on_text_change)
        self.email_text.name = 'email'

        self.gender_default = dict['Gender']['default']

        print(dict['Gender']['Genders'])
        self.gender_spinner = LoggedSpinner(text=dict['Gender']['default'],
                                            values=dict['Gender']['Genders'],
                                            size=(50, 50),
                                            font_name="fonts/the_font.ttf",
                                            font_size=40,
                                            size_hint_y=y_size,
                                            option_cls=MySpinnerOption)
        self.gender_spinner.name = 'gender'
        self.gender_spinner.bind(text=self.gender_spinner.on_spinner_text)

        end_button = Button(background_color=[0, 0.71, 1, 1],
                            background_normal="",
                            text=dict['end_button'], font_size=30,
                            font_name="fonts/the_font.ttf",
                            halign='right', on_press=self.next)

        end_button.bind(on_press=self.save)  # layout of the GUI

        layoutup = BoxLayout(orientation='vertical')
        layoutup.add_widget(BoxLayout(size_hint_y=y_size))
        layoutup.add_widget(
             Label(text=dict['details_title'], 
                   font_size=50, font_name="fonts/the_font.ttf",
                   halign='right', size_hint_y=y_size,
                   color=[0,0,0,1]))

        layout = GridLayout(cols=8, rows=6)

        # === first line ===
        layout.add_widget(end_button)
        layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=y_size))

        if 'age' in self.what_to_include:
            layout.add_widget(self.age_text)
            layout.add_widget(
                Label(text=dict['Age'], font_size=30,
                      font_name="fonts/the_font.ttf", halign='right',
                      size_hint_y=y_size,
                      color=[0,0,0,1]))
        else:
            layout.add_widget(BoxLayout())
            layout.add_widget(BoxLayout())

        if 'email' in self.what_to_include:
            layout.add_widget(self.email_text)
            # layout.add_widget(BoxLayout(size_hint_x=1, size_hint_y=1))
            layout.add_widget(
                Label(text=dict['Email'], font_size=30,
                      font_name="fonts/the_font.ttf", halign='right',
                      size_hint_y=y_size,
                      color=[0, 0, 0, 1]))

        else:
            layout.add_widget(BoxLayout())
            layout.add_widget(BoxLayout())

        if 'gender' in self.what_to_include:
            layout.add_widget(self.gender_spinner)
            layout.add_widget(
                Label(text=dict['Gender']['text'], font_size=30,
                      font_name="fonts/the_font.ttf", halign='right',
                      size_hint_y=y_size,
                      color=[0, 0, 0, 1]))
        else:
            layout.add_widget(BoxLayout())
            layout.add_widget(BoxLayout(size_hint_y=y_size))
    # === second line ===
        layout.add_widget(BoxLayout(size_hint_y=y_size))
        layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=y_size))
        layout.add_widget(BoxLayout())
        layout.add_widget(BoxLayout(size_hint_y=y_size))

        layout.add_widget(BoxLayout())
        layout.add_widget(BoxLayout())
        layout.add_widget(BoxLayout(size_hint_x=1.5))
        layout.add_widget(BoxLayout(size_hint_x=1.5))

        # === space lines ===
        for lines in range(2):
            for space_line in range(8):
                layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=1))
                # layout.add_widget(BoxLayout(size_hint_y=1))

        # === last line ===
        layout.add_widget(BoxLayout(size_hint_x=0.2))
        layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=y_size))
        layout.add_widget(BoxLayout())

        layout.add_widget(BoxLayout(size_hint_x=0.2))

        layout.add_widget(
            Label(text="ךתופתתשה לע הדות", font_size=36,
                  color=[0, 0, 0, 1],
                  font_name="fonts/the_font.ttf", halign='right', size_hint_x=1.5))

        layout.add_widget(BoxLayout())
        layout.add_widget(BoxLayout())

        # === space lines ===
        for lines in range(1):
            for space_line in range(7):
                layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=1))
                # layout.add_widget(BoxLayout(size_hint_y=1))
        # ======= end =======

        layoutup.add_widget(layout)
        self.add_widget(layoutup)
class TelaLogin(GridLayout):
    def __init__(self, **kwargs):
        super(TelaLogin, self).__init__(**kwargs)
        self.cols = 1
        self.started = 0
        self.run_serv = 0
        self.rc = None
        self.controller = None

        self.setpoint_box = BoxLayout()
        self.setpoint_box.add_widget(Label(text='Set Point'))
        self.ref = TextInput(multiline=False, input_filter='float')
        self.setpoint_box.add_widget(self.ref)
        self.add_widget(self.setpoint_box)

        self.change_ref = Button(text='Set')
        self.change_ref.bind(on_press=self.update_sp)
        self.add_widget(self.change_ref)

        self.kp_box = BoxLayout()
        self.kp_box.add_widget(Label(text='Kp'))
        self.Kp = TextInput(multiline=False, input_filter='float')
        self.kp_box.add_widget(self.Kp)
        self.add_widget(self.kp_box)

        self.ki_box = BoxLayout()
        self.ki_box.add_widget(Label(text='Ki'))
        self.Ki = TextInput(multiline=False, input_filter='float')
        self.ki_box.add_widget(self.Ki)
        self.add_widget(self.ki_box)

        self.kd_box = BoxLayout()
        self.kd_box.add_widget(Label(text='Kd'))
        self.Kd = TextInput(multiline=False, input_filter='float')
        self.kd_box.add_widget(self.Kd)
        self.add_widget(self.kd_box)

        self.update = Button(text='Start Server')
        self.update.bind(on_press=self.update_PID)
        self.add_widget(self.update)

        self.stop = Button(text='Stop Server', background_color=[1, 0, 0, 1])
        self.stop.bind(on_press=self.stop_sim)
        self.add_widget(self.stop)

    def update_sp(self, instance):
        self.controller.update_setpoint(float(self.ref.text))

    def update_PID(self, instance):
        if not self.started:
            self.controller = PID(T=0.1,
                                  order=2,
                                  Kp=float(self.Kp.text),
                                  Ki=float(self.Ki.text),
                                  Kd=float(self.Kd.text))
            if not self.run_serv:
                self.rc = RemoteControl(self.controller)
                self.task = asyncio.create_task(self.rc.run())
                asyncio.get_running_loop().run_until_complete(self.task)
                self.run_serv = 1
            else:
                self.rc.controller = self.controller
            self.update.text = 'Update'
            self.started = 1
        else:
            print('Updating gains...')
            self.controller.update_gains(Kp=float(self.Kp.text),
                                         Ki=float(self.Ki.text),
                                         Kd=float(self.Kd.text))

    def stop_sim(self, instance):
        self.controller.stop_press()
        self.update.text = 'Start Server'
        self.started = 0
Exemple #57
0
class DemoScreen(Screen):
    def __init__(self, **kwargs):
        super(DemoScreen, self).__init__(**kwargs)

        #object of nlp_base

        self.nlp_obj = nlp()

        self.setting_layout2 = SettingsBox()

        #demo screen
        self.r = BoxLayout(pos_hint={'x': 0, 'top': 0.9})
        self.r.orientation = 'vertical'

        string = 'Add text here and experiment with the different settings to observe the output'

        self.input = TextInput(text=string, size_hint=(1, 0.5))

        self.output = TextInput(text='OUTPUT:',
                                multiline=True,
                                disabled=True,
                                size_hint=(1, 0.5))

        # self.output.bind(size =self.)
        self.r.add_widget(self.input)

        self.list_operations = [
            'Tokenizer', 'Stemmer', 'StopWords', 'Lemmatization', 'Vectorizers'
        ]

        self.dict_options = {
            'Tokenizer': ['word', 'sent', 'None'],
            'StopWords': ['nltk', 'Extend', 'None'],
            'Stemmer': ['Port', 'SnowBall', 'ISR'],
            'Vectorizer': ['Count', 'TfiDf', 'None']
        }

        sgrid = BoxLayout()
        sgrid.orientation = 'vertical'
        sgrid.add_widget(self.setting_layout2)
        self.set = Button(text='SET', size_hint=(1, 0.2))
        self.set.bind(on_press=self.change_settings)
        sgrid.add_widget(self.set)

        self.pop_setting = Popup(title='preprocessing Settings',
                                 content=sgrid,
                                 size_hint=(0.7, 0.7))

        self.settings = Button(text='CHANGE SETTINGS',
                               size_hint=(0.8, 0.1),
                               pos_hint={
                                   'center_x': 0.5,
                                   'top': 1,
                                   'center_y': 0.5
                               })
        self.settings.bind(on_press=self.show_settings)

        self.r.add_widget(self.settings)

        grid = GridLayout(size_hint=(0.9, 0.5))
        grid.cols = 1

        self.checkbox_list = [
            CheckBox(group=self.list_operations[0]),
            CheckBox(group=self.list_operations[1]),
            CheckBox(group=self.list_operations[2]),
            CheckBox(group=self.list_operations[3]),
            CheckBox(group=self.list_operations[4])
        ]

        self.label_list = {
            self.list_operations[0]: Label(text='OFF'),
            self.list_operations[1]: Label(text='OFF'),
            self.list_operations[2]: Label(text='OFF'),
            self.list_operations[3]: Label(text='OFF'),
            self.list_operations[4]: Label(text='OFF')
        }

        for j, i in enumerate(self.list_operations):

            box = BoxLayout()
            box.add_widget(Label(text=i))
            box.add_widget(self.label_list[i])

            self.checkbox_list[j].bind(on_press=self.checker)
            box.add_widget(self.checkbox_list[j])

            grid.add_widget(box)

        self.r.add_widget(grid)

        # self.apply = Button(text = 'APPLY')
        # self.apply.bind(on_press = self.checker)

        # self.r.add_widget(self.apply)
        self.r.add_widget(self.output)
        self.add_widget(self.r)

    def show_settings(self, instance):
        self.pop_setting.open()

    def checker(self, instance):

        if instance.active:

            self.label_list[instance.group].text = 'ON'
            self.operations(type=instance.group, active='ON')
        elif not instance.active:
            self.label_list[instance.group].text = 'OFF'
            self.operations(type=instance.group, active='OFF')

    def change_settings(self, instance):
        self.pop_setting.dismiss()
        self.settings_list = self.setting_layout2.setting()
        # self.error_text .text = 'final settings:' + str(self.settings_list)
        print('final settings:', self.settings_list)

        if len(self.settings_list) > 0:
            for i in self.settings_list:
                self.nlp_obj.apply_settings(i)

    def operations(self, type, active):
        # print('action applied:',type,'active',active)

        if type == self.list_operations[0] and active == 'ON':
            self.tmp = self.input.text
            self.output.text = self.nlp_obj.get_tokens(input=self.tmp)
            # print(self.input.text)
        elif type == self.list_operations[0] and active == 'OFF':
            self.output.text = self.tmp

        if type == self.list_operations[1] and active == 'ON':
            self.tmp = self.input.text

            self.output.text = self.nlp_obj.get_stemmer(input=self.tmp)
        elif type == self.list_operations[1] and active == 'OFF':
            self.output.text = self.tmp

        if type == self.list_operations[2] and active == 'ON':
            self.tmp = self.input.text

            self.output.text = self.nlp_obj.get_stopwords(input=self.tmp)
            # print(self.input.text)
        elif type == self.list_operations[2] and active == 'OFF':
            self.output.text = self.tmp

        if type == self.list_operations[3] and active == 'ON':
            self.tmp = self.input.text

            self.output.text = self.nlp_obj.lemmatize_sent(text=self.tmp)
        elif type == self.list_operations[3] and active == 'OFF':
            self.output.text = self.tmp

        if type == self.list_operations[4] and active == 'ON':
            self.tmp = self.input.text

            self.output.text = self.nlp_obj.get_vec(input=self.tmp)
        elif type == self.list_operations[4] and active == 'OFF':
            self.output.text = self.tmp

    def select_options(self, instance, x):
        print(x)
        # setattr(instance,'text',x)

        self.nlp_obj.apply_settings(x)

    def get_nlp(self):
        return self.nlp_obj
    def build_song(self):
        sources = {
            "u": "icons/arrow-up-black.png",
            "d": "icons/arrow-down-black.png"
        }
        count = 0
        space = 1 / (self.line_len - 2)

        with open("songs/" + self.ids.title.text.replace(" ", "-") + ".txt",
                  "r") as infile:
            for line in infile:
                match = re.match("^\[(.*)\]([d|u]*)\n$", line)
                start = True

                for ch in match.group(2):
                    if count == self.line_len:
                        self.beats += [[]]
                        self.notes += [[]]
                        count = 0

                    if count == 0 or start == True:
                        self.notes[-1] += [
                            Label(text=match.group(1),
                                  font_size=38,
                                  color=self.colors["black"],
                                  size_hint=[space, None],
                                  height=50,
                                  bold=True), -1
                        ]
                        start = False

                    self.beats[-1] += [
                        Image(source=sources[ch],
                              size_hint=[space, None],
                              height=28)
                    ]
                    self.notes[-1][-1] += 1
                    count += 1

                self.beats[-1] += [
                    Label(text="", size_hint=[space, None], height=28)
                ]
                self.notes[-1] += [
                    Label(text="", size_hint=[space, None], height=28)
                ]

        for i in range(len(self.notes)):
            self.ids.sheetmusic.add_widget(
                Label(text="", size_hint_y=None, height=28))

            special_element = BoxLayout(orientation="horizontal",
                                        size_hint_y=None,
                                        height=50)
            bot_layout = BoxLayout(orientation="horizontal",
                                   size_hint_y=None,
                                   height=28)

            bot_layout.add_widget(
                Label(text="", size_hint=[space, None], height=28))
            special_element.add_widget(
                Label(text="", size_hint=[space, None], height=28))

            for j in range(len(self.notes[i])):
                if type(self.notes[i][j]) is int:
                    special_element.add_widget(
                        Label(text="",
                              size_hint=[space * self.notes[i][j], None],
                              height=50))
                else:
                    special_element.add_widget(self.notes[i][j])

            for el in self.beats[i]:
                bot_layout.add_widget(el)

            self.ids.sheetmusic.add_widget(special_element)
            self.ids.sheetmusic.add_widget(bot_layout)

        for i in range(len(self.notes)):
            self.notes[i] = list(
                filter(lambda el: type(el) is not Label or el.text != "",
                       self.notes[i]))
            self.beats[i] = list(
                filter(lambda el: type(el) is not Label, self.beats[i]))
Exemple #59
0
 def build(self):
     g = BoxLayout()
     spin = KivySpinbox()
     g.add_widget(spin)
     return g
Exemple #60
0
    def __init__(self, **kwargs):
        super(DemoScreen, self).__init__(**kwargs)

        #object of nlp_base

        self.nlp_obj = nlp()

        self.setting_layout2 = SettingsBox()

        #demo screen
        self.r = BoxLayout(pos_hint={'x': 0, 'top': 0.9})
        self.r.orientation = 'vertical'

        string = 'Add text here and experiment with the different settings to observe the output'

        self.input = TextInput(text=string, size_hint=(1, 0.5))

        self.output = TextInput(text='OUTPUT:',
                                multiline=True,
                                disabled=True,
                                size_hint=(1, 0.5))

        # self.output.bind(size =self.)
        self.r.add_widget(self.input)

        self.list_operations = [
            'Tokenizer', 'Stemmer', 'StopWords', 'Lemmatization', 'Vectorizers'
        ]

        self.dict_options = {
            'Tokenizer': ['word', 'sent', 'None'],
            'StopWords': ['nltk', 'Extend', 'None'],
            'Stemmer': ['Port', 'SnowBall', 'ISR'],
            'Vectorizer': ['Count', 'TfiDf', 'None']
        }

        sgrid = BoxLayout()
        sgrid.orientation = 'vertical'
        sgrid.add_widget(self.setting_layout2)
        self.set = Button(text='SET', size_hint=(1, 0.2))
        self.set.bind(on_press=self.change_settings)
        sgrid.add_widget(self.set)

        self.pop_setting = Popup(title='preprocessing Settings',
                                 content=sgrid,
                                 size_hint=(0.7, 0.7))

        self.settings = Button(text='CHANGE SETTINGS',
                               size_hint=(0.8, 0.1),
                               pos_hint={
                                   'center_x': 0.5,
                                   'top': 1,
                                   'center_y': 0.5
                               })
        self.settings.bind(on_press=self.show_settings)

        self.r.add_widget(self.settings)

        grid = GridLayout(size_hint=(0.9, 0.5))
        grid.cols = 1

        self.checkbox_list = [
            CheckBox(group=self.list_operations[0]),
            CheckBox(group=self.list_operations[1]),
            CheckBox(group=self.list_operations[2]),
            CheckBox(group=self.list_operations[3]),
            CheckBox(group=self.list_operations[4])
        ]

        self.label_list = {
            self.list_operations[0]: Label(text='OFF'),
            self.list_operations[1]: Label(text='OFF'),
            self.list_operations[2]: Label(text='OFF'),
            self.list_operations[3]: Label(text='OFF'),
            self.list_operations[4]: Label(text='OFF')
        }

        for j, i in enumerate(self.list_operations):

            box = BoxLayout()
            box.add_widget(Label(text=i))
            box.add_widget(self.label_list[i])

            self.checkbox_list[j].bind(on_press=self.checker)
            box.add_widget(self.checkbox_list[j])

            grid.add_widget(box)

        self.r.add_widget(grid)

        # self.apply = Button(text = 'APPLY')
        # self.apply.bind(on_press = self.checker)

        # self.r.add_widget(self.apply)
        self.r.add_widget(self.output)
        self.add_widget(self.r)