Beispiel #1
0
    def build(self):
        f = FloatLayout()
        b = Button(pos_hint={'x': 0.5, 'center_y': .5},text='Hello world', font_size=14)
        s = Scatter()
        l = Label(text="Hello!",font_size=150)
        
        def select_to(*args):
            try:
                print args[1][0]
            except:
                pass
    
        fi = FileChooserIconView()

        f.add_widget(s)        
        s.add_widget(l)
        l.add_widget(b)
        
        def callback(instance):
            print('The button <%s> is being pressed' % instance.text)
            
            f.add_widget(fi)
        b.bind(on_press=callback)
        fi.bind(on_selection=select_to)
        return f
Beispiel #2
0
 def build(self):
     root = FloatLayout()
     root.add_widget(Grid())
     game = Game()
     root.add_widget(game)
     Clock.schedule_interval(game.update, 1./60.)
     return root
Beispiel #3
0
 def __init__(self, **kwargs): 
     self.imageToSave = None
     super(DestinationPopup, self).__init__(**kwargs)
     self.title = "Save Image" 
     
     # create popup layout containing a boxLayout
     text_input = TextInput(text='./DestFileName.jpg') 
     self.text_input = text_input
     content = FloatLayout()
     
     text_and_buttons_layout = BoxLayout(orientation='vertical',size_hint=(.6, .3),pos_hint={'x':.2, 'y':.5})
     text_and_buttons_layout.add_widget(text_input)
     text_and_buttons_layout.add_widget(Widget(size_hint_y=None, size_hint=(1, .2)))
     
     # 2 buttons are created for accept or cancel the current value
     btnlayout = BoxLayout(size_hint_y=None, height=40, spacing=5)
     okbutton = Button(text='Ok')
     okbutton.bind(on_release=self._validate)
     btnlayout.add_widget(okbutton)
     
     cancelbutton = Button(text='Cancel')
     cancelbutton.bind(on_release=self.cancel)
     btnlayout.add_widget(cancelbutton)
     
     text_and_buttons_layout.add_widget(btnlayout)
     
     content.add_widget(text_and_buttons_layout)
     
     self.content = content
Beispiel #4
0
    def build(self):
        root = FloatLayout(size=(600,600), pos=(0,0))
        with root.canvas:
            Color(1,1,0)
            Rectangle(pos=root.pos, size=root.size)

        widget1 = Widget(id='magenta', size=(50,50), pos=(0,0))
        with widget1.canvas:
            Color(1,0,1)
            Rectangle(pos=widget1.pos, size=widget1.size)

        widget2 = Widget(id='cyan', size=(50,50), pos=(0,100))
        with widget2.canvas:
            Color(0,1,1)
            Rectangle(pos=widget2.pos, size=widget2.size)

        widget3 = Widget(id='red', size=(50,50), pos=(100, 200))
        with widget3.canvas:
            Color(1,0,0)
            Rectangle(pos=widget3.pos, size=widget3.size)

        widget4 = Widget(id='green', size=(50,50), pos=(200,200))
        with widget4.canvas:
            Color(0,1,0)
            Rectangle(pos=widget4.pos, size=widget4.size)

        root.add_widget(widget1)
        root.add_widget(widget2)
        root.add_widget(widget3)
        root.add_widget(widget4)
        return root
Beispiel #5
0
    def build(self):
        # the environment for all 2D shapes
        scene = FloatLayout()

        # list of 2D shapes, starting with regular ones
        shapes = [
            RegularShape(
                name='Shape {}'.format(x), edges=x
            ) for x in range(3, 13)
        ]

        shapes.append(MeshShape(name='DefaultMesh'))
        shapes.append(MeshShape(name='Cloud', poly=cloud_poly))
        shapes.append(MeshShape(
            name='3QuarterCloud',
            poly=cloud_poly[:110]
        ))

        # move shapes to some random position
        for shape in shapes:
            shape.pos = [randint(50, i - 50) for i in Window.size]
            scene.add_widget(shape)

        # check for simple collisions between the shapes
        Clock.schedule_interval(
            lambda *t: self.collision_circles(shapes, debug=True), 0.1)
        return scene
Beispiel #6
0
class bitfluiApp(App):

    def build(self):
        self.root = FloatLayout()
        self.selector = Selector(app=self)
        self.root.add_widget(self.selector)
        return self.root
class CelticKnotwork(App):
    '''Main tabbed interface, each tab contains its own instance of CelticKnotwork2'''
    def build(self):
        ##Instance Variables
        self.showDots = True
        self.showGrid = True
        self.showBreaklines = True
        self.showSkeleton = True
        self.showKnot = True
        self.knotX = 4
        self.knotY = 4
        self.knotWidth = 8
        self.knotWidthView = 8
        self.gridUnits = 50
        self.gridUnitsView = 50
        self.offsetX = 150
        self.offsetY = 50
        self.totTabs = 1
        self.tabNo = 1
        
        
        ##Main Layout
        self.layout_main = AnchorLayout(anchor_x = "left", anchor_y="top")
        self.layout_tabs= FloatLayout(size=(Window.width, Window.height), size_hint=(0.1, 0.08))

        
        ##Top Tab Bar - allowing multiple knots
        self.tp = TabbedPanel()
        self.tp.default_tab_text = "Knot 1"
        self.layout_main.add_widget(self.tp)
        self.addTab = TabbedPanelHeader(text='+')
        self.addTab.bind(on_release = self.onPressAddTab)
        self.addTab = Button(text='+', pos =(Window.width*.9,Window.height*.92))
        self.addTab.bind(on_press = self.onPressAddTab)
        self.tp.default_tab_content = CelticKnotwork2().build() #get tab content from CelticKnotwork2
        self.layout_tabs.add_widget(self.addTab)
        self.layout_main.add_widget(self.layout_tabs)

        Window.bind(on_resize=self.on_resize)

        
        
        return self.layout_main
    def onPressAddTab(self, instance):
        '''Add a tab when "+" button pressed'''
        self.totTabs += 1
        self.tabNo = self.totTabs
        self.th = TabbedPanelHeader(text='Knot '+str(self.totTabs))
        self.th.content = CelticKnotwork2().build()
        self.tp.add_widget(self.th)
        
        self.tp.switch_to(self.th)
    def on_resize(self, window, height, somethingesle):
        '''Handles window resize'''
        self.layout_main.remove_widget(self.layout_tabs)
        self.layout_tabs= FloatLayout(size=(Window.width, Window.height), size_hint=(0.1, 0.05))
        self.addTab = Button(text='+', pos =(Window.width*.9,Window.height*.95))
        self.addTab.bind(on_press = self.onPressAddTab)
        self.layout_tabs.add_widget(self.addTab)
        self.layout_main.add_widget(self.layout_tabs)
Beispiel #8
0
class AnnotatorApp(App):
    def build(self):
        self.root = FloatLayout()

        box = BoxLayout(
                padding=10,
                spacing=10,
                size_hint=(1,None),
                pos_hint={'top':1},
                height=44)

        image = Image(
                size_hint=(None,None),
                size=(30,30),
                source='hand-icon.png')

        label = Label(
                height=24,
                text='Annotator')
        with label.canvas:
            Color(1,1,1,.8)

        box.add_widget(image)
        box.add_widget(label)
        self.root.add_widget(box)
        imd = ImageDisplay()
        self.root.add_widget(imd)
        self.icon = 'hand-icon.png'
Beispiel #9
0
    def build(self):
        # prepare shader list
        available_shaders = (
            shader_pulse, shader_postprocessing, shader_monochrome)
        self.shader_index = 0

        # create our widget tree
        root = FloatLayout()
        sw = ShaderWidget()
        root.add_widget(sw)

        # add a button and scatter image inside the shader widget
        btn = Button(text='Hello world', size_hint=(None, None),
                     pos_hint={'center_x': .25, 'center_y': .5})
        sw.add_widget(btn)

        center = Window.width * 0.75 - 256, Window.height * 0.5 - 256
        scatter = ScatterImage(source='tex3.jpg', size_hint=(None, None),
                               size=(512, 512), pos=center)
        sw.add_widget(scatter)

        # create a button outside the shader widget, to change the current used
        # shader
        btn = Button(text='Change fragment shader', size_hint=(1, None),
                     height=50)
        def change(*largs):
            sw.fs = available_shaders[self.shader_index]
            self.shader_index = (self.shader_index + 1) % len(available_shaders)
        btn.bind(on_release=change)
        root.add_widget(btn)
        return root
Beispiel #10
0
class Workflow:
	def __init__(self):
		self.root = FloatLayout()
		self.states = {}
	
	def add_state(self, step, name):
		self.states[name] = step
	
	def set_handler(self, handler):
		self.handler = handler

	def return_state(self, parameters):
		name, parameters = self.handler.send(parameters)
		self.next_step(name, parameters)
		
	def start(self):
		name, parameters = self.handler.send(None)
		self.next_step(name, parameters)
		return self.root
	
	def next_step(self, name, parameters):
		step = self.states[name]
		widget = step.called_with(self, parameters)
		
		self.root.clear_widgets()
		self.root.add_widget(widget)
Beispiel #11
0
    def setup_battle(self, dt=None):
        self.graphics_widget.remove_widget(self.button_reset)
        self.graphics_widget.remove_widget(self.image_score)
        self.graphics_widget.remove_widget(self.progress_bar)
        if self.level == 11:
            graphics_widget = FloatLayout()
            image = Image(source = PATH + "end.png", keep_ratio=False, allow_stretch=True,\
               size=(SCREEN_WIDTH, SCREEN_HEIGHT), size_hint=(None, None), pos=(0,0))
            graphics_widget.add_widget(image)
            graphics_widget.add_widget(self.button_reset)
            screen = Screen(name="end")
            screen.add_widget(graphics_widget)
            self.add_widget(screen)
            self.current=screen.name
        else:
            self.get_level_data()

            graphics_widget = self.set_background()
            screen = Screen(name=str(self.level))
            screen.add_widget(graphics_widget)
            self.graphics_widget = graphics_widget
            self.add_widget(screen)
            self.current=screen.name
            if self.score_threshold > 0:
                self.level_score = - self.score_threshold
            else:
                self.level_score = 0
            self.image_score.set_score(self.level_score)
            if self.level < 3:
                self.start_battle()
            else:
                self.schedule(self.start_battle, 0) #WAS 2
            self.graphics_widget.add_widget(self.button_reset)
            self.graphics_widget.add_widget(self.progress_bar)
            self.graphics_widget.add_widget(self.image_score)
Beispiel #12
0
    def build(self):
        root = FloatLayout()
        self.renderer = Renderer()
        scene = Scene()
        camera = PerspectiveCamera(15, 1, 1, 1000)
        # load obj file
        loader = OBJLoader()
        obj_path = os.path.join(os.path.dirname(__file__), "./testnurbs.obj")
        obj = loader.load(obj_path)

        scene.add(*obj.children)
        for obj in scene.children:
            obj.pos.z = -20
            obj.material.specular = .35, .35, .35

        # set colors to 3d objects
        scene.children[0].material.color = 0., .7, 0.  # green
        scene.children[1].material.color = .7, 0., 0.  # red
        scene.children[2].material.color = 0., 0., .7  # blue
        scene.children[3].material.color = .7, .7, 0.  # yellow

        scene.children[0].material.diffuse = 0., .7, 0.  # green
        scene.children[1].material.diffuse = .7, 0., 0.  # red
        scene.children[2].material.diffuse = 0., 0., .7  # blue
        scene.children[3].material.diffuse = .7, .7, 0.  # yellow

        self.renderer.render(scene, camera)
        root.add_widget(self.renderer)
        self.renderer.bind(size=self._adjust_aspect)
        return root
Beispiel #13
0
    def set_background(self):
        graphics_widget = FloatLayout()

        for td in self.textures_data:
            filename,xpos,ypos,width,height = td.split(":")
            xpos = float(xpos)
            ypos = float(ypos)
            image = MyImage(keep_ratio=True, allow_stretch=False, color=(0,0,0,0))
            image.set_shadow(False)
            with image.canvas:
                Rectangle(texture=self.textures[filename].texture, size=(float(width) * X_BLOCK, float(height) * Y_BLOCK))
            scatter = Scatter(do_rotation=False, do_scale=False, do_translation=False)
            scatter.pos = (xpos * X_BLOCK, ypos * Y_BLOCK)
            scatter.add_widget(image)
            graphics_widget.add_widget(scatter)

        #for td in self.sprites_data:
        #    filename,xpos,ypos,width,height = td.split(":")
        #    xpos = float(xpos)
        #    ypos = float(ypos)
        #    image = MyImage(texture = self.sprites[filename].texture, keep_ratio=True, allow_stretch=False)
        #    image.set_shadow(False)
        #    scatter = Scatter(do_rotation=False, do_scale=False, do_translation=False)
        #    scatter.pos = (xpos * X_BLOCK, (ypos + 4) * Y_BLOCK / 2)
        #    scatter.add_widget(image)
        #    graphics_widget.add_widget(scatter)
        #    scatter.scale = 6 -  ypos * 1.5

        return graphics_widget
Beispiel #14
0
class SettingPicture(SettingFile):
    ''' let the user select a picture from a folder '''
    def __init__(self, **kwargs):

        self.oLayout =FloatLayout(size_hint=(1, 1))
        super(SettingPicture, self).__init__(**kwargs)
        uPicFN=self.value

        try:
            uPicFN = AdjustPathToOs(ReplaceVars(self.value))
            self.oPic=Image(source=ToAtlas(uPicFN),size_hint=(1, 1), pos_hint={'x':0.0, 'y':0.0})
            oBackFN=AdjustPathToOs(oORCA.uResourcesPath+"/pics/imagepicker_background.png")
            self.oBack=Image(source=ToAtlas(oBackFN),size_hint=(1, 1), pos_hint={'x':0.0, 'y':0.0})
            self.oLayout.add_widget(self.oBack)
            self.oLayout.add_widget(self.oPic)
            self.add_widget(self.oLayout)
            self.content.children[1].text=''
        except Exception as e:
            uMsg=u'Settings: Picture: can\'t load image file: '+ToUnicode(e)+ " "+uPicFN
            Logger.error (uMsg)


    def _validate(self, instance):
        ''' displays the folder '''
        SettingFile._validate(self,instance)
        self.oPic.source=ToAtlas(AdjustPathToOs(self.value))
        self.content.children[1].text=''
    def __init__(self, **kwargs):
        super(case, self).__init__(**kwargs)
        box = FloatLayout()
        graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
            x_ticks_major=25, y_ticks_major=1,
            y_grid_label=True, x_grid_label=True, padding=5,
            x_grid=True, y_grid=True, xmin=-0, xmax=20, ymin=0, ymax=10)
        plot = LinePlot()
        # plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]

        # data = np.array([[0,0], [1,1],[2,2]])

        data = collections.deque(maxlen = 20)
        time = collections.deque(maxlen = 20)

        d = (0,1,2,3,4,5,6,7,8,9)
        t = (0,1,2,3,4,5,6,7,8,9)

        data.append(d)
        time.append(t)

        toplot = np.vstack((time,data)).T

        print toplot

        plot.points = tuple(map(tuple, toplot))

        graph.add_plot(plot)
        box.add_widget(graph)

        self.add_widget(box)
Beispiel #16
0
 def build(self):
     f = FloatLayout()
     s = Scatter()
     l = Label(text="Hello!", font_size=150)
     f.add_widget(s)
     s.add_widget(l)
     return f
Beispiel #17
0
class Test(App):
    def create_clock(self, widget, touch, *args):
        callback = partial(self.menu, touch)
        Clock.schedule_once(callback, 2)
        touch.ud['event'] = callback

    def delete_clock(self, widget, touch, *args):
        Clock.unschedule(touch.ud['event'])

    def menu(self, touch, *args):
        menu = BoxLayout(
                size_hint=(None, None),
                orientation='vertical',
                center=touch.pos)
        menu.add_widget(Button(text='a'))
        menu.add_widget(Button(text='b'))
        close = Button(text='close')
        close.bind(on_release=partial(self.close_menu, menu))
        menu.add_widget(close)
        self.root.add_widget(menu)

    def close_menu(self, widget, *args):
        self.root.remove_widget(widget)

    def build(self):
        self.root = FloatLayout()
        self.root.bind(
            on_touch_down=self.create_clock,
            on_touch_up=self.delete_clock)
Beispiel #18
0
 def build(self):
     # 'atlas://VFX/smoke_particles/VFX_SmokeParticle'
     fl = FloatLayout(pos=(0,0),size=Window.size)
     fl.add_widget(CBL_DebugPanel(pos=(0,0),size=(100,50)))
     for dummy in range(5):
         fl.add_widget(ParticleEmitter(size = (128,128), size_hint=(None,None), pos = (randint(100,Window.width-100),randint(100,Window.height-100))))
     return fl
Beispiel #19
0
    def build(self):
        wid = StencilTestWidget(size_hint=(None, None), size=Window.size)

        label = Label(text='0')

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

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

        btn_stencil = Button(text='Reset Stencil')
        btn_stencil.bind(on_press=partial(self.reset_stencil, wid))

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

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

        return root
Beispiel #20
0
	def build(self):
		layout = FloatLayout()

		cam = Camera(
			play=True,
			resolution=(640,480),
			size_hint=(1.0, 1.0),
			pos=(0, 0)
		)

		def save_camera_snapshot(*args):
			import time
			name = time.asctime()
			# This requires Kivy v1.9.0 (I'm using v1.7.2)
			cam.export_to_png( name )

		btnSave = Button(
			text = 'Save',
			size_hint = (1.0,0.1)
		)
		btnSave.bind( on_press = save_camera_snapshot )

		layout.add_widget( cam )
		layout.add_widget( btnSave )

		return layout
Beispiel #21
0
class TextAlignApp(App):

    def select(self, case):
        for _child in self.selector.grid.children[:]:
            self.selector.grid.remove_widget(_child)
        for valign in ('bottom', 'middle', 'top'):
            for halign in ('left', 'center', 'right'):
                label = BoundedLabel(text='V: %s\nH: %s' % (valign, halign),
                               size_hint=(None, None),
                               size=(150, 150),
                               halign=halign, valign=valign)
                if case == 0:
                    label.text_size = (None, None)
                elif case == 1:
                    label.text_size = (label.width, None)
                elif case == 2:
                    label.text_size = (None, label.height)
                else:
                    label.text_size = label.size
                self.selector.grid.add_widget(label)

        self.selector.grid.bind(minimum_size=self.selector.grid.setter('size'))

    def build(self):
        self.root = FloatLayout()
        self.selector = Selector(app=self)
        self.root.add_widget(self.selector)
        self.grid = None
        self.select(0)
        return self.root
Beispiel #22
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)
Beispiel #23
0
class KeyPadApp(App):
    kps = None
    def build(self):
        self.root = FloatLayout()
        self.kps=KeyPadScreen()
        self.root.add_widget(self.kps)
        return self.root
Beispiel #24
0
	def mail_pop(self):
		"""Popup with features to mail timesheet """

		f=FloatLayout()
		global popup2
		popup2 = Popup(title='Mail Timesheet',content=f,
		size_hint=(1.0, 0.6), size=(400, 400))
		g=GridLayout(cols=1,row_force_default=True,
					 row_default_height=40,pos_hint={'center_x':.5})
		global msg
		msg=Label(text="ENTER AN EMAIL ID")
		global mail_id
		mail_id=TextInput(write_tab=False)
		g.add_widget(msg)
		g.add_widget(mail_id)
		btn1=Button(text='MAIL',size_hint=(0.2,0.1),
					pos=(popup2.width-350,popup2.height-250) )
		btn1.bind(on_press=(MyApp.mail_timesheet))
		btn2=Button(text='CLOSE',size_hint=(0.2,0.1),
					pos=(popup2.width-50,popup2.height-250))
		f.add_widget(btn1)
		f.add_widget(btn2)
		f.add_widget(g)
		popup2.open()
		btn2.bind(on_press=popup2.dismiss)
    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
Beispiel #26
0
 def build(self):
     name1 = 'Name1'
     lastname1 = 'Last1'
     name2 = 'Name2'
     name3 = 'Name3'
     name4 = 'Name4'
     name5 = 'Name5'
     f = FloatLayout()
     
     button_layout = BoxLayout(pos_hint={'x': 0, 'center_y': .5}, size_hint=(1, 1), orientation='vertical')
     
     with button_layout.canvas.before:
         Color(.5, .5, .5, .2) 
         self.rect = Rectangle(size=button_layout.size, pos=button_layout.pos)
         
     name1_button = Button(font_size=25, text=name1+lastname1, size=(150,150))
     name2_button = Button(font_size=25, text=name2, size=(150,150))
     name3_button = Button(font_size=25, text=name3, size=(150,150))
     name4_button = Button(font_size=25, text=name4, size=(150,150))
     name5_button = Button(font_size=25, text=name5, size=(150,150))
     
     #name1_button.bind(on_release=self.get_flickr_images(name1))
     name2_button.bind(on_release=self.on_touch_down)
     
     button_layout.add_widget(name1_button)
     button_layout.add_widget(name2_button)
     button_layout.add_widget(name3_button)
     button_layout.add_widget(name4_button)
     button_layout.add_widget(name5_button)
     
     #s = Scatter(size_hint=(None, None), size=(450,250), pos=(300, 300), do_rotation=False, do_scale=False)
     #s.add_widget(button_layout)
     #f.add_widget(s)
     f.add_widget(button_layout)
     return f
Beispiel #27
0
        def build(self):
            root = FloatLayout()
            bx = BoxLayout()
            bx.add_widget(Button())
            bx.add_widget(Button())
            bx2 = BoxLayout()
            bx2.add_widget(Button())
            bx2.add_widget(Button())
            bx2.add_widget(Button())
            spl = Splitter(
                size_hint=(1, .25),
                pos_hint = {'top': 1},
                sizable_from = 'bottom')
            spl1 = Splitter(
                sizable_from='left',
                size_hint=(None, 1), width=90)
            spl1.add_widget(Button())
            bx.add_widget(spl1)
            spl.add_widget(bx)

            spl2 = Splitter(size_hint=(.25, 1))
            spl2.add_widget(bx2)
            spl2.sizable_from = 'right'
            root.add_widget(spl)
            root.add_widget(spl2)
            return root
Beispiel #28
0
 def __init__(self,bkground,sprites,*args,**kwargs):
     FloatLayout.__init__(self,*args,**kwargs)
     self.touch = 0,0
     self.bkground = bkground if isinstance(bkground,BackgroundWidget
                                            )else BackgroundWidget(bkground)
     self.isprites = sprites # ListProperty(background, cat, mouse)
     self.build_stage()
Beispiel #29
0
class TextAlignApp(App):

    def select(self, case):
        grid = GridLayout(rows=3, cols=3, spacing=10, size_hint=(None, None),
                          pos_hint={'center_x': .5, 'center_y': .5})
        for valign in ('bottom', 'middle', 'top'):
            for halign in ('left', 'center', 'right'):
                label = BoundedLabel(text='V: %s\nH: %s' % (valign, halign),
                              size_hint=(None, None),
                              halign=halign, valign=valign)
                if case == 0:
                    label.text_size = (None, None)
                elif case == 1:
                    label.text_size = (label.width, None)
                elif case == 2:
                    label.text_size = (None, label.height)
                else:
                    label.text_size = label.size
                grid.add_widget(label)

        if self.grid:
            self.root.remove_widget(self.grid)
        grid.bind(minimum_size=grid.setter('size'))
        self.grid = grid
        self.root.add_widget(grid)

    def build(self):
        self.root = FloatLayout()
        self.selector = Selector(app=self)
        self.root.add_widget(self.selector)
        self.grid = None
        self.select(0)
        return self.root
Beispiel #30
0
    def build(self):
        layout_main = BoxLayout(
            orientation='vertical',

        )
        text_input = TextInput(
            font_size=150,
            height=200,
            size_hint_y=None,
            text='default',
        )

        layout = FloatLayout()
        scatter = Scatter()
        label = Label(
            text="default",
            font_size=150,
        )

        text_input.bind(text=label.setter('text'))

        layout.add_widget(scatter)
        scatter.add_widget(label)

        # Order is important - first is top/left
        layout_main.add_widget(text_input)
        layout_main.add_widget(layout)

        return layout_main
Beispiel #31
0
    def build(self):

        interface = FloatLayout()
        self.data = Data()

        if self.config.get('Maslow Settings', 'colorScheme') == 'Light':
            self.data.iconPath = './Images/Icons/normal/'
            self.data.fontColor = '[color=7a7a7a]'
            self.data.drawingColor = [.47, .47, .47]
            Window.clearcolor = (1, 1, 1, 1)
            self.data.posIndicatorColor = [0, 0, 0]
            self.data.targetInicatorColor = [1, 0, 0]
        elif self.config.get('Maslow Settings', 'colorScheme') == 'Dark':
            self.data.iconPath = './Images/Icons/highvis/'
            self.data.fontColor = '[color=000000]'
            self.data.drawingColor = [1, 1, 1]
            Window.clearcolor = (0, 0, 0, 1)
            self.data.posIndicatorColor = [1, 1, 1]
            self.data.targetInicatorColor = [1, 0, 0]
        elif self.config.get('Maslow Settings',
                             'colorScheme') == 'DarkGreyBlue':
            self.data.iconPath = './Images/Icons/darkgreyblue/'
            self.data.fontColor = '[color=000000]'
            self.data.drawingColor = [1, 1, 1]
            Window.clearcolor = (0.06, 0.10, 0.2, 1)
            self.data.posIndicatorColor = [0.51, 0.93, 0.97]
            self.data.targetInicatorColor = [1, 0, 0]

        Window.maximize()

        self.frontpage = FrontPage(self.data, name='FrontPage')
        interface.add_widget(self.frontpage)

        self.nonVisibleWidgets = NonVisibleWidgets()
        '''
        Load User Settings
        '''

        # force create an ini no matter what.
        self.config.write()

        if self.config.get('Advanced Settings', 'encoderSteps') == '8148.0':
            self.data.message_queue.put(
                "Message: This update will adjust the the number of encoder pulses per rotation from 8,148 to 8,113 in your settings which improves the positional accuracy.\n\nPerforming a calibration will help you get the most out of this update."
            )
            self.config.set('Advanced Settings', 'encoderSteps', '8113.73')
        #up the maximum feedrate
        if self.config.get('Advanced Settings', 'maxFeedrate') == '700':
            self.data.message_queue.put(
                "Message: This update will increase the maximum feedrate of your machine. You can adjust this value under the Advanced settings."
            )
            self.config.set('Advanced Settings', 'maxFeedrate', '800')
            self.config.write()

        self.data.comport = self.config.get('Maslow Settings', 'COMport')
        self.data.baudRate = int(self.config.get('Maslow Settings',
                                                 'baudRate'))
        self.data.gcodeFile = self.config.get('Maslow Settings', 'openFile')
        offsetX = float(self.config.get('Advanced Settings', 'homeX'))
        offsetY = float(self.config.get('Advanced Settings', 'homeY'))
        self.data.gcodeShift = [offsetX, offsetY]
        self.data.config = self.config
        self.config.add_callback(self.configSettingChange)

        # Background image setup
        self.data.backgroundFile = self.config.get('Background Settings',
                                                   'backgroundFile')
        self.data.backgroundManualReg = json.loads(
            self.config.get('Background Settings', 'manualReg'))
        if self.data.backgroundFile != "":
            BackgroundMenu(self.data).processBackground()
        '''
        Initializations
        '''

        self.frontpage.setUpData(self.data)
        self.nonVisibleWidgets.setUpData(self.data)
        self.frontpage.gcodecanvas.initialize()
        '''
        Scheduling
        '''

        Clock.schedule_interval(self.runPeriodically, .01)
        '''
        Push settings to machine
        '''
        self.data.bind(connectionStatus=self.requestMachineSettings)
        self.data.pushSettings = self.requestMachineSettings

        return interface
	def build(self):
		return FloatLayout()
class Star_Gazer(App):
    def build(self):

        self.layout = BoxLayout(padding=5, orientation='vertical', spacing=5)

        #label 1
        self.label_crop = Label(text='Your Crop:', size_hint=[0.1, 0.1])
        self.layout.add_widget(self.label_crop)
        #first input
        self.txt1 = TextInput(text='', multiline=True)
        self.layout.add_widget(self.txt1)

        #label 2
        self.label_price = Label(text='Your Price:', size_hint=[0.1, 0.1])
        self.layout.add_widget(self.label_price)
        #second input
        self.txt2 = TextInput(text='', multiline=True)
        self.layout.add_widget(self.txt2)
        # 3rd label
        self.label_market = Label(text='Your Market:', size_hint=[0.1, 0.1])
        self.layout.add_widget(self.label_market)
        #third input
        self.txt3 = TextInput(text='', multiline=True)
        self.layout.add_widget(self.txt3)

        # second layout box
        self.layout2 = FloatLayout(size=[300, 300],
                                   pos_hint={
                                       'x': 1,
                                       'center_y': .5
                                   })
        self.layout.add_widget(self.layout2)
        #buttons
        self.btn1 = Button(text='Submit',
                           background_color=[0.09, 0.41, 1, 1.5],
                           size_hint=[0.48, 0.48],
                           pos=[12, 50],
                           font_size='30sp',
                           font_name='Calibri')

        self.btn1.bind(on_press=self.submit_form)

        self.layout2.add_widget(self.btn1)
        self.btn2 = Button(text="Check",
                           background_color=[0.09, 0.41, 1, 1.5],
                           size_hint=[0.48, 0.48],
                           pos=[405, 50],
                           font_size='30sp',
                           font_name='Calibri')
        self.btn2.bind(on_press=self.save)
        self.layout2.add_widget(self.btn2)

        return self.layout

    def back(self, button):
        self.layout.clear_widgets()

        #label 1
        label_crop = Label(text='Your Crop:', size_hint=[0.1, 0.1])
        self.layout.add_widget(label_crop)
        #first input
        self.txt1 = TextInput(text='', multiline=True)
        self.layout.add_widget(self.txt1)

        #label 2
        label_price = Label(text='Your Price:', size_hint=[0.1, 0.1])
        self.layout.add_widget(label_price)
        #second input
        self.txt2 = TextInput(text='', multiline=True)
        self.layout.add_widget(self.txt2)
        # 3rd label
        label_market = Label(text='Your Market:', size_hint=[0.1, 0.1])
        self.layout.add_widget(label_market)
        #third input
        self.txt3 = TextInput(text='', multiline=True)
        self.layout.add_widget(self.txt3)

        # second layout box

        layout2 = FloatLayout(size=[300, 300],
                              pos_hint={
                                  'x': 1,
                                  'center_y': .5
                              })
        self.layout.add_widget(layout2)
        #buttons
        btn1 = Button(text='Submit',
                      background_color=[0.09, 0.41, 1, 1.5],
                      size_hint=[0.48, 0.48],
                      pos=[12, 50],
                      font_size='30sp',
                      font_name='Calibri')

        btn1.bind(on_press=self.submit_form)

        layout2.add_widget(btn1)
        btn2 = Button(text="Check",
                      background_color=[0.09, 0.41, 1, 1.5],
                      size_hint=[0.48, 0.48],
                      pos=[405, 50],
                      font_size='30sp',
                      font_name='Calibri')
        btn2.bind(on_press=self.save)
        layout2.add_widget(btn2)

    def submit_form(self, button1):
        crop1 = self.txt1.text
        price1 = self.txt2.text
        market1 = self.txt3.text
        crop = str(crop1).lower().strip()
        crop = crop.title()
        price = str(price1).lower().strip()
        market = str(market1).lower().strip()
        self.layout.clear_widgets()

        #get data if market there print 5 + market index value else pass
        print(crop)

        if crop == 'Corn':

            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Var&CommCode=4&VarCode=8&Date=09/01/2018&CommName=Maize%20/%20%E0%B2%AE%E0%B3%86%E0%B2%95%E0%B3%8D%E0%B2%95%E0%B3%86%E0%B2%9C%E0%B3%8B%E0%B2%B3&VarName=Hybrid/Local%20/%20%E0%B2%B9%E0%B3%88%E0%B2%AC%E0%B3%8D%E0%B2%B0%E0%B2%BF%E0%B2%A1%E0%B3%8D%20%E0%B2%B8%E0%B3%8D%E0%B2%A5%E0%B2%B3%E0%B3%80%E0%B2%AF"
            ) as url:
                data_page = url.read()
            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:150]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)

            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(
                        text='Your Selling Price: ' + str_final +
                        "             Today's Profit: " + profit,
                        font_size='40sp',
                        size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(
                        text='Your Selling Price: ' + str_final +
                        "              Unsure about today's profit",
                        font_size='40sp',
                        size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(
                        text='Your Selling Price: ' + str_final +
                        "          Today's Profit: " + profit,
                        font_size='40sp',
                        size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(
                        text='Your Selling Price: ' + str_final +
                        "          Unsure about today's profit",
                        font_size='40sp',
                        size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)

        elif crop == 'Red':
            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Var&CommCode=1&VarCode=71&Date=18/01/2018&CommName=Wheat%20/%20%E0%B2%97%E0%B3%8B%E0%B2%A7%E0%B2%BF&VarName=Red%20/%20%E0%B2%95%E0%B3%86%E0%B2%82%E0%B2%AA%E0%B3%81"
            ) as url:
                data_page = url.read()

            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:18]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)
            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "   Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
        #cotton
        elif crop == 'Cotton':
            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Com&CommCode=15&VarCode=5&Date=10/02/2018&CommName=Cotton%20/%20%E0%B2%B9%E0%B2%A4%E0%B3%8D%E0%B2%A4%E0%B2%BF&VarName=Suyodhar%20/%20%E0%B2%B8%E0%B3%81%E0%B2%AF%E0%B3%8B%E0%B2%A7%E0%B2%B0%E0%B3%8D"
            ) as url:
                data_page = url.read()

            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:1000]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)
            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 7])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 7])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "   Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[7])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[7])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)

        elif crop == 'Wheat':

            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Com&CommCode=1&VarCode=7&Date=09/01/2018&CommName=Wheat%20/%20%E0%B2%97%E0%B3%8B%E0%B2%A7%E0%B2%BF&VarName=Bansi%20/%20%E0%B2%AC%E0%B2%A8%E0%B3%8D%E0%B2%B8%E0%B2%BF"
            ) as url:
                data_page = url.read()

            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:118]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)

            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "   Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)

        elif crop == 'Lemon':
            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Var&CommCode=180&VarCode=1&Date=09/01/2018&CommName=Lime%20(Lemon)%20/%20%E0%B2%A8%E0%B2%BF%E0%B2%82%E0%B2%AC%E0%B3%86%E0%B2%B9%E0%B2%A3%E0%B3%8D%E0%B2%A3%E0%B3%81&VarName=Lime%20(Lemon)%20/%20%E0%B2%A8%E0%B2%BF%E0%B2%82%E0%B2%AC%E0%B3%86%E0%B2%B9%E0%B2%A3%E0%B3%8D%E0%B2%A3%E0%B3%81"
            ) as url:
                data_page = url.read()

            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:30]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)
            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "   Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)

        elif crop == 'Navane':
            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Com&CommCode=121&VarCode=1&Date=09/01/2018&CommName=Navane%20/%20%E0%B2%A8%E0%B2%B5%E0%B2%A3%E0%B3%86&VarName=Navane%20Hybrid%20/%20%E0%B2%A8%E0%B2%B5%E0%B2%A3%E0%B3%86%20%E0%B2%B9%E0%B3%88%E0%B2%AC%E0%B3%8D%E0%B2%B0%E0%B2%BF%E0%B2%A1%E0%B3%8D"
            ) as url:
                data_page = url.read()

            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:76]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)
            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 5])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "   Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[5])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
        #barley
        elif crop == 'Barley':
            with urllib.request.urlopen(
                    "https://www.krishimaratavahini.kar.nic.in/MainPage/DailyMrktPriceRep2.aspx?Rep=Com&CommCode=15&VarCode=5&Date=10/02/2018&CommName=Cotton%20/%20%E0%B2%B9%E0%B2%A4%E0%B3%8D%E0%B2%A4%E0%B2%BF&VarName=Suyodhar%20/%20%E0%B2%B8%E0%B3%81%E0%B2%AF%E0%B3%8B%E0%B2%A7%E0%B2%B0%E0%B3%8D"
            ) as url:
                data_page = url.read()

            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            value_list = []
            for farmer_value in values[12:1000]:
                final_value = cleanhtml(str(farmer_value))
                value_list.append(final_value)
            if market in value_list and market != '':
                index_value = value_list.index(market)
                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)

                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = float(value_list[index_value + 7])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                else:
                    final = float(value_list[index_value + 7])
                    print(final / 100)
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "   Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)

            else:

                with urllib.request.urlopen(
                        "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                        context=gcontext) as url:
                    data_page = url.read()
                soup = BeautifulSoup(data_page)
                values = soup.findAll('td')
                profit_list = []
                for farmer_value in values[23:10000]:
                    final_value = cleanhtml(str(farmer_value))
                    final_value = ' '.join(final_value.split())

                    profit_list.append(final_value)
                if crop in profit_list:
                    index = profit_list.index(crop)
                    profit = profit_list[index + 7]
                    profit = int(profit)
                    profit = profit / 100
                    profit = str(profit)
                    final = int(value_list[7])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Today's Profit: " + profit,
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)
                else:
                    final = int(value_list[7])
                    str_final = str(final / 100 - final / 100 * .238)
                    output_label = TextInput(text='Your Selling Price: ' +
                                             str_final +
                                             "    Unsure about today's profit",
                                             font_size='40sp',
                                             size_hint=[1, .8])
                    self.layout.add_widget(output_label)
                    print(final / 100)

        else:
            output_label = TextInput(
                text=
                "You have likely misspelled the name of your crop or it's a new crop click save to add that crop to data base",
                font_size='40sp',
                size_hint=[1, .8])
            self.layout.add_widget(output_label)

            print(
                'You have likely misspelled the name of your crop or have not input a crop'
            )

        #write out string or integer to list considering all possible crop names
        button_back = Button(text='Back',
                             background_color=[0.09, 0.41, 1, 1.5],
                             size_hint=[1, 0.48],
                             pos=[12, 50],
                             font_size='50sp',
                             font_name='Calibri')
        button_back.bind(on_press=self.back)
        self.layout.add_widget(button_back)

    #save button command
    def save(self, button2):
        crop1 = self.txt1.text
        price1 = self.txt2.text
        crop = str(crop1)
        crop = crop.title()
        price = str(price1)
        print(crop)

        if crop == "":
            self.layout.clear_widgets()
            output_label = TextInput(
                text=
                'No crop has been input please press back and enter a crop',
                font_size='40sp')
            self.layout.add_widget(output_label)
            button_back = Button(text='Back',
                                 background_color=[0.09, 0.41, 1, 1.5],
                                 size_hint=[1, 0.48],
                                 pos=[12, 50],
                                 font_size='50sp',
                                 font_name='Calibri')
            button_back.bind(on_press=self.back)
            self.layout.add_widget(button_back)
            return
        if price == "":
            self.layout.clear_widgets()
            output_label = TextInput(
                text=
                'No price has been input please press back and enter a price',
                font_size='40sp')
            self.layout.add_widget(output_label)
            button_back = Button(text='Back',
                                 background_color=[0.09, 0.41, 1, 1.5],
                                 size_hint=[1, 0.48],
                                 pos=[12, 50],
                                 font_size='50sp',
                                 font_name='Calibri')
            button_back.bind(on_press=self.back)
            self.layout.add_widget(button_back)
            return
        else:
            with urllib.request.urlopen(
                    "https://www.ncdex.com/MarketData/LiveFuturesQuotes.aspx",
                    context=gcontext) as url:
                data_page = url.read()
            soup = BeautifulSoup(data_page)
            values = soup.findAll('td')
            profit_list = []
            for farmer_value in values[23:10000]:
                final_value = cleanhtml(str(farmer_value))
                final_value = ' '.join(final_value.split())

                profit_list.append(final_value)
            if crop in profit_list:
                profit = profit_list.index(crop)
                profit = profit_list[profit + 5]
                profit = float(profit)
                profit = profit / 100
                price = float(price)
                profit = price - profit
                if profit < 0:

                    profit = str(profit)

                    self.layout.clear_widgets()
                    output_label = TextInput(
                        text='Your Profit: ' + profit +
                        ' you need to sell for a higher price',
                        font_size='40sp')
                    self.layout.add_widget(output_label)
                    button_back = Button(text='Back',
                                         background_color=[0.09, 0.41, 1, 1.5],
                                         size_hint=[1, 0.48],
                                         pos=[12, 50],
                                         font_size='50sp',
                                         font_name='Calibri')
                    button_back.bind(on_press=self.back)
                    self.layout.add_widget(button_back)
                else:
                    profit = str(profit)

                    self.layout.clear_widgets()
                    output_label = TextInput(
                        text='Your Profit: ' + profit +
                        ' you need to sell for a lower price',
                        font_size='40sp')
                    self.layout.add_widget(output_label)
                    button_back = Button(text='Back',
                                         background_color=[0.09, 0.41, 1, 1.5],
                                         size_hint=[1, 0.48],
                                         pos=[12, 50],
                                         font_size='50sp',
                                         font_name='Calibri')
                    button_back.bind(on_press=self.back)
                    self.layout.add_widget(button_back)
            else:
                self.layout.clear_widgets()
                output_label = TextInput(text='Sorry ' + crop +
                                         ' is not in our database',
                                         font_size='40sp')
                self.layout.add_widget(output_label)
                button_back = Button(text='Back',
                                     background_color=[0.09, 0.41, 1, 1.5],
                                     size_hint=[1, 0.48],
                                     pos=[12, 50],
                                     font_size='50sp',
                                     font_name='Calibri')
                button_back.bind(on_press=self.back)
                self.layout.add_widget(button_back)
        '''
Beispiel #34
0
class CharacterScreen(Screen):
    def __init__(self, **kwargs):
        super(CharacterScreen, self).__init__(**kwargs)
        self.add_widget(
            Image(
                #change to src
                source="src/images/background.jpg",
                allow_stretch=True,
                keep_ratio=False))

        self.layout = FloatLayout()
        self.add_widget(self.layout)

        self.panes = []

        sheet = self.create_sheet()
        self.layout.add_widget(sheet)

        buttons = self.create_buttons()
        self.add_widget(buttons)

        self.back_button = Button(font_name='src/fonts/Enchanted_Land.otf',
                                  font_size=24,
                                  text='Back',
                                  size_hint=(.10, .05),
                                  pos_hint={
                                      'center_x': .95,
                                      'bottom_y': .025
                                  })

        self.add_widget(self.back_button)

    def create_buttons(self):
        buttons = BoxLayout(orientation='horizontal',
                            size_hint=(.5, .05),
                            pos_hint={
                                'center_x': .325,
                                'center_y': .1
                            },
                            spacing=15)

        save_button = Button(font_name='src/fonts/Enchanted_Land.otf',
                             font_size=24,
                             text='Save')
        save_button.bind(on_release=self.save_sheet)
        buttons.add_widget(save_button)

        new_button = Button(font_name='src/fonts/Enchanted_Land.otf',
                            font_size=24,
                            text='New')
        buttons.add_widget(new_button)

        load_button = Button(font_name='src/fonts/Enchanted_Land.otf',
                             font_size=24,
                             text='Load')
        load_button.bind(on_release=self.load_sheet)
        buttons.add_widget(load_button)

        return buttons

    def create_sheet(self):
        character_sheet = TabbedPanel(tab_pos='top_mid',
                                      size_hint=(.85, .85),
                                      pos_hint={
                                          'center_x': .5,
                                          'center_y': .5
                                      },
                                      do_default_tab=False)
        general_tab = GeneralTab(font_name='src/fonts/Enchanted_Land.otf',
                                 font_size=24)

        self.panes.append(general_tab)

        attributes_tab = AttributesTab(
            font_name='src/fonts/Enchanted_Land.otf', font_size=24)
        self.panes.append(attributes_tab)

        skills_tab = SkillsTab(font_name='src/fonts/Enchanted_Land.otf',
                               font_size=24)
        self.panes.append(skills_tab)

        weapon_tab = WeaponTab(font_name='src/fonts/Enchanted_Land.otf',
                               font_size=24)
        self.panes.append(weapon_tab)

        armor_tab = ArmorTab(font_name='src/fonts/Enchanted_Land.otf',
                             font_size=24)
        self.panes.append(armor_tab)

        spells_tab = self.create_spells()
        self.panes.append(spells_tab)

        character_sheet.add_widget(general_tab)
        character_sheet.add_widget(attributes_tab)
        #NOTE ADD FEATS TO SKILLS
        character_sheet.add_widget(skills_tab)
        character_sheet.add_widget(weapon_tab)
        character_sheet.add_widget(armor_tab)
        character_sheet.add_widget(spells_tab)

        return character_sheet

    def create_spells(self):
        spells = TabbedPanelHeader(font_name='src/fonts/Enchanted_Land.otf',
                                   font_size=24,
                                   text='Spells')
        return spells

    def general_make_serializable(self):
        general_dict = {}
        general_dict['name'] = self.panes[0].name_input.text
        general_dict['alignment'] = self.panes[0].alignment_input.text
        general_dict['class'] = self.panes[0].class_input.text
        general_dict['level'] = self.panes[0].level_input.text
        general_dict['gender'] = self.panes[0].gender_input.text
        general_dict['race'] = self.panes[0].race_input.text
        general_dict['age'] = self.panes[0].age_input.text
        general_dict['height'] = self.panes[0].height_input.text
        general_dict['weight'] = self.panes[0].weight_input.text
        general_dict['size'] = self.panes[0].size_input.text
        return general_dict

    def save_sheet(self, *args):
        file_handler = filehandler.FileHandler()
        save_dict = self.general_make_serializable()
        file_handler.show_save_popup(save_dict)

    def load_sheet(self, *args):
        file_handler = filehandler.FileHandler()
        file_handler.show_load_popup()
Beispiel #35
0
 def build(self):
     f = FloatLayout()
     f.add_widget(Item("Hola"))
     f.add_widget(Item("Mundo"))
     return f
Beispiel #36
0
class GamesScreen(Screen):
    def __init__(self, **kwargs):
        Screen.__init__(self, **kwargs)
        with self.canvas:
            self.rectangle = Rectangle (source = 'game-06.png', size = self.size, pos_hint = self.pos)
            self.bind(pos = self.update_rect, size = self.update_rect)
#         Window.bind(on_key_up=self._keyup)
        Window.bind(on_key_down=self._keydown)
        
        self.layout= FloatLayout()
        self.sm = Typing_sm()
        self.sm.start()
        
        self.diff_lvl = Label(text = 'Level: ' + difficulty[difficulty['choice']], font_size = 24,size_hint = (.1,.1),pos_hint = {'x':0.1, 'y': 0})
        self.layout.add_widget(self.diff_lvl)
        self.life_indicator = Label(text = 'Lives left: 0' + str(life['hearts']), font_size = 24, size_hint = (.1,.1), pos_hint = {'x':0.1, 'y': 0.9})
        self.layout.add_widget(self.life_indicator)
        self.timer = Countdown(font_size = 48, pos_hint = {'x':0, 'y': 0.1})
        self.layout.add_widget(self.timer)
        self.label = Label(text = 'Start', font_size = 24,size_hint =(.1,.1), pos_hint = {'x':.4, 'y': .75})
        self.layout.add_widget(self.label)
        self.reminder = Label (text = 'DOUBLE CLICK TEXTBOX!!', font_size = 24, pos_hint = {'x':0, 'y': 0.1})
        self.layout.add_widget(self.reminder)
        self.total_words = ''
        self.inp = MyInput(hint_text = "type here", pos_hint = {'x':.4, 'y': .65}, on_double_tap = self.startCountdown)
        self.layout.add_widget(self.inp)
        self.add_widget(self.layout)
      
    def update_rect(self, *args): 
        self.rectangle.pos = self.pos 
        self.rectangle.size = self.size 
    
#     def _keyup(self,*args):
#         print('key up!!', args)

    def startCountdown(self, *args):
        self.layout.remove_widget(self.reminder)
        self.timer.start()
    
    def _keydown(self,*args):
        diff_name = difficulty[difficulty['choice']]
        word_dic = dictionaries[diff_name]
        if self.sm.state == 'norm':
            if args[3] == None and args[1] == 13 and args[2] == 40: #'enter key'
                user = self.inp.text.strip()
                word = self.label.text
                self.sm.step(user, word)
                self.total_words += user
                self.inp.text = ' '
                self.inp.focus = True
                num = random.randrange(0, len(word_dic))
                word = word_dic[num]
                self.label.text = word
        elif self.sm.state == 'wrong' and life['hearts'] > 0:
            #removing hearts
            self.remove_widget(self.heartlayout)
            
            #update lives and state
            life['hearts']-= 1
            self.sm.state = 'norm'
            self.life_indicator.text = 'Lives left: 0' + str(life['hearts'])
            
            #adding hearts
            self.heartlayout = FloatLayout()
            for i in range(life['hearts']): 
                self.hearts = HeartButtons(text = '',pos =(30+ 70*i,500))
                self.heartlayout.add_widget(self.hearts)
            self.add_widget(self.heartlayout)
        if life['hearts'] == 0:
            #access the Main widget Screen Manager
            self.manager.transition.direction = 'up' 
            # modify the current screen to a different "name"
            fail = sm.get_screen('fail')
            characters = str(len(self.total_words))
            stat = Label(text = 'you typed ' + characters + ' characters per minute.', size_hint=(.1,.1), pos_hint = {'x':.3, 'y': .5})
            fail.layout.add_widget(stat)
            self.manager.current = 'fail'
        return True
Beispiel #37
0
    def build(self):
        #self.init_GPIO()

        #layout = BoxLayout(orientation='vertical')
        layout = FloatLayout(size=(800, 480), pos=(0, 0))

        self._toggle = ToggleButton(text='LED OFF',
                                    size_hint=(0.2, 0.2),
                                    pos_hint={'pos': (0.8, 0)})

        self._snap = Button(text='Capture',
                            size_hint=(0.2, 0.2),
                            pos_hint={'pos': (0.8, 0.2)})

        self._snapref = Button(text='Reference',
                               size_hint=(0.2, 0.2),
                               pos_hint={'pos': (0.8, 0.4)})

        self._demo = Button(text='Demo Results',
                            size_hint=(0.2, 0.1),
                            pos_hint={'pos': (0.0, 0.7)})

        self._auto_centroid = ImageButton(
            size_hint=(0.1, 0.1),
            pos_hint={'pos': (0.7, 0)},
            source='/home/pi/d3-ui/img/distribution_centroid_off.png')

        self._object_detection = ImageButton(
            size_hint=(0.1, 0.1),
            pos_hint={'pos': (0.7, 0.1)},
            source='/home/pi/d3-ui/img/object_detection_off.png')

        self._reset_scatter = ImageButton(
            size_hint=(0.1, 0.1),
            pos_hint={'pos': (0.7, 0.2)},
            source='/home/pi/d3-ui/img/reset_scatter.png')

        self._exit = Button(text='X',
                            size_hint=(0.05, 0.05),
                            pos_hint={'pos': (0.95, 0.95)})

        self._fps = Label(text='FPS: 0',
                          size_hint=(0.1, 0.1),
                          pos_hint={'pos': (0.8, 0.9)})
        self._uploading = Label(text='Uploading...',
                                size_hint=(0.2, 0.1),
                                pos_hint={'pos': (-1, -1)},
                                color=[0, 0, 1, 0])
        self._uploadingAmt = Label(text='',
                                   size_hint=(0.2, 0.1),
                                   pos_hint={'pos': (-1, -1)},
                                   color=[0, 0, 1, 0])

        self._exposure = Label(text='Exposure: 0',
                               size_hint=(0.2, 0.1),
                               pos_hint={'pos': (0, 0)})

        self._centroid = Label(text='C:0',
                               size_hint=(0.1, 0.1),
                               pos_hint={'pos': (0.79, 0.83)},
                               color=[1, 0, 0, 1])

        self._exposure_slider = Slider(min=0,
                                       max=2500,
                                       value=333,
                                       size_hint=(0.5, 0.1),
                                       pos_hint={'pos': (0.2, 0)})

        self._upload_progress = ProgressBar(max=100,
                                            size_hint=(0.5, 0.1),
                                            pos_hint={'pos': (-1, -1)})

        self._camera = Camera(
            resolution=(640, 480),
            fourcc="GREY",
            capture_resolution=(3872, 2764),
            capture_fourcc="Y16 ",
            size_hint=(1, 1),
            pos_hint={'pos': (0, 0)},
            play=True,
        )

        self._dropdown = DropDown()

        # create a big main button
        self._imageResultsButton = Button(text='Image Explorer',
                                          pos_hint={'pos': (0.0, 0.6)},
                                          size_hint=(0.2, 0.1))

        # show the dropdown menu when the main button is released
        # note: all the bind() calls pass the instance of the caller (here, the
        # mainbutton instance) as the first argument of the callback (here,
        # dropdown.open.).
        self._imageResultsButton.bind(on_release=self._dropdown.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        self._dropdown.bind(on_select=lambda instance, x: setattr(
            self._imageResultsButton, 'text', x))

        # self._camera = CameraD3(resolution=(1280,720),
        #                         play=True, fourcc="GREY")

        # self._camera = CameraD3(resolution=(3872, 2764),
        #                       play=True, fourcc="Y16 ")

        # self._camera = CameraD3(resolution=(1920,1080),
        #                        play=True, fourcc="GREY")

        # self._camera = CameraD3(resolution=(2560, 1920),
        #                        play=True, fourcc="GREY")

        self._histogram = Histogram(size_hint=(0.2, 0.3),
                                    pos_hint={'pos': (0.8, 0.6)})

        self._demo.bind(on_press=self._show_demo_results)
        self._toggle.bind(on_press=self._led_toggle)
        self._snap.bind(on_press=self._request_capture)
        self._snapref.bind(on_press=self._request_ref_capture)
        self._exit.bind(on_press=self._exit_app)
        self._auto_centroid.bind(on_press=self._auto_change_exposure)
        self._object_detection.bind(on_press=self._toggle_object_detection)
        self._exposure_slider.bind(value=self._change_exposure)
        self._reset_scatter.bind(on_press=self._do_reset_scatter)

        #update.bind(on_press=self._update_histogram)
        self._camera.fbind('on_frame_complete', self._update_histogram)

        self._scatter = Scatter(
            size_hint=(None, None),
            size=(200, 200),
        )
        self._scatter.add_widget(self._camera)
        #layout.add_widget(self._camera)
        layoutInner = FloatLayout(size_hint=(0.8, 1),
                                  pos_hint={
                                      'x': 0,
                                      'y': 0
                                  })
        layoutInner.add_widget(self._scatter)
        layout.add_widget(layoutInner)

        mat = Matrix().scale(10, 10, 10).translate(0, -150, 0)
        self._scatter.apply_transform(mat)
        layout.add_widget(self._imageResultsButton)
        layout.add_widget(self._uploading)
        layout.add_widget(self._uploadingAmt)
        layout.add_widget(self._demo)
        layout.add_widget(self._histogram)
        layout.add_widget(self._snap)
        layout.add_widget(self._snapref)
        layout.add_widget(self._exit)
        layout.add_widget(self._centroid)
        layout.add_widget(self._exposure_slider)
        layout.add_widget(self._upload_progress)
        layout.add_widget(self._auto_centroid)
        layout.add_widget(self._object_detection)
        layout.add_widget(self._reset_scatter)

        layout.add_widget(self._exposure)
        layout.add_widget(self._fps)
        Clock.schedule_interval(self._update_fps, 2)
        layout.add_widget(self._toggle)
        #layout.add_widget(update)

        self._is_updating = False
        self.updateImages()
        return layout
Beispiel #38
0
class MyLayout(GridLayout):

    url_ans_dict = {
        "https://homepages.cae.wisc.edu/~ece533/images/airplane.png":
        ("airplane", "bird"),
        "https://homepages.cae.wisc.edu/~ece533/images/baboon.png":
        ("Baboon", "Human"),
        "https://homepages.cae.wisc.edu/~ece533/images/cat.png":
        ("Cat", "Tiger"),
        "https://homepages.cae.wisc.edu/~ece533/images/girl.png":
        ('Girl', "Car")
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 1
        self.load_new_image(url=list(self.url_ans_dict.keys())[0])

    def ans_correct_callback(self, url, instance):
        print(f"This button was called - {instance.text}")
        if self.url_ans_dict.get(url)[0] == instance.text:
            print("Correct answer")
            correct = True
        else:
            print("Wrong Answer")
            correct = False
        self.show_popup(correct)
        self.clear_widgets()
        rand_int = random.randint(1, len(list(self.url_ans_dict.keys())) - 1)
        self.load_new_image(list(self.url_ans_dict.keys())[rand_int])

    def show_popup(self, correct):
        layout = GridLayout(cols=1, padding=10)
        label = Label(text="Correct") if correct else Label(
            text="Wrong Answer")
        layout.add_widget(label)
        popup = Popup(title="",
                      content=layout,
                      size_hint=(None, None),
                      size=(200, 200),
                      auto_dismiss=True)
        popup.open()

    def load_new_image(self, url):

        self.ans_button = self.url_ans_dict.get(url)
        self.add_widget(AsyncImage(source=url))
        self.bottom_layout = FloatLayout(size=(600, 600))
        self.ans_1 = Button(text=self.ans_button[0],
                            background_color=(0.1, 0.5, 0.3, 1),
                            size_hint=(0.2, 0.2),
                            pos_hint={
                                'x': 0.3,
                                'y': 0.5
                            })
        buttoncallback = lambda *args: self.ans_correct_callback(url, *args)
        self.ans_1.bind(on_press=buttoncallback)
        self.bottom_layout.add_widget(self.ans_1)
        self.ans_2 = Button(text=self.ans_button[1],
                            background_color=(0.1, 0.5, 0.3, 1),
                            size_hint=(0.2, 0.2),
                            pos_hint={
                                'x': 0.5,
                                'y': 0.5
                            })
        self.ans_2.bind(on_press=buttoncallback)
        self.bottom_layout.add_widget(self.ans_2)
        self.add_widget(self.bottom_layout)
Beispiel #39
0
    def __init__(self, **kwargs):
        super(ParameterScreen1, self).__init__(**kwargs)
        screen_layout = FloatLayout()
        # parametry:
        # 0 - sex, 1 - age, 2 - weight, 3 - height, 4 - food, 5 - metabolism
        self.body_parameters = [0, 0, 0, 0, 0, 0]

        screen_layout.add_widget(SexSlider(self.body_parameters))
        screen_layout.add_widget(AgeSlider(self.body_parameters))
        screen_layout.add_widget(WeightSlider(self.body_parameters))
        screen_layout.add_widget(HeightSlider(self.body_parameters))
        screen_layout.add_widget(MetabolismSlider(self.body_parameters))
        screen_layout.add_widget(FoodSlider(self.body_parameters))

        next_button = Button(text='Następny krok',
                             size_hint=(.3, .1),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .1
                             })
        next_button.bind(on_press=self.on_press_button)
        screen_layout.add_widget(next_button)

        self.add_widget(screen_layout)
Beispiel #40
0
 def __init__(self, **kw):
     self.content = FloatLayout()
     super(RelativeLayout, self).__init__(**kw)
     super(RelativeLayout, self).add_widget(self.content)
     self.bind(size=self.update_size)
Beispiel #41
0
 def build(self):
     self.root = FloatLayout()
     self.root.add_widget(Game())
     return self.root
Beispiel #42
0
    def update_plants(self, *args):
        try:
            self.remove_widget(self.grid_layout)
        except:
            pass

        grid_layout = GridLayout(cols=2)

        # left side of display
        layout_left = FloatLayout()

        # colored background for left side of main menu
        layout_left.canvas.add(brown_color)
        layout_left.canvas.add(
            Rectangle(pos=(0, 0),
                      size=(screen_width / 2, screen_height),
                      orientation='horizontal'))
        layout_left.add_widget(
            Label(
                text="[b][size=42][color=#5C4940]PLANTHING[/color][/size][/b]",
                markup=True,
                size_hint=(.5, .5),
                pos_hint={
                    'x': .25,
                    'y': .4
                }))

        # reading humidity and temp using sensors.get_humidity_temp()
        temp_humidity = sensors.get_humidity_temp(
        )  #{'temperature': 0, 'humidity': 0 }

        temperature_string = "[b][size=18][color=#5C4940]Temperature: {0} C[/color][/size][/b]".format(
            temp_humidity["temperature"])
        humidity_string = "[b][size=18][color=#5C4940]Humidity: {0}%[/color][/size][/b]".format(
            temp_humidity["humidity"])

        # temperature display
        self.temperature_widget = Label(text=temperature_string,
                                        markup=True,
                                        size_hint=(.5, .05),
                                        pos_hint={
                                            'x': .25,
                                            'y': 0.2
                                        })
        layout_left.add_widget(self.temperature_widget)

        # humidity display
        self.humidity_widget = Label(text=humidity_string,
                                     markup=True,
                                     size_hint=(.5, .05),
                                     pos_hint={
                                         'x': .25,
                                         'y': 0.15
                                     })
        layout_left.add_widget(self.humidity_widget)

        # four plants on display
        layout_right = FloatLayout(cols=2,
                                   row_force_default=True,
                                   row_default_height=screen_height / 2)
        layout_right.canvas.add(Color(1, 1, 1))
        layout_right.canvas.add(
            Rectangle(pos=(screen_width / 2, 0),
                      size=(screen_width / 2, screen_height),
                      orientation='horizontal'))

        # initialize the plants
        plant_size = 0.3  # plant image width is 30% of width
        plant_padding = (0.5 -
                         plant_size) / 2  # total space for each plant is 50%
        positions = [(plant_padding, 0.5 + plant_padding),
                     (0.5 + plant_padding, 0.5 + plant_padding),
                     (plant_padding, plant_padding),
                     (0.5 + plant_padding, plant_padding)]

        total_plants = 4
        for i in range(total_plants):
            # Position of this button
            (x, y) = positions[i]

            # Add brown background for each plant
            layout_right.canvas.add(brown_color)
            layout_right.canvas.add(
                Rectangle(
                    pos=(screen_width / 2 + (x - 0.035) * screen_width / 2,
                         (y - 0.08) * screen_height),
                    size=(150, 210),
                    orientation='horizontal'))

            # If plant exists, add it
            if i < len(plants):
                plant = plants[i]

                # each plant icon is a button
                plant_button = ImageButton(source=plant["plant_image"],
                                           on_press=partial(
                                               self.view_detail,
                                               plant_id=plant["plant_id"]),
                                           size_hint=(plant_size, plant_size),
                                           pos_hint={
                                               'x': x,
                                               'y': y
                                           })

                layout_right.add_widget(plant_button)

                # adding in names of plants
                plant_text = "[b][color=#5C4940]{0}[/color][/b]".format(
                    plant['name'])
                label_height = 0.05
                label_offset = 0.09
                layout_right.add_widget(
                    Label(text=plant_text,
                          markup=True,
                          size_hint=(plant_size, label_height),
                          pos_hint={
                              'x': x,
                              'y': y - plant_size / 2 + label_offset
                          }))
            else:
                # Plant doesn't exist, allow users to add new plant
                plant_button = Button(
                    text=
                    "[b][size=18][color=#5C4940]Add Plant[/color][/size][/b]",
                    markup=True,
                    background_color=[0, 0, 0, 0],
                    on_press=self.add_plant,
                    size_hint=(plant_size, plant_size),
                    pos_hint={
                        'x': x,
                        'y': y - 0.035
                    })
                layout_right.add_widget(plant_button)
                plant_background = Rectangle(pos=(x, y),
                                             size=(plant_size, plant_size),
                                             orientation='horizontal')
                layout_right.canvas.add(plant_background)

        # add left and right screens
        grid_layout.add_widget(layout_left)
        grid_layout.add_widget(layout_right)

        self.add_widget(grid_layout)
        self.grid_layout = grid_layout
Beispiel #43
0
def CellPopup(gear, screen, character, main, button):
    fL = FloatLayout()
    name = Cards.Text("name", gear.name)
    type = Cards.Text("type", gear.type)
    text = Cards.Text("text", gear.definition)

    border = Image(source="GearCard.png",
                   size_hint=(.85, .85),
                   pos_hint={
                       "center_x": .5,
                       "y": .13
                   },
                   allow_stretch=True)
    border.add_widget(
        Image(texture=name,
              pos=(295, 388),
              size=(220, 220),
              allow_stretch=True))
    border.add_widget(
        Image(texture=type,
              pos=(295, 363),
              size=(220, 220),
              allow_stretch=True))
    border.add_widget(
        Image(texture=text, pos=(278, 80), size=(250, 250),
              allow_stretch=True))

    b4 = Button(size_hint=(.4, .1),
                pos_hint={
                    "center_x": .27,
                    "y": .012
                },
                text="Discard")
    fL.add_widget(border)
    fL.add_widget(b4)

    popup = Popup(title='Card Viewer',
                  content=fL,
                  size_hint=(None, None),
                  size=(410, 580))

    b2 = Button(name="item",
                text=str(gear.quality),
                size_hint=(.05, .02),
                color=(0, 0, 0, 1),
                pos_hint={
                    "center_x": .81,
                    "y": .195
                },
                background_color=(0, 0, 0, 0))
    b5 = Button(size_hint=(.4, .1),
                pos_hint={
                    "center_x": .73,
                    "y": .012
                },
                text="Use")
    fL.add_widget(b2)
    fL.add_widget(b5)
    qlt = gear.quality
    b2.bind(on_release=partial(Screens.WeaponPlusMinus, qlt, gear))
    b5.bind(on_release=partial(UsePopup, gear, screen, popup, character, main))
    b4.bind(
        on_release=partial(DiscardPopup, gear, screen, popup, character, main))

    if screen.name == "confirm":
        b4.disabled = True
        b5.disabled = True

    popup.open()
Beispiel #44
0
class LevelScreen(Screen):
    def __init__(self, **kwargs):
        Screen.__init__(self, **kwargs)
        with self.canvas:
            self.rectangle = Rectangle (source = 'lvl_5.png', size = self.size, pos_hint = self.pos)
            self.bind(pos = self.update_rect, size = self.update_rect)
        self.layout = FloatLayout()
    
        plus_btn = Button(text = "+", size_hint=(.1, .1),background_normal= '', color = [0,0,0,1],
                pos_hint={'x':.4, 'y':.5}, on_release = self.life_plus)
        minus_btn = Button(text = "-", size_hint=(.1, .1),background_normal= '', color = [0,0,0,1],
                pos_hint={'x':.2, 'y':.5}, on_release = self.life_minus)
        self.layout.add_widget(plus_btn)
        self.layout.add_widget(minus_btn)
               
        self.lifelines = Label(text = 'Lifelines: 0' + str(life['hearts']), font_size = 24, size_hint =(.1,.1), pos_hint = {'x':.3, 'y': .6})
        self.layout.add_widget(self.lifelines)
        
        self.difficulty = 0
        up_btn = Button(text = ">", size_hint=(.1, .1), background_normal= '', color = [0,0,0,1], 
                        pos_hint ={'x':.8, 'y':.5}, on_release = self.difficulty_up)
        down_btn = Button(text = "<", size_hint=(.1, .1),background_normal= '', color = [0,0,0,1],
                pos_hint={'x':.6, 'y':.5}, on_release = self.difficulty_down)                  
        self.layout.add_widget(up_btn)                               
        self.layout.add_widget(down_btn)
        
        self.diff_lvl = Label(text = difficulty[self.difficulty], font_size = 24, size_hint =(.1,.1), pos_hint = {'x':.7, 'y': .6})
        self.layout.add_widget(self.diff_lvl)
                         
        confirm_btn = Button(text = 'confirm', size_hint = (.2,.1), background_normal= '', color = [0,0,0,1], 
                             pos_hint = {'x':.45, 'y': .2}, on_release = self.change_to_game)
        self.layout.add_widget(confirm_btn)                    
                          
        self.add_widget(self.layout)
        
    def update_rect(self, *args): 
        self.rectangle.pos = self.pos 
        self.rectangle.size = self.size 
    
    def life_plus (self, instance): 
        if life['hearts'] < 9: 
            life['hearts'] += 1
        else: 
            life['hearts'] = life['hearts'] 
        self.lifelines.text = 'Lifelines: 0' + str(life['hearts'])
        lives = sm.get_screen('game').life_indicator
        lives.text = 'Lifelines: 0' + str(life['hearts'])
        
    def life_minus (self, instance): 
        if life['hearts'] > 1: 
            life['hearts'] -=1
        else: 
            life['hearts'] = life['hearts']
        self.lifelines.text = 'Lifelines: 0' + str(life['hearts'])
        game_life = sm.get_screen('game').life_indicator
        game_life.text = 'Lives left: 0' + str(life['hearts'])
            
    def difficulty_up (self, instance): 
        self.difficulty +=1
        if self.difficulty >2: 
            self.difficulty= 0 
        elif self.difficulty < 0: 
            self.difficulty = 2
        self.diff_lvl.text = difficulty[self.difficulty]
        difficulty['choice'] = self.difficulty
    
    def difficulty_down (self, instance): 
        self.difficulty -=1
        if self.difficulty >2: 
            self.difficulty= 0 
        elif self.difficulty < 0: 
            self.difficulty = 2
        self.diff_lvl.text = difficulty[self.difficulty]
        difficulty['choice'] = self.difficulty
    
    def change_to_game(self, instance):
        game = sm.get_screen('game')
        game.heartlayout = FloatLayout()
        for i in range(life['hearts']):
            game.hearts = HeartButtons(text = '',pos =(30+ 70*i,500))
            game.heartlayout.add_widget(game.hearts)
        game.add_widget(game.heartlayout)
        game_diff_lvl = sm.get_screen('game').diff_lvl
        game_diff_lvl.text = 'Level: ' + difficulty[difficulty['choice']]
        #access the Main widget Screen Manager
        self.manager.transition.direction = 'left' 
        # modify the current screen to a different "name"
        self.manager.current = 'game'
Factory.register('HoverBehavior', HoverBehavior)

if __name__ == '__main__':
    from kivy.uix.floatlayout import FloatLayout
    from kivy.lang import Builder
    from kivy.uix.label import Label
    from kivy.base import runTouchApp

    class HoverLabel(Label, HoverBehavior):
        def on_enter(self, *args):
            print("You are in, through this point", self.border_point)

        def on_leave(self, *args):
            print("You left through this point", self.border_point)

    Builder.load_string('''
<HoverLabel>:
    text: "inside" if self.hovered else "outside"
    pos: 200,200
    size_hint: None, None
    size: 100, 30
    canvas.before:
        Color:
            rgb: 1,0,0
        Rectangle:
            size: self.size
            pos: self.pos
    ''')
    fl = FloatLayout()
    fl.add_widget(HoverLabel())
runTouchApp(fl)
Beispiel #46
0
    def __init__(self, **kwargs):
        super(Detail, self).__init__(**kwargs)  # detail superclass
        grid_layout = GridLayout(cols=2)

        self.mainMenu = kwargs['main']

        self.plant = None

        # left side
        left_layout = FloatLayout()

        # background colour
        left_layout.canvas.add(brown_color)
        left_layout.canvas.add(
            Rectangle(pos=(0, 0),
                      size=(screen_width / 2, screen_height),
                      orientation='horizontal'))

        # plant image
        plant_size = 0.6
        self.plant_image = Image(source="",
                                 size_hint=(plant_size, plant_size),
                                 pos_hint={
                                     'x': (1 - plant_size) / 2,
                                     'y': (1 - plant_size) / 2
                                 })
        left_layout.add_widget(self.plant_image)

        left_layout.add_widget(
            Button(text="Back",
                   on_press=self.back,
                   background_color=brown_button_background,
                   size_hint=(1, .05),
                   pos_hint={
                       'x': 0,
                       'y': 0.95
                   }))

        # plant name and owner labels
        self.plant_name_label = Label(
            text="[b][size=18][color=#5C4940]Name: Plant[/color][/size][/b]",
            markup=True,
            size_hint=(1, 0.1),
            pos_hint={
                'x': 0,
                'y': 0.05
            })
        self.owner_name_label = Label(
            text=
            "[b][size=18][color=#5C4940]Owned By: Person[/color][/size][/b]",
            markup=True,
            size_hint=(1, 0.1),
            pos_hint={
                'x': 0,
                'y': 0
            })
        left_layout.add_widget(self.plant_name_label)
        left_layout.add_widget(self.owner_name_label)

        # right side
        right_layout = FloatLayout()

        # background colour
        right_layout.canvas.add(Color(1, 1, 1))
        right_layout.canvas.add(
            Rectangle(pos=(screen_width / 2, 0),
                      size=(screen_width / 2, screen_height),
                      orientation='horizontal'))

        # Water and fertilizer buttons
        btn_size = .3
        btn_gap = 0.05

        self.water_btn = ImageButton(source="Graphics/water_btn.png",
                                     size_hint=(btn_size, btn_size),
                                     pos_hint={
                                         'x': 0.5 - btn_gap / 2 - btn_size,
                                         'y': 0.2
                                     },
                                     on_press=self.water)
        self.fertilizer_btn = ImageButton(source="Graphics/fertilizer_btn.png",
                                          size_hint=(btn_size, btn_size),
                                          pos_hint={
                                              'x': 0.5 + btn_gap / 2,
                                              'y': 0.2
                                          },
                                          on_press=self.fertilize)

        right_layout.add_widget(self.water_btn)
        right_layout.add_widget(self.fertilizer_btn)

        progress_start_y = 0.8
        progress_bar_height = 0.1

        # temperature bar
        right_layout.add_widget(
            ImageButton(source="Graphics/light_icon.png",
                        size_hint=(0.1, progress_bar_height),
                        pos_hint={
                            'x': 0.2,
                            'y': progress_start_y
                        }))
        self.temperature_bar = ProgressBar(max=100,
                                           size_hint=(0.3,
                                                      progress_bar_height),
                                           pos_hint={
                                               'x': 0.5,
                                               'y': progress_start_y
                                           })
        right_layout.add_widget(self.temperature_bar)

        # water bar
        right_layout.add_widget(
            ImageButton(source="Graphics/water_icon.png",
                        markup=True,
                        size_hint=(0.1, progress_bar_height),
                        pos_hint={
                            'x': 0.2,
                            'y': progress_start_y - progress_bar_height
                        }))
        self.water_bar = ProgressBar(max=100,
                                     size_hint=(0.3, progress_bar_height),
                                     pos_hint={
                                         'x':
                                         0.5,
                                         'y':
                                         progress_start_y - progress_bar_height
                                     })
        right_layout.add_widget(self.water_bar)

        # fertilizer bar
        right_layout.add_widget(
            ImageButton(source="Graphics/fertilizer_icon.png",
                        markup=True,
                        size_hint=(0.1, progress_bar_height),
                        pos_hint={
                            'x': 0.2,
                            'y': progress_start_y - 2 * progress_bar_height
                        }))
        self.fertilizer_bar = ProgressBar(max=100,
                                          size_hint=(0.3, progress_bar_height),
                                          pos_hint={
                                              'x':
                                              0.5,
                                              'y':
                                              progress_start_y -
                                              2 * progress_bar_height
                                          })
        right_layout.add_widget(self.fertilizer_bar)

        # delete button
        right_layout.add_widget(
            ImageButton(source="Graphics/delete.png",
                        on_press=self.remove_plant,
                        markup=True,
                        size_hint=(0.25, progress_bar_height),
                        pos_hint={
                            'x': 0.5 - 0.25 / 2,
                            'y': 0.05
                        }))

        grid_layout.add_widget(left_layout)
        grid_layout.add_widget(right_layout)
        self.add_widget(grid_layout)
from kivy import kivy_data_dir
from kivy.core.window import Window
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scatter import Scatter
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.config import Config
from kivy.base import runTouchApp
from os.path import join, splitext, basename

chineseFont = join(kivy_data_dir, 'fonts/mingliuhk.ttf')

if __name__ == '__main__':

    root = FloatLayout()

    # create a button to release everything
    def release_all_keyboard(*l):
        Window.release_all_keyboards()

    btn = Button(text='Release\nall\nkeyboards',
                 size_hint=(None, None),
                 halign='center')
    btn.bind(on_release=release_all_keyboard)
    root.add_widget(btn)

    # show current configuration
    lbl = 'Configuration keyboard_mode is %r, keyboard_layout is %r' % (
        Config.get('kivy',
                   'keyboard_mode'), Config.get('kivy', 'keyboard_layout'))
Beispiel #48
0
class SpaceGame(App):
    def close_keyboard(self):
        self._keyboard.unbind(
            on_key_down = self.key_down,
            on_key_up = self.key_up
            ) 

    def key_down(self, keyboard, keycode, text, modifiers):
            key = keycode[1]
            print 'down', key
            if key in self.keymap:
                self.controls[self.keymap[key]] = 1
                self.player.update_controls(self.controls)

    def key_up(self, keyboard, keycode):
            key = keycode[1]
            print 'up', key
            if key in self.keymap:
                self.controls[self.keymap[key]] = 0
                self.player.update_controls(self.controls)

    def update_game(self, delta_time):
        for obj in self.objects.values():
            obj.update(delta_time, self.player)
            for other_obj in self.objects.values():
                if other_obj == obj: continue
                obj.test_collision(other_obj) 
        self.starfield.scroll(self.player.loc.x, self.player.loc.y, 0)
        self.health.value = self.player.health
        
    def add_obj(self, obj, index=0):
        self.objects[obj.id] = obj
        self.hud.add_widget(obj.image, index=index)

    def remove_obj(self, obj):
        if obj.id in self.objects:
            del self.objects[obj.id]
            self.hud.remove_widget(obj.image) 

    def build(self):
        self.keyboard = Window.request_keyboard(self.close_keyboard, self)
        self.keyboard.bind(on_key_down = self.key_down)
        self.keyboard.bind(on_key_up = self.key_up)
        self.image_map = {
            'player': 'images/player.png',
            'planet': 'images/planet.png',
            'bullet': 'images/Buggy.png', 
        }
        self.keymap = {
            'w': 'thrust',
            'a': 'turn_left',
            'd': 'turn_right',
            'spacebar': 'attack', 
        }
        self.controls = {} 
        self.layout = FloatLayout()
        self.starfield = Starfield()
        self.layout.add_widget(self.starfield) 
        self.hud = FloatLayout(size_hint=(1,1))
        self.layout.add_widget(self.hud) 
        health_label = Label(
            text='Health',
            pos_hint={
                'top':1.4,
                'center_x':0.5
            }
        )
        self.hud.add_widget(health_label)
        self.health = ProgressBar(
           pos_hint={
                'top': 1,
               'center_x': 0.5
            },
            size_hint=(0.5, 0.1),
            max = 100,
            value = 50
        ) 

        self.hud.add_widget(self.health)
        self.objects = {}
        planet = self.add_obj(Planet(game_obj=self,source=self.image_map['planet'])) 
        self.player = Player(self)
        self.add_obj(self.player) 
        Clock.schedule_interval(self.update_game, 1.0 / FPS) 
        return self.layout
Beispiel #49
0
    def __init__(self, **kwargs):

        app_log.info("started")

        data_label = [None] * 12

        self._touch_down_x = 0
        self._touch_down_y = 0

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

        layout = FloatLayout(size=(800, 600))

        #Set up the screen labels - create them, setting the font, colour, position and size from the database.
        for label_loop in range(1, 12):
            label_values = main_application.db.get_value(
                "label" + str(label_loop)).split("^")
            data_label[label_loop] = DataLabel(id=str(label_loop),
                                               font_size=label_values[0],
                                               pos_hint={
                                                   'x': float(label_values[1]),
                                                   'y': float(label_values[2])
                                               })
            data_label[label_loop].color = [
                float(label_values[3]),
                float(label_values[4]),
                float(label_values[5]),
                float(label_values[6])
            ]
            Clock.schedule_interval(data_label[label_loop].update,
                                    float(label_values[7]))

        #depending on whether 12 or 24 hour clock, position the colon accordingly - come back to this..
        if main_application.db.get_value("timestyle") == "12":
            colon_label = DataLabel(id="35",
                                    font_size='96pt',
                                    pos_hint={
                                        'x': -0.32,
                                        'y': 0.15
                                    })
        else:
            colon_label = DataLabel(id="35",
                                    font_size='96pt',
                                    pos_hint={
                                        'x': -0.28,
                                        'y': 0.15
                                    })

        colon_label.color = [1.0, 1.0, 0.0, 1.0]
        Clock.schedule_interval(colon_label.update, 0.1)

        #Find how many buttons we have and create and position them
        main_application.button_count = 0
        for btn_loop in range(0, 8):
            str_btn_loop = str(btn_loop)
            if len(
                    main_application.db.get_value("button" + str_btn_loop +
                                                  "alias")) > 0:
                main_application.button_count = main_application.button_count + 1
            else:
                break

        button_position = round(1.00 / main_application.button_count, 2)
        button_size = button_position - 0.01

        for btn_loop in range(0, main_application.button_count):
            str_btn_loop = str(btn_loop)
            alias = main_application.db.get_value("button" + str_btn_loop +
                                                  "alias")
            button_type = main_application.db.get_value("button" +
                                                        str_btn_loop + "type")
            if len(alias) > 0:
                if button_type == "button":
                    main_application.settings_buttons[btn_loop] = MyButton(
                        id=str_btn_loop,
                        text=alias,
                        size_hint=(button_size, 0.1),
                        pos_hint={
                            'x': 0.01 + (btn_loop * button_position),
                            'y': 0.02
                        })
                else:
                    main_application.settings_buttons[
                        btn_loop] = MyToggleButton(
                            id=str_btn_loop,
                            text=alias,
                            size_hint=(button_size, 0.1),
                            pos_hint={
                                'x': 0.01 + (btn_loop * button_position),
                                'y': 0.02
                            })

                main_application.settings_buttons[btn_loop].bind(
                    on_press=main_application.settings_buttons[btn_loop].
                    callback)
                layout.add_widget(main_application.settings_buttons[btn_loop])
            else:
                break

        #Images
        pir_image = PIRImage(source='Pictures//pir.jpg',
                             pos_hint={
                                 'x': -0.42,
                                 'y': 0.38
                             })
        Clock.schedule_interval(pir_image.update, 0.1)

        indicator_image = IndicatorImage(pos_hint={'x': 0.42, 'y': 0.38})
        Clock.schedule_interval(indicator_image.update, 1)

        Clock.schedule_interval(main_application.automation1, 0.5)

        for x in range(1, 12):
            layout.add_widget(data_label[x])

        layout.add_widget(colon_label)
        layout.add_widget(pir_image)
        layout.add_widget(indicator_image)

        self.add_widget(layout)
Beispiel #50
0
 def build(self):
     self.fl = FloatLayout()
     self.btn=Button(text="simulate Touch", size_hint=[None, None], pos_hint={"center_x":0.5, "center_y":0.5})
     self.fl.add_widget(self.btn)
     return self.fl
Beispiel #51
0
 def f(self):
     return FloatLayout()
Beispiel #52
0
class StartupScreen(Screen):

    ##
    # Class Constructor: __init__
    # ---------------------------
    # This method is called during the creation of the StartupScreen object.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    ##
    def __init__(self, **kwargs):
        super(StartupScreen, self).__init__(**kwargs)
        with self.canvas:
            Color(DARK_CHARCOAL[0], DARK_CHARCOAL[1],  DARK_CHARCOAL[2], 1)
            self.rect=Rectangle()
        self.bind(pos=manager.update_rect, size=manager.update_rect)
        self.needs_config = False
        self.config_lines = []
        self.load_config_file()
        self.layout = FloatLayout(size_hint=(None,None),
                                  size=Window.size,
                                  pos_hint={'center_x':.5, 'center_y':.5})
        self.layout.add_widget(Label(text="Configuration",
                                     font_size=40,
                                     size_hint=(None,None),
                                     pos_hint={'center_x':.5, 'top':.98},
                                     color=(1,1,1,1)))
        self.layout.add_widget(Label(text="FreeRADIUS IP",
                                     font_size=20,
                                     size_hint=(None,None),
                                     pos_hint={'center_x':.5, 'top':.88},
                                     color=(1,1,1,1)))
        self.ip_box = TextInput(text="localhost",
                                hint_text="IP Address",
                                     size_hint=(None, None),
                                     multiline=False,
                                     write_tab=False,
                                     size=(300, 30),
                                     pos_hint={'center_x':.5, 'top':.76})
        self.layout.add_widget(Label(text="Database Username",
                                     font_size=20,
                                     size_hint=(None,None),
                                     pos_hint={'center_x':.5, 'top':.73},
                                     color=(1,1,1,1)))
        self.db_user_box = TextInput(hint_text="Database Username",
                                     size_hint=(None, None),
                                     write_tab=False,
                                     multiline=False,
                                     size=(300, 30),
                                     pos_hint={'center_x':.5, 'top':.61})
        self.layout.add_widget(Label(text="Database Password",
                                     font_size=20,
                                     size_hint=(None,None),
                                     pos_hint={'center_x':.5, 'top':.58},
                                     color=(1,1,1,1)))
        self.db_passwd_box = TextInput(hint_text="Database Password",
                                     size_hint=(None, None),
                                     multiline=False,
                                     size=(300, 30),
                                     write_tab=False,
                                     password=True,
                                     pos_hint={'center_x':.5, 'top':.46})
        self.layout.add_widget(Label(text="Database Name",
                                     font_size=20,
                                     size_hint=(None,None),
                                     pos_hint={'center_x':.5, 'top':.43},
                                     color=(1,1,1,1)))
        self.db_name_box = TextInput(text="radius",
                                     hint_text="Database Name",
                                     size_hint=(None, None),
                                     multiline=False,
                                     size=(300, 30),
                                     write_tab=False,
                                     pos_hint={'center_x':.5, 'top':.31})
        self.layout.add_widget(HoverButton(text="Done",
                                    size_hint=(None, None),
                                    pos_hint={'center_x':.5, 'top':.2},
                                    size=(120, 40),
                                    on_press=self.finish_config,
                                    button_up=BTN_LCHRC[0],
                                    button_down= BTN_LCHRC[1]))
        self.err_label = Label(text="Please fill out all fields properly",
                                    font_size=11,
                                    size_hint=(None, None),
                                    color=(1,0,0,1),
                                    pos_hint={'center_x':.5, 'top':.15})
        self.layout.add_widget(self.db_name_box)
        self.layout.add_widget(self.ip_box)
        self.layout.add_widget(self.db_user_box)
        self.layout.add_widget(self.db_passwd_box)
        self.db_name_box.bind(on_text_validate=self.finish_config)
        self.ip_box.bind(on_text_validate=self.finish_config)
        self.db_user_box.bind(on_text_validate=self.finish_config)
        self.db_passwd_box.bind(on_text_validate=self.finish_config)
        self.add_widget(self.layout)


    ##
    # Class method: validate_fields
    # -----------------------------
    # This method validates whether all fields on the configuration screen have
    # been filled out.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    #
    # (bool) return                         True if fields pass basic check, False if not
    ##
    def validate_fields(self):
        if self.ip_box.text == '' or self.db_user_box.text == '' or \
           self.db_passwd_box.text == '' or self.db_name_box.text == '':
            return False
        elif not self.is_valid_ip():
            return False
        else:
            return True


    ##
    # Class method: ip_valid_ip
    # -------------------------
    # This method checks whether the ip address field on the startup screen has
    # been filled with a valid ip address.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    ##
    def is_valid_ip(self):
        if self.ip_box.text == 'localhost':
            return True
        octaves = self.ip_box.text.split('.')
        if len(octaves) != 4:
            return False
        try:
            for octave in octaves:
                value = int(octave)
                if value < 0 or value > 255:
                    return False
        except:
            return False
        return True


    ##
    # Class Method: finish_config
    # ---------------------------
    # This method finishes the configuration process. Checks whether all fields are valid,
    # writing config and switching to login page if fields are valid and displaying an
    # error label if fields not valid.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    # (HoverButton) instance                Button pressed to finish config
    ##
    def finish_config(self, instance):
        if self.validate_fields():
            self.populate_manager_variables()
            self.write_config_file()
            manager.populate_database_variables()
            if manager.menu.should_initialize():
                manager.menu.initialize_menus()
            if database.attempt_connect_database():
                manager.sm.current = 'login'
            else:
                manager.sm.current = 'error'
        else:
            if self.err_label not in self.layout.children:
                self.layout.add_widget(self.err_label)


    ##
    # Class Method: populate_manager_variables
    # ----------------------------------------
    # This method fills out variables stored in the manager module with values entered
    # on the startup screen.
    # 
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    ##
    def populate_manager_variables(self):
        manager.ip_addr = self.ip_box.text
        manager.db_user = self.db_user_box.text
        manager.db_password = self.db_passwd_box.text
        manager.db_name = self.db_name_box.text


    ##
    # Class Method: write_config_file
    # -------------------------------
    # This method takes the values entered on the configuration screen, and writes
    # them to a config text file.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    ##
    def write_config_file(self):
        #Generates random 8 char string
        def key_gen():
            key = ""
            for i in range(8):
                ch = random.randint(33,126)
                key += chr(ch)
            return key

        #Pads text with whitepace until it its length is multiple of 8
        def pad(text):
            while len(text) % 8 != 0:
                text += ' '
            return text

        key = key_gen()
        des = DES.new(key.encode('ascii'), DES.MODE_ECB)
        config_file = open('config.bin', 'w')
        
        config_file.write(key + '\n')
        config_file.write(des.encrypt(pad(manager.ip_addr).encode('ascii')).hex() + "\n")
        config_file.write(des.encrypt(pad(manager.db_user).encode('ascii')).hex() + "\n")
        config_file.write(des.encrypt(pad(manager.db_password).encode('ascii')).hex() + "\n")
        config_file.write(des.encrypt(pad(manager.db_name).encode('ascii')).hex() + "\n")
        config_file.write(des.encrypt(pad(manager.admin_pw).encode('ascii')).hex() )
        config_file.close()
        



    
    ##
    # Class Method: load_config_files
    # -------------------------------
    # This method reads the config text file and loads its values into the
    # startup screen class.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    ##
    def load_config_file(self):
        config_file = open("config.bin")
        content = config_file.read()
        if not content:
            self.needs_config = True
            return
        self.config_lines = content.splitlines()
        key = self.config_lines[0]
        des = DES.new(key.encode('ascii'), DES.MODE_ECB)
        
        for i in range(1,len(self.config_lines)):
            self.config_lines[i] = des.decrypt(bytes.fromhex(self.config_lines[i].strip())).decode('ascii').strip()
        
        manager.ip_addr = self.config_lines[1]
        manager.db_user = self.config_lines[2]
        manager.db_password = self.config_lines[3]
        manager.db_name = self.config_lines[4]
        manager.admin_pw = self.config_lines[5]
        config_file.close()
    

    ##
    # Class Method: should_launch_startup
    # -----------------------------------
    # This functionchecks whether FRAG has already been configured, and returns whether
    # the startup screen should be launched.
    #
    # @params
    # (StartupScreen) self                  This instance of StartupScreen
    ##
    def should_launch_startup(self):
        return self.needs_config
    def build(self, **kwargs):
        Window.clearcolor = (1, 1, 1, 1)
        self.title = "Xfinity Wifi Connector"
        self.icon = "imgs/appIcon.png"
        layout = FloatLayout()
        # super(LoginScreen, self).__init__(**kwargs)


        layout.add_widget(MyLabel(text='Adapters: ', pos_hint={'x':x, 'y':y}))

        #Create adapters button
        adapterDropDown = DropDown(max_height=300,do_scroll_x=True)
        adapterButton = Button(text='Choose Adapter',  size_hint=(buttonWidth,.05),pos_hint={'x':x+xAdd, 'y':y})
        for adapter in adapters:
            btn = Button(text=adapter.hardwareName, size_hint_y=None, height=44)
            btnMap[btn]=adapter
            scaleButton(btn)
            btn.bind(on_release=lambda btn: adapterDropDown.select([btn,adapterButton]))

            # Add the button inside the dropdown
            adapterDropDown.add_widget(btn)



        adapterButton.bind(on_release=adapterDropDown.open)

        # Listen for the selection in the dropdown list and
        adapterDropDown.bind(on_select=onSelectInterface)

        downArrow  = Image(source='imgs/down-arrow2.png',pos_hint={'x':x+xAdd+buttonWidth-.04, 'y':y},size_hint=(.05,.05))
        # adapterButton.add_widget(downArrow)
        layout.add_widget(adapterButton)
        layout.add_widget(downArrow)

        # Networks button
        layout.add_widget(MyLabel(text='Networks: ', pos_hint={'x':x, 'y':y+yAdd}))
        networkButton.bind(on_release=networks.open)
        networks.bind(on_select=onSelectNetwork)



        downArrow  = Image(source='imgs/down-arrow2.png',pos_hint={'x':x+xAdd+buttonWidth-.04, 'y':y+yAdd},size_hint=(.05,.05))

        layout.add_widget(networkButton)
        layout.add_widget(downArrow)

        layout.add_widget(MyLabel(text='Refresh Rate: ', pos_hint={'x':x, 'y':y+yAdd*2}))

        timeLabel = MyLabel(text='57 mins', pos_hint={'x':x+xAdd+buttonWidth, 'y':y+yAdd*2})

        st = Slider(min=10, max=70, value=57, size_hint=(buttonWidth,.05),pos_hint={'x':x+xAdd, 'y':y+yAdd*2},step=1)
        def OnSliderValueChange(instance,value):
            timeLabel.text = str(value)+" mins"

        st.bind(value=OnSliderValueChange)

        layout.add_widget(timeLabel)
        layout.add_widget(st)

        l = MyLabel(text='Time Till Next Refresh:', pos_hint={'x':x, 'y':y+yAdd*3})
        layout.add_widget(l)

        l = MyLabel(text = "00:00:00",pos_hint={'x':x+xAdd+.045, 'y':y+yAdd*4.25},font_size='25sp',size_hint=(buttonWidth,.05))
        refreshCountDown= SimpleCountDownTimer(l,10*60)
        layout.add_widget(l)

        l = MyLabel(text='Time On Connection:', pos_hint={'x':x, 'y':y+yAdd*5})

        layout.add_widget(l)

        l = MyLabel(text = "00:00:00",pos_hint={'x':x+xAdd+.045, 'y':y+yAdd*6.20},font_size='25sp',size_hint=(buttonWidth,.05))
        connectionTimer = SimpleCountUpTimer(l)
        layout.add_widget(l)



        img = Image(source='imgs/tex.png',pos_hint={'x':x+xAdd*3.5, 'y':y-.57}, size_hint=(.65,.65), allow_stretch=True)
        layout.add_widget(img)
        # commandStream = ScrollView()

        programOutput.update_status("Waiting to be turned on!")
        programOutput.update_status("Please pick adapter and network!")
        layout.add_widget(programOutput)

        #add xfinity logo   pos_hint={'x':x+xAdd*4.5, 'y':y-.5},size_hint=(.45,.4),color = (1,0,0,1),valign="middle",font_size='15sp'
        xfinityImage = Image(source='imgs/xfinity-logo.png',pos_hint={'x':x+xAdd*5.5, 'y':y-.8},size_hint=(.25,.25))
        layout.add_widget(xfinityImage)


        global isInternet
        def holdValue(instance, value):
            global isInternet
            if(not isInternet):
                instance.state = 'normal'
            else:
                instance.state = 'down'


        internet_connected = ToggleButton(text = 'Status: Internet Connected', state='normal',pos_hint={'x':x+xAdd*5, 'y':y-.825},size_hint=(.35,.07), color = (0,1,0,1),font_size='20sp')

        global isInternet
        isInternet = is_internet()
        if(isInternet):
            internet_connected.state = 'down'
            internet_connected.text = 'Status: Internet Connected'
            internet_connected.color = (0,1,0,1)
        else:
            internet_connected.state = 'normal'
            internet_connected.text = 'Status: No Internet'
            internet_connected.color = (1,0,0,1)

        internet_connected.bind(state=holdValue)
        layout.add_widget(internet_connected)

        global isOn

        switch = ToggleButton(text = 'Off', state='normal', pos_hint={'x':x+buttonWidth*.35, 'y':y+yAdd*8},size_hint=(.25,.1), color = (1,0,0,1))

        threadSafeList = MyList() #Updates from network reset thread
        global thState
        thState = None
        def cb(dt):
            global lasttimeZ
            global countertimeZ
            global isInternet
            global thState
            if isOn:
                connectionTimer.update()
                refreshCountDown.update()
                if refreshCountDown.left() < 0 and( thState==None or not thState.locked()):
                    thState =callback(switch, 'down', True)
            while len(threadSafeList) > 0:
                programOutput.update_status(threadSafeList.pop())
            countertimeZ += dt

            # Update Internet Label
            if(countertimeZ > lasttimeZ + 20.0):
                print "Tick tock"
                # global isInternet
                isInternet = is_internet()
                if(isInternet):
                    internet_connected.state = 'down'
                    internet_connected.text = 'Status: Internet Connected'
                    internet_connected.color = (0,1,0,1)
                else:
                    internet_connected.state = 'normal'
                    internet_connected.text = 'Status: No Internet'
                    internet_connected.color = (1,0,0,1)
                lasttimeZ = countertimeZ


        Clock.schedule_interval(cb, .5)

        #create worker thread (resets connection)
        #create thread safe list
        # On/Off Button
        def callback(instance, value,auto=False):
            global isOn
            if(adapterSelected is not None and networkSelected is not None):
                if(value == 'down'):
                    instance.text="On"
                    instance.color=(0,1,0,1)
                    programOutput.update_status("")
                    programOutput.update_status("Network resetting")
                    resetNetwork(adapterSelected,networkSelected,threadSafeList)
                    refreshCountDown.setTimeLeft(st.value*60)
                    connectionTimer.reset()
                    isOn = True
                else:
                    instance.text = "Off"
                    instance.color=(1,0,0,1)
                    isOn = False
                    programOutput.update_status("Stopping timers! Network will not be automatically reset")
            elif value == 'down':
                programOutput.update_status("Please select adapter and corresponding network!")
                instance.state = 'normal'


        switch.bind(state=callback)
        layout.add_widget(switch)


        s = Screen(name='Xfinity Wifi Connector')
        s.add_widget(layout)
        sm = ScreenManager()
        sm.add_widget(s)

        return sm
Beispiel #54
0
    def finalize(self, *args):
        """Add my tabs"""
        if not self.canvas:
            Clock.schedule_once(self.finalize, 0)
            return

        deck_builder_kwargs = {
            'pos_hint': {
                'x': 0,
                'y': 0
            },
            'starting_pos_hint': {
                'x': 0.05,
                'top': 0.95
            },
            'card_size_hint': (0.3, 0.4),
            'card_hint_step': (0, -0.1),
            'deck_x_hint_step': 0.4
        }

        self._tabs = TabbedPanel(size=self.size,
                                 pos=self.pos,
                                 do_default_tab=False)
        self.bind(size=self._tabs.setter('size'), pos=self._tabs.setter('pos'))
        self.add_widget(self._tabs)

        for functyp in 'trigger', 'prereq', 'action':
            tab = TabbedPanelItem(text=functyp.capitalize())
            setattr(self, '_{}_tab'.format(functyp), tab)
            self._tabs.add_widget(getattr(self, '_{}_tab'.format(functyp)))
            builder = DeckBuilderView(**deck_builder_kwargs)
            setattr(self, '_{}_builder'.format(functyp), builder)
            builder.bind(
                decks=getattr(self, '_trigger_push_{}s'.format(functyp)))
            scroll_left = DeckBuilderScrollBar(size_hint_x=0.01,
                                               pos_hint={
                                                   'x': 0,
                                                   'y': 0
                                               },
                                               deckbuilder=builder,
                                               deckidx=0,
                                               scroll_min=0)
            setattr(self, '_scroll_left_' + functyp, scroll_left)
            scroll_right = DeckBuilderScrollBar(size_hint_x=0.01,
                                                pos_hint={
                                                    'right': 1,
                                                    'y': 0
                                                },
                                                deckbuilder=builder,
                                                deckidx=1,
                                                scroll_min=0)
            setattr(self, '_scroll_right_' + functyp, scroll_right)
            layout = FloatLayout()
            setattr(self, '_{}_layout'.format(functyp), layout)
            tab.add_widget(layout)
            layout.add_widget(builder)
            layout.add_widget(scroll_left)
            layout.add_widget(scroll_right)
            layout.add_widget(
                Label(text='Used',
                      pos_hint={
                          'center_x': 0.1,
                          'center_y': 0.98
                      },
                      size_hint=(None, None)))
            layout.add_widget(
                Label(text='Unused',
                      pos_hint={
                          'center_x': 0.5,
                          'center_y': 0.98
                      },
                      size_hint=(None, None)))
            self.bind(rule=getattr(self, '_trigger_pull_{}s'.format(functyp)))
class Container(FloatLayout):
    slider_val = NumericProperty(25)

    # layout
    def __init__(self, *args, **kwargs):
        super(Container, self).__init__(*args, **kwargs)
        Window.clearcolor = (1, 1, 1, 1)
        Window.color = (0, 0, 0, 1)
        Window.size=(800, 400)
        font_color = (0, 0, 0, 1)
        self.size=(300, 50)

        self.txt1 = TextInput(text='',
                              multiline=False,
                              size_hint=(.5, .07),
                              pos_hint={'x': .3, 'y': .7})

        self.openpopupbtn = Button(text='Select',
                                   size_hint=(.1, .07),
                                   pos_hint={'x': .8, 'y': .7})

        self.filechs = FileChooserIconView(filters=['*.docx'],
                                           path='~',
                                           size_hint=(.8, .7),
                                           pos_hint={'x': .1, 'y': .3})

        self.popupcontent = FloatLayout()
        self.popupcontent.add_widget(self.filechs)

        self.popup = Popup(title='Select file',
                           content=self.popupcontent,
                           size_hint=(.8, .8))

        self.openpopupbtn.bind(on_press=self.popup.open)

        self.closepopupbtn = Button(text='Select',
                                    size_hint=(.8, .1),
                                    pos_hint={'x': .1, 'y': .1})
        self.closepopupbtn.bind(on_press=self.selectfile)

        self.popupcontent.add_widget(self.closepopupbtn)

        self.add_widget(Label(text="Original file name:",
                                size_hint=(.4, .05),
                                pos_hint={'x': .0, 'y': .7},
                                color=font_color))
        self.add_widget(self.txt1)
        self.add_widget(self.openpopupbtn)

        self.slider = Slider(min=1,
                             max=40,
                             value=25,
                             step=1,
                             size_hint=(.5, .05),
                             pos_hint={'x': .3, 'y': .5})
        self.slider.bind(value=self.on_value)

        self.lblslider = Label(text="25",
                               size_hint=(.3, .05),
                               pos_hint={'x':.7, 'y':.5},
                               color=font_color)

        self.add_widget(Label(text="Number of output files:",
                                size_hint=(.4, .05),
                                pos_hint={'x': .0, 'y': .5},
                                color=font_color))
        self.add_widget(self.slider)
        self.add_widget(self.lblslider)

        btn1 = Button(text="Create!",
                      size_hint=(1, .15),
                      pos_hint={'x':.0, 'y':.2})
        btn1.bind(on_press=self.buttonClicked)

        self.lbl1 = Label(text="",
                          size_hint=(1, .05),
                          pos_hint={'x': .0, 'y': .1},
                          color=font_color)

        self.add_widget(self.lbl1)
        # layout.add_widget(self.txt2)

        self.add_widget(btn1)

    # button click function
    def buttonClicked(self, btn):
        filename = self.txt1.text
        size = int(self.slider.value)

        self.lbl1.text = "Creating {} files from {} original file.".format(size, filename)

        shuffler = FileSet(filename=filename, size=size)
        shuffler.shuffle()
        shuffler.save()

    def on_value(self, instance, value):
        print(value)
        self.lblslider.text = str(value)

    def selectfile(self, btn):
        self.txt1.text = os.path.join(self.filechs.path, self.filechs.selection[0])
        self.popup.dismiss()
Beispiel #56
0
 def __init__(self, **kwargs):
     super(StartupScreen, self).__init__(**kwargs)
     with self.canvas:
         Color(DARK_CHARCOAL[0], DARK_CHARCOAL[1],  DARK_CHARCOAL[2], 1)
         self.rect=Rectangle()
     self.bind(pos=manager.update_rect, size=manager.update_rect)
     self.needs_config = False
     self.config_lines = []
     self.load_config_file()
     self.layout = FloatLayout(size_hint=(None,None),
                               size=Window.size,
                               pos_hint={'center_x':.5, 'center_y':.5})
     self.layout.add_widget(Label(text="Configuration",
                                  font_size=40,
                                  size_hint=(None,None),
                                  pos_hint={'center_x':.5, 'top':.98},
                                  color=(1,1,1,1)))
     self.layout.add_widget(Label(text="FreeRADIUS IP",
                                  font_size=20,
                                  size_hint=(None,None),
                                  pos_hint={'center_x':.5, 'top':.88},
                                  color=(1,1,1,1)))
     self.ip_box = TextInput(text="localhost",
                             hint_text="IP Address",
                                  size_hint=(None, None),
                                  multiline=False,
                                  write_tab=False,
                                  size=(300, 30),
                                  pos_hint={'center_x':.5, 'top':.76})
     self.layout.add_widget(Label(text="Database Username",
                                  font_size=20,
                                  size_hint=(None,None),
                                  pos_hint={'center_x':.5, 'top':.73},
                                  color=(1,1,1,1)))
     self.db_user_box = TextInput(hint_text="Database Username",
                                  size_hint=(None, None),
                                  write_tab=False,
                                  multiline=False,
                                  size=(300, 30),
                                  pos_hint={'center_x':.5, 'top':.61})
     self.layout.add_widget(Label(text="Database Password",
                                  font_size=20,
                                  size_hint=(None,None),
                                  pos_hint={'center_x':.5, 'top':.58},
                                  color=(1,1,1,1)))
     self.db_passwd_box = TextInput(hint_text="Database Password",
                                  size_hint=(None, None),
                                  multiline=False,
                                  size=(300, 30),
                                  write_tab=False,
                                  password=True,
                                  pos_hint={'center_x':.5, 'top':.46})
     self.layout.add_widget(Label(text="Database Name",
                                  font_size=20,
                                  size_hint=(None,None),
                                  pos_hint={'center_x':.5, 'top':.43},
                                  color=(1,1,1,1)))
     self.db_name_box = TextInput(text="radius",
                                  hint_text="Database Name",
                                  size_hint=(None, None),
                                  multiline=False,
                                  size=(300, 30),
                                  write_tab=False,
                                  pos_hint={'center_x':.5, 'top':.31})
     self.layout.add_widget(HoverButton(text="Done",
                                 size_hint=(None, None),
                                 pos_hint={'center_x':.5, 'top':.2},
                                 size=(120, 40),
                                 on_press=self.finish_config,
                                 button_up=BTN_LCHRC[0],
                                 button_down= BTN_LCHRC[1]))
     self.err_label = Label(text="Please fill out all fields properly",
                                 font_size=11,
                                 size_hint=(None, None),
                                 color=(1,0,0,1),
                                 pos_hint={'center_x':.5, 'top':.15})
     self.layout.add_widget(self.db_name_box)
     self.layout.add_widget(self.ip_box)
     self.layout.add_widget(self.db_user_box)
     self.layout.add_widget(self.db_passwd_box)
     self.db_name_box.bind(on_text_validate=self.finish_config)
     self.ip_box.bind(on_text_validate=self.finish_config)
     self.db_user_box.bind(on_text_validate=self.finish_config)
     self.db_passwd_box.bind(on_text_validate=self.finish_config)
     self.add_widget(self.layout)
    def __init__(self, *args, **kwargs):
        super(Container, self).__init__(*args, **kwargs)
        Window.clearcolor = (1, 1, 1, 1)
        Window.color = (0, 0, 0, 1)
        Window.size=(800, 400)
        font_color = (0, 0, 0, 1)
        self.size=(300, 50)

        self.txt1 = TextInput(text='',
                              multiline=False,
                              size_hint=(.5, .07),
                              pos_hint={'x': .3, 'y': .7})

        self.openpopupbtn = Button(text='Select',
                                   size_hint=(.1, .07),
                                   pos_hint={'x': .8, 'y': .7})

        self.filechs = FileChooserIconView(filters=['*.docx'],
                                           path='~',
                                           size_hint=(.8, .7),
                                           pos_hint={'x': .1, 'y': .3})

        self.popupcontent = FloatLayout()
        self.popupcontent.add_widget(self.filechs)

        self.popup = Popup(title='Select file',
                           content=self.popupcontent,
                           size_hint=(.8, .8))

        self.openpopupbtn.bind(on_press=self.popup.open)

        self.closepopupbtn = Button(text='Select',
                                    size_hint=(.8, .1),
                                    pos_hint={'x': .1, 'y': .1})
        self.closepopupbtn.bind(on_press=self.selectfile)

        self.popupcontent.add_widget(self.closepopupbtn)

        self.add_widget(Label(text="Original file name:",
                                size_hint=(.4, .05),
                                pos_hint={'x': .0, 'y': .7},
                                color=font_color))
        self.add_widget(self.txt1)
        self.add_widget(self.openpopupbtn)

        self.slider = Slider(min=1,
                             max=40,
                             value=25,
                             step=1,
                             size_hint=(.5, .05),
                             pos_hint={'x': .3, 'y': .5})
        self.slider.bind(value=self.on_value)

        self.lblslider = Label(text="25",
                               size_hint=(.3, .05),
                               pos_hint={'x':.7, 'y':.5},
                               color=font_color)

        self.add_widget(Label(text="Number of output files:",
                                size_hint=(.4, .05),
                                pos_hint={'x': .0, 'y': .5},
                                color=font_color))
        self.add_widget(self.slider)
        self.add_widget(self.lblslider)

        btn1 = Button(text="Create!",
                      size_hint=(1, .15),
                      pos_hint={'x':.0, 'y':.2})
        btn1.bind(on_press=self.buttonClicked)

        self.lbl1 = Label(text="",
                          size_hint=(1, .05),
                          pos_hint={'x': .0, 'y': .1},
                          color=font_color)

        self.add_widget(self.lbl1)
        # layout.add_widget(self.txt2)

        self.add_widget(btn1)
Beispiel #58
0
class GameScreen(Screen):
    def __init__(self, game_session, **kwargs):
        super(GameScreen, self).__init__(**kwargs)
        self.time_label = None
        self.current_load_label = None
        self.load_plot = None
        self.locations = [(0.15, 0.15), (0.25, 0.15), (0.38, 0.15),
                          (0.5, 0.15), (0.62, 0.15), (0.73, 0.15)]
        self.layout = FloatLayout()
        self.game_session = game_session
        self.current_load_label = Label(
            text=str(self.game_session.current_load))

    def display(self):
        background = Image(source="images/background2.png")
        clinic = Image(source="images/clinic.png",
                       pos_hint={
                           'x': .15,
                           'y': -0.05
                       },
                       size_hint=(.7, .7))
        sun = Image(source="images/sun.png", size_hint=(.7, .7))
        sun.pos_hint = {
            'x': .15,
            'y': 0.3
        }

        self.layout.add_widget(background)
        self.layout.add_widget(clinic)
        self.layout.add_widget(sun)

        if self.game_session.level.battery > 0:
            battery = Image(source="images/battery.png",
                            size_hint=(.3, .38),
                            pos_hint={
                                'x': .1,
                                'y': .2
                            })
            self.layout.add_widget(battery)

        self.time_label = Label(text="00:00:00",
                                font_size='24dp',
                                pos_hint={
                                    'x': .4,
                                    'y': .01
                                },
                                size_hint=(.2, .1))
        self.layout.add_widget(self.time_label)

        back_button = Button(text="<< Menu",
                             font_size='18dp',
                             pos_hint={
                                 'x': .01,
                                 'y': 0.01
                             },
                             size_hint=(.15, .075),
                             on_press=self.callpopup)
        self.layout.add_widget(back_button)

        for i, appliance in enumerate(self.game_session.level.appliances):
            appliance.pos_hint = {
                'x': self.locations[i][0],
                'y': self.locations[i][1]
            }
            appliance.size_hint = (.12, .12)
            self.layout.add_widget(appliance)

        self.layout.add_widget(self.current_load_label)
        self.add_widget(self.layout)
        Clock.schedule_interval(self.update, 1)
        Clock.schedule_interval(self.add_drop, 1 / 20)
        Clock.schedule_interval(self.move_rain, 1 / 20)

    def add_drop(self, dt):
        drop = Drop()
        time = self.game_session.current_time()
        if self.game_session.level.rain[time[0]] > 0:
            self.game_session.rain.append(drop)
            self.layout.add_widget(drop)

    def move_rain(self, dt):
        for i, drop in enumerate(self.game_session.rain):
            drop.pos_hint = {
                'y': drop.pos_hint.get('y') - .01,
                'x': drop.pos_hint.get('x')
            }
            if drop.pos_hint.get('y') < 0:
                self.layout.remove_widget(drop)
                del self.game_session.rain[i]
                del drop

    def update(self, dt):
        current_time = self.game_session.current_time()
        current_supply = self.game_session.level.supply[current_time[0]]
        current_load = self.game_session.current_load
        balance = current_supply - current_load

        hour = ("0" + str(current_time[0]))[-2:]
        min = ("0" + str(current_time[1]))[-2:]
        sec = ("0" + str(current_time[2]))[-2:]

        self.time_label.text = "%s:%s:%s" % (hour, min, sec)
        self.game_session.time += (12 * 60) / self.game_session.duration
        self.game_session.set_current_load()
        self.current_load_label.text = str(self.game_session.current_load)

        rect_width = 5
        rect_height = 100
        full_height = 480
        space = 1

        with self.layout.canvas:
            # plot supply
            Color(0, 1, 0, 1.0, mode='rgba')
            Rectangle(pos=(self.game_session.iteration * (rect_width + space),
                           full_height - rect_height),
                      size=(rect_width,
                            self.game_session.level.supply[current_time[0]] /
                            rect_height))
            # plot load
            Color(0, 0, 1, 1.0, mode='rgba')
            Rectangle(pos=(self.game_session.iteration * (rect_width + space),
                           full_height - rect_height),
                      size=(rect_width,
                            self.game_session.current_load / rect_height))

            # plot overload (battery used)
            Color(1, 0, 1, 1.0, mode='rgba')
            if balance < 0:
                Rectangle(pos=(self.game_session.iteration *
                               (rect_width + space), full_height -
                               rect_height + current_load / rect_height),
                          size=(rect_width, balance / rect_height))
        self.game_session.iteration += 1

    def callpopup(self, event):
        MessageBox(self,
                   titleheader="Confirm",
                   message="Are sure you want to quit the game",
                   options={
                       "YES": "yes()",
                       "NO": "no()"
                   })

    def yes(self):
        self.game_session.level = None
        self.manager.current = 'welcome_screen'
        # Todo: Clock unschedule
        self.manager.remove_widget(self)

    def no(self):
        pass
Beispiel #59
0
    def __init__(self, **kwargs):
        super(ParameterScreen2, self).__init__(**kwargs)
        screen_layout = FloatLayout()
        names = [
            "małe piwo(5%, 330ml)", "duże piwo(5%, 500ml)",
            "kieliszek wina(12%, 150ml)", "mocny alkohol(40%, 50ml)"
        ]
        volumes = [330, 500, 150, 50]
        self.alcohols = []
        # wypite, w każdej podliście: 0 - procent, 1 - ilość
        self.drunk = [[5.0, 0], [5.0, 0], [12.0, 0], [40.0, 0]]
        self.time = 0.0

        for i in range(len(names)):
            self.alcohols.append(Alcohol(names[i], volumes[i], i))
            screen_layout.add_widget(self.alcohols[i])

        self.another_label = Label(text="Inne:",
                                   size_hint=(.4, .1),
                                   pos_hint={
                                       'center_x': .2,
                                       'center_y': .53
                                   })
        self.another_percent = TextInput(text='',
                                         hint_text="Procent alkoholu",
                                         multiline=False,
                                         size_hint=(.2, .06),
                                         pos_hint={
                                             'center_x': .5,
                                             'center_y': .53
                                         })
        self.another_amount = TextInput(text='',
                                        hint_text="Ilość [ml]",
                                        multiline=False,
                                        size_hint=(.2, .06),
                                        pos_hint={
                                            'center_x': .7,
                                            'center_y': .53
                                        })

        self.time_label = Label(text="Czas spożywania alkoholu (w godzinach):",
                                size_hint=(.3, .1),
                                pos_hint={
                                    'center_x': .25,
                                    'center_y': .4
                                })
        self.time_value = Label(text=str(self.time),
                                size_hint=(.3, .1),
                                pos_hint={
                                    'center_x': .8,
                                    'center_y': .4
                                })
        self.time_minusbutton = Button(text="-",
                                       size_hint=(.05, .05),
                                       pos_hint={
                                           'center_x': .625,
                                           'center_y': .4
                                       })
        self.time_plusbutton = Button(text="+",
                                      size_hint=(.05, .05),
                                      pos_hint={
                                          'center_x': .675,
                                          'center_y': .4
                                      })
        self.time_plusbutton.bind(on_press=self.on_press_time_plusbutton)
        self.time_minusbutton.bind(on_press=self.on_press_time_minusbutton)

        screen_layout.add_widget(self.another_label)
        screen_layout.add_widget(self.another_percent)
        screen_layout.add_widget(self.another_amount)
        screen_layout.add_widget(self.time_label)
        screen_layout.add_widget(self.time_value)
        screen_layout.add_widget(self.time_plusbutton)
        screen_layout.add_widget(self.time_minusbutton)

        back_button = Button(text='Wróć',
                             size_hint=(.3, .1),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .2
                             })
        back_button.bind(on_press=self.on_press_backbutton)
        next_button = Button(text='Oblicz',
                             size_hint=(.3, .1),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .1
                             })
        next_button.bind(on_press=self.on_press_button)

        screen_layout.add_widget(back_button)
        screen_layout.add_widget(next_button)

        self.add_widget(screen_layout)
Beispiel #60
0
class TwistedServerApp(App):
    online_c = 0

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

        return root

    def setup_gui(self):

        self.layout = FloatLayout(size=(300, 300))
        self.online = Button(text="None", size_hint=(.06, .06), pos=(10, 100))
        self.textbox = TextInput(size_hint_y=.1, pos=(0, 0))
        self.textport = TextInput(hint_text="Enter port no",
                                  size_hint=(.18, .1),
                                  pos=(160, 200),
                                  focus=True,
                                  multiline=False,
                                  background_color=(0, 255, 255, 0.7),
                                  foreground_color=(255, 255, 255, 1),
                                  font_size=17)

        self.button = Button(text='Start Server By clicking Button',
                             size_hint=(.27, .2),
                             background_color=(0.5, 0.7, 1, 1),
                             pos=(360, 180))
        #self.button = Button(text='Start Server',size_hint=(.5,.1))
        self.button.bind(on_press=self.start_server)

        self.label = Label(text="Server is currently down",
                           font_size="19dp",
                           size_hint=(.5, .5),
                           color=(0.9, 0.1, 0.1, 1),
                           pos=(190, 300))

        self.avail = Label(text="Available Clients",
                           size_hint=(.2, .2),
                           color=(0.1, 0.9, 0.1, 1),
                           font_size="19dp",
                           pos=(10, 480),
                           readonly=True,
                           background_color=(255, 255, 0, 0.6))
        self.cl_conn = TextInput(text="NONE ",
                                 size_hint=(.7, .1),
                                 foreground_color=(0.1, 0.1, 0.9, 1),
                                 pos=(160, 500))

        self.layout.add_widget(self.cl_conn)
        self.layout.add_widget(self.avail)
        self.layout.add_widget(self.label)
        self.layout.add_widget(self.button)
        #self.layout.add_widget(self.textbox)
        self.layout.add_widget(self.textport)
        return self.layout

    def start_server(self, touch):
        self.label.text = 'Server Started'
        self.button.text = 'Server Started'

        if ((self.textport.text).isdigit()):
            reactor.listenTCP(int(self.textport.text), EchoFactory(self))

            self.label.text = 'Server Started'
        else:
            self.label.text = 'Server Not Responding :( Enter valid port'
        return self.label

    def on_connection(self, connection):
        self.print_message("New Client")

    def handle_message(self, msg):

        opr = msg.split("$#")[0]
        msg = msg.split("$#")[1]
        print msg
        #self.label.text  = "received:  %s\n" % msg
        self.label.text = "received: Event\n"
        splitmsg = msg.split(":")[0]
        #curos = splitmsg.split("@")[1]
        curos = platform.system()
        if (opr.isdigit()):
            if (int(opr) == 2):
                self.label.text = "received:  %s\n" % msg
                msg = msg.split(": ")[1]
        root_dirname = "Hellosnp"
        if (int(opr) == 2):
            if (curos == 'Linux'):
                output = subprocess.Popen(
                    ["find", "/home/", "-name", msg + "*"],
                    stdout=subprocess.PIPE).communicate()[0]
                msg = opr + "$#" + output
            if (curos == 'Windows'):
                #os.chdir('C:\\Users\\Varun Malhotra\\Desktop\\')

                output = subprocess.Popen(
                    ["dir", "/s", "/a", "/b", msg + "*"],
                    shell=True,
                    stdout=subprocess.PIPE).communicate()[0]
                msg = opr + "$#" + output
                #print msg
        if (int(opr) == 4):
            msg = opr + "$#" + msg
        if (int(opr) == 5):
            msg = opr + "$#" + str(self.cl_conn.text)
        if (int(opr) == 8):
            msg = opr + "$#" + "lol"
            self.label.text = "received:  %s\n" % msg
        return msg

    def client_conn(self, conn_info):
        self.cl_conn.text = ""
        #y=20
        #on=0

        for t in conn_info:
            #self.onlines = self.onlines + on
            #self.onlines = Button(text="yes",size_hint=(.06,.06),pos=(10,400-y))
            #self.layout.add_widget(self.onlines)
            self.cl_conn.text = self.cl_conn.text + str(t) + " , "
            #y=y+40
            #on=on+1
        #global online_c
        #online_c = on
        if (self.cl_conn.text == ""):
            self.cl_conn.text = "None Available"

        return self.layout