Exemple #1
0
class MyBigImage(FloatLayout):
    def __init__(self, **kwargs):
        super(MyBigImage, self).__init__(**kwargs)
	self.addImage("bluerose.png")

    def addImage(self, filename):
        self.button = Button()
        self.button.background_normal=filename
        self.button.background_down=filename
	self.button.size_hint = None, None
	self.button.border = [0,0,0,0]
	self.button.width = 140
	self.button.height = 140
	self.button.pos = 400, 450
	self.add_widget(self.button)
	self.button.bind(on_press=self.clicked)

    def clicked(self, button):
	#animate = Animation(pos=(400, 0), t='in_bounce')
	#animate = Animation(pos=(400, 0), t='in_elastic')
	animate1 = Animation(pos=(400, 0), t='in_elastic', duration=5)
	animate2 = Animation(pos=(400, 450), t='in_elastic', duration=5)
	a = animate1 + animate2
	a.start(button)
	print "ok"
Exemple #2
0
    def __init__(self, **kwargs):
        super(WelcomeScreen, self).__init__(**kwargs)
        self.layout = FloatLayout()
        background = Image(source="images/background2.png")
        self.layout.add_widget(background)
        welcome_label = Label(text="Energy Game",
                            font_size='48dp',
                            pos_hint={'x': .4, 'y': .8},
                            size_hint=(.2, .1))
        self.layout.add_widget(welcome_label)
        duration_label = Label(text="Duration (Min)",
                              font_size='16dp',
                              pos_hint={'x': .34, 'y': .64},
                              size_hint=(.2, .1))
        self.layout.add_widget(duration_label)
        self.duration = TextInput(text="10", pos_hint={'x': .52, 'y': .65}, size_hint=(.1, .07))
        self.layout.add_widget(self.duration)
        for i, level in enumerate(WelcomeScreen.json_levels):
            level_button = Button(text=level['name'],
                          font_size='18dp',
                          pos_hint={'x': .375, 'y': 0.55 - (i * 0.076)},
                          size_hint=(.25, .075))
            level_button.bind(on_press=self.changer)
            self.layout.add_widget(level_button)

        self.add_widget(self.layout)
Exemple #3
0
  def init(self, bShow):
    self.bShow = bShow
    
    if not bShow:
      return
      
    # toggle btn
    self.btn_layout = BoxLayout(orientation='horizontal', size=(W, self.btn_height), pos=(0, H-self.btn_height))
    self.add_widget(self.btn_layout)
    self.fps = Button(text="Toggle", size_hint_x=1.5)
    self.fps.bind(on_release = self.toggleDebug)
    self.fps.name = "FPS"
    self.btn_layout.add_widget(self.fps)
    
    self.btn_update = Button(text="Show Update", size_hint_x=3)
    self.btn_update.bind(on_release=self.toggleShowUpdate)
    self.btn_layout.add_widget(self.btn_update)
    
    self.btn_clear = Button(text="Clear log", size_hint_x=2)
    self.btn_clear.bind(on_release = self.clearPrint)
    self.btn_layout.add_widget(self.btn_clear)
    
    self.btn_python = Button(text="Run Python", size_hint_x=3)
    self.btn_python.bind(on_release=self.togglePython)
    self.btn_layout.add_widget(self.btn_python)
    
    # label
    self.debugLabel = TextInput(text="", halign='left', valign='top', readonly=True, use_bubble=False, use_handles=False,
      allow_copy=False, multiline=True, background_color=(1,1,1,0), foreground_color=(1,1,1,1), size_hint_y=None)
    self.debugLabel.size = (W, 0)
    self.debugLabel.pos=(0,0)
    self.debugLabel.name = "Print output"
    self.add_widget(self.debugLabel)

    self.toggleDebug()
    def paradigm_start_screen(self):
        
        #add background color and text
        #with self.canvas.before:
        #    Color(1,1,0,0.5)
        #    self.bg_start =  Rectangle(pos=(Window.width*0.1,  Window.height*0.2),
        #            size=(Window.width*0.8, Window.height*0.4))
        #    self.txt_start = Label(text="Press start to start paradigm", color = (1,0.7,0,0.7), pos=(Window.width*0.1,  Window.height*0.3),
        #            size=(Window.width*0.8, Window.height*0.4), font_size = 48)
        #    #somehow below is required or the first buttons do not expand
        #    w = Label(text='')

        #make new float layer
        self.layout_start =FloatLayout()
        self.layout_start.width = Window.width*0.7
        self.layout_start.height = Window.height*0.7
        self.layout_start.x = Window.height*0.3
        self.layout_start.y = Window.width*0.1
        self.add_widget(self.layout_start)

        #add button to layer
        paradigm_start_button = Button(text='Start',   size_hint=(.2, .2),
                pos_hint={'x':.28, 'y':.2})
        paradigm_start_button.bind(on_press= self.clear_start_screen)
        self.layout_start.add_widget(paradigm_start_button)

        #add text to layer
        self.txt_start = Label(text="Press start to start paradigm", color = (1,0.7,0,0.7), pos=(Window.width*0.14,  Window.height*0.3),
                    size=(Window.width*0.8, Window.height*0.4), font_size = 48)
        self.layout_start.add_widget(self.txt_start)
Exemple #5
0
	def render_distribuite(self,tab):
		self.dist_layout = GridLayout(cols=2)
		self.Blayout=BoxLayout(orientation='vertical')
		self.Blayout.size_hint=( 1, 1)
		btnDistr=Button(text='Start Distribuite',size_hint=(1, .1))
		btnDistr.bind(on_press=self.start_dist)
		self.btnReckivy=ToggleButton(text='Choose recipes for Kivy Launcher',size_hint=(1, .1))
		self.btnReckivy.bind(on_release=self.select_kivy_rec)

		self.recipe_layout = GridLayout(cols=4)
		thedir=os.path.join(self.py4a_path,'recipes')
		recipes=[ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
		for r in recipes:
			t=ToggleButton(text=r)
			t.bind(state=self.add_remove)
			self.recipe_layout.add_widget(t)
		self.Blayout.add_widget(btnDistr)
		self.Blayout.add_widget(self.btnReckivy)
		self.Blayout.add_widget(self.recipe_layout)




		self.dist_layout.add_widget(self.Blayout)
		self.dist_layout.add_widget(self.kvc)


		tab.add_widget(self.dist_layout)
	def result(self,instance):
		odd_words = ["</br>","<br>","<div>","</div>","<i>","</i>"]
		song_artist = str(self.song_artist_input.text).replace(" ","")
		song_title = str(self.song_title_input.text).replace(" ","")
		# print (sa,st)
		url = 'http://www.azlyrics.com/lyrics/' + str(song_artist) +'/' + str(song_title) + '.html'

		#this error handling is important here becuase erros like Http 404 error can occur when the user enters non-existing
		# artist and song title and that will make your app not function well.Its always good to check for errors
		# even if it passes all tests.

		try:
			soup = BeautifulSoup(urllib2.urlopen(url).read(), "html.parser")
			raw_lyrics_html = soup.find_all("div")
			lyrics = (str(raw_lyrics_html[22]))
			
			#this for loop will replace all html tags in the odd_word varaible with empty string.
			for word in odd_words:
				lyrics = lyrics.replace(str(word),"")

			intro ="This lyrics is brought to you by 'azlyrics.com' Enjoy"
			
			self.song_result = TextInput(text = intro + "\n" + lyrics, multiline = True, height = 70, size_hint = (1, 1))
			self.layout.add_widget(self.song_result)
			self.clearResult =Button(text = "Clear Lyrics",size_hint = (1, 0.2))
			self.clearResult.bind(on_press = self.removeWidget)
			self.layout.add_widget(self.clearResult)

		except Exception:
			self.song_result = TextInput(text = "There was no result for your search.\nPlease check spelling",\
						     multiline = True,height = 70,size_hint = (1, 1))
			self.layout.add_widget(self.song_result)
			self.clearResult = Button(text = "Clear Lyrics",size_hint = (1, 0.2))
			self.clearResult.bind(on_press = self.removeWidget)
			self.layout.add_widget(self.clearResult)
Exemple #7
0
    def do_email(self, popup, address, filename, widget):
        thread = SenderThread(address, filename)
        thread.daemon = True
        thread.start()
        popup.dismiss()

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

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

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

        Window.release_all_keyboards()
        self.reset_email_textinput()
        popup.open()
Exemple #8
0
    def build(self):
        self.wid = wid = Widget()
        maskBotRight = shapely.geometry.Polygon([[0,0], [300, 0], [300,300], [Window.width, 300], [Window.width, Window.height], [0, Window.height]])
        maskBotLeft = shapely.geometry.Polygon([[Window.width, Window.height], [0, Window.height], [0, 300], [300, 300], [300, 0], [Window.width, 0]])
        maskTopRight = shapely.geometry.Polygon([[0,0], [0, Window.height], [300, Window.height], [300, 300], [Window.width, 300], [Window.width, 0]])
        maskTopLeft = shapely.geometry.Polygon([[Window.width, 0], [Window.width, Window.height], [300, Window.height], [300, 300], [0, 300], [0, 0]])
        with wid.canvas:
            self.mesh = self.build_mesh(maskBotRight)
            self.mesh.mode = "triangle_fan"
            self.mesh2 = self.build_mesh(maskTopLeft)
            self.mesh2.mode = "triangle_fan"
            self.mesh3 = self.build_mesh(maskBotLeft)
            self.mesh3.mode = "triangle_fan"
            self.mesh4 = self.build_mesh(maskTopRight)
            self.mesh4.mode = "triangle_fan"

        layout = BoxLayout(size_hint=(1, None), height=50)
        for mode in ('points', 'line_strip', 'line_loop', 'lines',
                'triangle_strip', 'triangle_fan'):
            button = Button(text=mode)
            button.bind(on_release=partial(self.change_mode, mode))
            layout.add_widget(button)

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

        return root
Exemple #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
Exemple #10
0
  def show_install_form(self):
    self.orientation = 'vertical'
    self.spacing='10sp'

    headerLayout = BoxLayout(orientation='horizontal')
    headerLabelsLayout = BoxLayout(orientation='vertical')

    headerLabelsLayout.add_widget(Label(text='Proyecto TiX', font_size=24))

    headerLabelsLayout.add_widget(Label(text='Iniciar sesion', font_size=18))

    headerLayout.add_widget(headerLabelsLayout)
    headerLayout.add_widget(Image(source='./images/LogoTiX.png'))
    self.add_widget(headerLayout)

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

        scroll.add_widget(grid)
        boxl.add_widget(scroll)
        boxl.add_widget(button_back)
        color.add_widget(boxl)
        self.add_widget(color)
Exemple #12
0
	def makeHeaderLayout(self):
		layout = self.HeaderLayout
		layout.clear_widgets()

		self.btnP = Button(text="Update", size_hint_x=None, width = self.factor*125)
		self.btnP.bind(on_press = buttonUpdate)
		layout.add_widget(self.btnP)

		btnSep = Button(text="", size_hint_x=None, width = self.factor*50)
		layout.add_widget(btnSep)

		self.btnLi = ToggleButton(text="List", group='menu', size_hint_x=None, width = self.factor*125, state='down')
		self.btnLi.bind(on_press = buttonList)
		layout.add_widget(self.btnLi)

		self.btnV = ToggleButton(text="VM Launcher", group='menu', size_hint_x=None, width = self.factor*125)
		self.btnV.bind(on_press = buttonVM)
		layout.add_widget(self.btnV)

		self.btnSta = ToggleButton(text="Statistics", group='menu', size_hint_x=None, width = self.factor*125)
		self.btnSta.bind(on_press = buttonStatistics)
		layout.add_widget(self.btnSta)

		self.btnL = ToggleButton(text="Log", group='menu', size_hint_x=None, width = self.factor*125)
		self.btnL.bind(on_press = buttonLog)
		layout.add_widget(self.btnL)

		self.btnS = Button(text="Settings", size_hint_x=None, width = self.factor*125)
		self.btnS.bind(on_press = buttonSettings)
		layout.add_widget(self.btnS)
          def build(self):

                # create a floating layout as base
                camlayout = FloatLayout(size=(600, 600))
                cam = Camera()        #Get the camera
                cam=Camera(resolution=(1024,1024), size=(300,300))
                cam.play=True         #Start the camera
                camlayout.add_widget(cam)

                button=Button(text='Take Picture',size_hint=(0.12,0.12))
                button.bind(on_press=self.doscreenshot)
                camlayout.add_widget(button)    #Add button to Camera Layout

                # create a text input box for site name
                s1 = Scatter(size_hint=(None, None), pos_hint={'x':.01, 'y':.9})
                self.site = TextInput(size_hint=(None, None), size=(150, 50), multiline=False)

                # create a text input box for sample (flag) name
                s2 = Scatter(size_hint=(None, None), pos_hint={'x':.01, 'y':.8})
                self.sample = TextInput(size_hint=(None, None), size=(150, 50), multiline=False)

                # add the text widgets to the window
                s1.add_widget(self.site)
                camlayout.add_widget(s1) 
                s2.add_widget(self.sample)
                camlayout.add_widget(s2) 

                return camlayout
Exemple #14
0
	def build(self):
		# Set up the layout:
		layout = GridLayout(cols=5, spacing=30, padding=30, row_default_height=150)

		# Make the background gray:
		with layout.canvas.before:
			Color(.2,.2,.2,1)
			self.rect = Rectangle(size=(800,600), pos=layout.pos)

		# Instantiate the first UI object (the GPIO input indicator):
		inputDisplay = InputButton(text="Input")

		# Schedule the update of the state of the GPIO input button:
		Clock.schedule_interval(inputDisplay.update, 1.0/10.0)

		# Create the rest of the UI objects (and bind them to callbacks, if necessary):
		outputControl = ToggleButton(text="LED")
		outputControl.bind(on_press=press_callback)
		beepButton = Button(text="BEEP!")
		beepButton.bind(on_press=press_callback)
		wimg = Image(source='logo.png')
		speedSlider = Slider(orientation='vertical', min=1, max=30, value=speed)
		speedSlider.bind(on_touch_down=update_speed, on_touch_move=update_speed)

		# Add the UI elements to the layout:
		layout.add_widget(wimg)
		layout.add_widget(inputDisplay)
		layout.add_widget(outputControl)
		layout.add_widget(beepButton)
		layout.add_widget(speedSlider)

		# Start flashing the LED
		Clock.schedule_once(flash, 1.0/speed)

		return layout
Exemple #15
0
        def viewGames(self):
            sview = ScrollView(size_hint=(.9, .8), pos_hint={'center_x':.5, 'center_y':.5})
            layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
            # Make sure the height is such that there is something to scroll.
            layout.bind(minimum_height=layout.setter('height'))
            # Run sql query to get all available games
            availableGames = retrieve("SELECT * FROM Games")
            
            if availableGames == "":
                popup = Popup(title='No Games', content=Label(text='There are currently no available games'), size_hint=(None, None), size=(400, 100))
                popup.open()
            elif availableGames == 0:
                popup = Popup(title='Connection', content=Label(text='Could not connect to the database'), size_hint=(None, None), size=(400, 100))
                popup.open()
            else:
                for tpl in availableGames:
                    uid, name, location, creator, status = tpl
                    print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n"
                    print name
                    print "\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n"
                    btn = Button(id=name, text=name, size_hint_y=None, height=200)
                    btn.bind(on_press=self.seeInfo)
                    layout.add_widget(btn)

            sview.add_widget(layout)
            self.add_widget(sview)
Exemple #16
0
    def ansresult(self, instance):
        # invokes by pressing button Answer

        # stops all clock shedules
        Clock.unschedule(self.time_label.update)
        Clock.unschedule(self.timeend)

        # checks whether user gave right answer
        # and invokes window with answering result
        for i in self.togglebuttonlist:
            if i.text == self.states[self.guess_state]:
                i.background_color = (0, 1, 0, 1)
                if i.state == "down":
                    self.score += 1
                    if self.score % 10 == 0:
                        self.level += 1
                    text = "Congratulations! Your score is %d" % (self.score)

                    btnaction = self.nextround
                else:
                    text = "You lost!"
                    btnaction = self.gameover

        content = Button(text=text)
        self.answerresult = Popup(title="", content=content,
                                  size_hint=(.8, .5), auto_dismiss=False)
        content.bind(on_press=btnaction)
        self.answerresult.open()
Exemple #17
0
 def __init__(self, app, *args, **kwargs):
     super(ScreenNine, self).__init__(*args, **kwargs)
     self.app = app
     self.win_popup = WinPopup(app, "You have played all the stages", "Taking you to menu screen", "menu")
     self.lose_popup = LosePopup(app, "Sorry you lost the game", "Try again", "nine")
     self.box_size = [Window.size[0] / 16., Window.size[1] / 10.]
     self.init_physics()
     self.keyboard = Window.request_keyboard(self.keyboard_closed, self, 'text')
     self.keyboard.bind(on_key_down=self.on_keyboard_down)
     self.keyboard.bind(on_key_up=self.on_keyboard_up)
     Clock.schedule_interval(self.step, 1/FRAMES)
     #Adding the lines
     for i in xrange(16):
         with self.canvas:
             Color(0, 0, 0, 0.3)
             Line(points=[self.box_size[0]*i, 0, self.box_size[0]*i, Window.size[1]], width=0.3)
     for i in xrange(10):
         with self.canvas:
             Line(points=[0, self.box_size[1]*i, Window.size[0], self.box_size[1]*i], width=0.3)
     #Adding back and forward buttons
     back_button = Button(text="<", pos=[Window.size[0]*0.025, Window.size[1]*0.925], size_hint = [0.05, 0.05])
     back_button.bind(on_press=self.back_btn_pressed)
     #forward_button = Button(text=">", pos=[Window.size[0]*0.925, Window.size[1]*0.925], size_hint = [0.05, 0.05])
     #forward_button.bind(on_press=self.forward_btn_pressed)
     self.add_widget(back_button)
    def load_main_window(self):

        self.atual_menu = 0
        op_n = 1
        main_options = [APPERTIZERS_NAME, MEAT_NAME, FISH_NAME, VEGAN_NAME, DRINKS_NAME, DESSERT_NAME]

        self.a_articles.clear_widgets()

        for op in main_options:
            button = Button(text=op)
            button.bind(on_press=self.open_new_menu)
            op_n = op_n + 1
            self.a_articles.add_widget(button)

        for a in range(op_n-1, 9):
            self.a_articles.add_widget(Label(text=''))

        self.bt_next.enabled = False
        self.bt_previous.enabled = False

        if self.pos_system.get_buy_list() is None:
            self.bt_newlist.enabled = True
            self.bt_clearlist.enabled = False
            self.bt_finishlist.enabled = False

        self.menu_page = 0
    def open_new_menu(self, instance):
        op_n = 1
        total_rows = 0
        menu_type = ''
        if instance != self.bt_next and instance != self.bt_previous:
            menu_type = instance.text.lower()

        cursor = self.database.load_articles(menu_type, self.menu_page)

        self.a_articles.clear_widgets()

        for row in cursor:
            total_rows = total_rows + 1
            if total_rows > 9:
                break
            button = Button(text=row[1])
            button.bind(on_press=self.add_to_buy_list)
            button.item = Item(id_p=row[0], name=row[1], price=row[2], tax=0.2)
            op_n = op_n + 1
            self.a_articles.add_widget(button)

        for a in range(op_n-1, 9):
            self.a_articles.add_widget(Label(text=''))

        self.bt_next.enabled = (total_rows > 9)
        self.bt_previous.enabled = (self.menu_page > 0)
    def build(self):
        obj = self.object
        widget = KivyNoteMap()
        #widget.build(obj.currentMelodyRating.getInNote(), obj.currentMelodyRating.getKnownNote())
        widget.build(obj.getInNote(), obj.getKnownNote())

        btn = Button(text="id:" + str(id(obj)))
        widget.add_widget(btn)

        def callback(instance):
            myglobals.ScreenState.mystate.selectedobject = self.object


        btn.bind(on_press=callback)

        #widget.add_widget(widget.orgchord)
        #widget.add_widget(widget.chord)
        #widget.error.text=str(len(widget.errors))
        #widget.add_widget(widget.error)
        #widget.add_widget(TextInput(text="id:" + str(id(obj))))
        widget.add_widget(Label(text="lenlist " + str(obj.lenlist)))

        #widget.add_widget(Label(text= obj.getKnownChordInNoteMap().prettyprint()))
        widget.add_widget(Label(text=str(obj.EqValueState())))
        widget.add_widget(TextInput(text= obj.getKnownChordInNoteMap().prettyprint()))

        #atxt= str(self.challenge.seen.get(obj,None))
        atxt= str(obj.rcost)

        widget.add_widget(Label(text=atxt))

        widget.size_hint=(None,None)
        return widget
Exemple #21
0
    def Show(self,uTitle,uMessage,lMax):
        ''' Shows the Popup '''
        self.lMax           = lMax
        self.bCancel        = False
        oContent            = BoxLayout(orientation='vertical', spacing='5dp')
        iHeight=oORCA.iAppHeight*0.5
        if oORCA.uDeviceOrientation=="landscape":
            iHeight=oORCA.iAppHeight*0.9
        self.oPopup         = Popup(title=ReplaceVars(uTitle),content=oContent, size=(oORCA.iAppWidth*0.9,iHeight),size_hint=(None, None),auto_dismiss=False)
        self.oLabel         = label = Label(text=ReplaceVars(uMessage), text_size=(oORCA.iAppWidth*0.86, None), shorten=True,multiline=True, valign='top',halign='left')
        self.oProgressText  = Label(multiline=False, valign='top',halign='center',text_size=(oORCA.iAppWidth*0.86, None), shorten=True)
        oContent.add_widget(Widget())
        oContent.add_widget(label)
        oContent.add_widget(Widget())
        self.oProgressText.text=""

        self.oProgressBar      = ProgressBar(size_hint_y=None, height='50dp', spacing='5dp', max=lMax)
        oContent.add_widget(self.oProgressBar)
        oContent.add_widget(self.oProgressText)
        oContent.add_widget(SettingSpacer())
        oBtn            = Button(size_hint_y=None, height='50dp',text=ReplaceVars('$lvar(5009)'))
        oBtn.bind(on_release=self.OnCancel)
        oContent.add_widget(oBtn)
        self.oPopup.open()
        return self.oPopup
Exemple #22
0
    def hire_item(self):
        for name in self.dicAvail:
            if self.dicAvail[name] == "":

                temp_button = Button(text=name)
                temp_button.bind(on_release=self.press_entry_hire)
                self.root.ids.entriesBox.add_widget(temp_button)
Exemple #23
0
class MyApp(App):
    def build(self):
        self.modes = (
            '%I:%m:%S',
            '%H:%m:%S %P',
            '%S:',
        )
        self.mode = 0
        self.main_box = BoxLayout(orientation='vertical')

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

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

        return self.main_box

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

    def timer(self, dt):
        now = datetime.datetime.now()
        self.button.text = now.strftime(self.modes[self.mode])
        if self.mode == 2:
            self.button.text += str(now.microsecond)[:3]
Exemple #24
0
    def build(self):
        self.game_select = []
        self.games_index = {}
        self.index = [0]*game_pole
        self.game_end = 0
        self.game_buttons = []

        self.game_data = [[word for word in line.strip().split(',')] 
		 for line in open(game_data_path)]

        self.game_select = self.game_data[0][1:]
        self.root.ids.open_butt.text = text_choise + self.game_data[0][0]

        for idx, words in enumerate(self.game_data):
            word = words[0]
            self.games_index[word] = idx
            btn = Button(text = words[0],size_hint_y = None, height = '40dp')
            btn.bind(on_release=lambda btn:self.root.ids.drop.select(btn.text))
            self.root.ids.drop.add_widget(btn)

	for i in xrange(game_pole):
            btn = Factory.GameButton()
            btn.text = font_s + self.game_select[i].replace("\\n", "\n") + font_e
            btn.id = 'b' + str(i)
            self.game_buttons.append(btn)
            self.root.ids.nomad.add_widget(btn)

        self.update_button()
    def build(self):
        # create root widget
        root_widget = FloatLayout()
        box = BoxLayout(orientation='vertical',
                        size_hint=(None, None),
                        size=(400, 200),
                        spacing=dp(20),
                        padding=dp(20),
                        pos_hint={'center_x': .5, 'center_y':.5})

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

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

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

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

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

		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)
Exemple #27
0
 def create_entry_buttons(self):
     # creates a button for each new item entry being added
     for item in self.list_item.items:
         temp_button = Button(text=item.name)
         temp_button.bind(on_release=self.press_entry)
         # adds the button to "newItem" using add.widget
         self.root.ids.newItem.add_widget(temp_button)
Exemple #28
0
class GameOver(Popup):
  
  def __init__(self, root_widget, **kw):
    super(GameOver, self).__init__(**kw)
    self.root_widget = root_widget
    self.title = 'GAME OVER'
    self.layout = RelativeLayout()
    self.btn_new_game = Button(text='New Game', size_hint=(.5,.1), pos_hint={'center_x':.25, 'center_y': .05})
    self.btn_new_game.bind(on_press=self.new_game)
    self.btn_exit = Button(text='Exit', size_hint=(.5,.1), pos_hint={'center_x':.75, 'center_y': .05})
    self.btn_exit.bind(on_press=self.root_widget.close_app)
    self.lbl_score = Label(size_hint=(.5,.1), pos_hint={'center_x':.5, 'center_y': .4})
    self.lbl_high_score = Label(size_hint=(.5,.1), pos_hint={'center_x':.5, 'center_y': .7})
    self.layout.add_widget(self.lbl_score)
    self.layout.add_widget(self.lbl_high_score)
    self.layout.add_widget(self.btn_new_game)
    self.layout.add_widget(self.btn_exit)
    self.content = self.layout
    self.size_hint = (None, None)
    self.size = (400, 400)
        
  def set_score(self, score):
    high_score = load_data('data/score.txt')
    if score > high_score:
      high_score = score
      write_data('data/score.txt', score)
    self.lbl_score.text = 'Score: %s' % score
    self.lbl_high_score.text = 'High Score: %s' % high_score
  
  def new_game(self, *args):
    self.dismiss()
    self.root_widget.new_game()
Exemple #29
0
	def timesheet_pop(self):
		"""Popup to display the Timesheet"""

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

		con=lite.connect('TimeTracker.db')
		with con:
				cur=con.cursor()
				cur.execute("SELECT ID, TASK_DATE, TIME, TASK FROM Timesheet")
				rows = cur.fetchall()
				for row in rows:
				  tslabel.text=tslabel.text+"\n   "
				  tslabel.text+=str(row[0]).center(4)+"      "+str(row[1])
				  tslabel.text+="  "+str(row[2]).center(34)+"  "+str(row[3])
		if con:
				con.close()
Exemple #30
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
Exemple #31
0
class InteractiveMc(App):
    def __init__(self, mpf_path, machine_path, args, **kwargs):

        super().__init__(**kwargs)

        self.config_validator = ConfigValidator(self)
        self.mpf_config_processor = MpfConfigProcessor()
        files = [
            os.path.join(mpfmc.__path__[0],
                         'tools/interactive_mc/imcconfig.yaml')
        ]
        self.machine_config = self.mpf_config_processor.load_config_files_with_cache(
            files, "machine")
        self.machine_config['mpf'] = dict()
        self.machine_config['mpf']['allow_invalid_config_sections'] = True
        self.config = self.machine_config
        self._initialized = False
        self.options = dict(bcp=True)
        self.clock = ClockBase(self)

        # needed for bcp
        self.settings = Settings()
        self.machine_vars = {}
        self.modes = []

        self.events = EventManager(self)
        self.mode_controller = ModeController(self)
        self.bcp = Bcp(self)
        self.slide_player = MpfSlidePlayer(self)
        self.slide_player.instances['imc'] = dict()

        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_1"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_2"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_3"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_4"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_5"))

        self.sm = ScreenManager()
        self.slide_screen = Screen(name="Slide Player")
        self.widget_screen = Screen(name="Widget Player")
        self.sm.add_widget(self.slide_screen)
        self.sm.add_widget(self.widget_screen)
        self.slide_player_code = YamlCodeInput(lexer=YamlLexer(), tab_width=4)
        self.slide_player_code.bind(on_triple_tap=self.send_slide_to_mc)

        self.slide_player_code.text = '''my_test_slide:
    widgets:
      - type: text
        text: iMC
        color: red
      - type: line
        points: 1, 1, 1, 32, 128, 32, 128, 1, 1, 1
        color: lime
      - type: rectangle
        width: 50
        height: 20
        color: yellow
'''

        self.send_button = Button(text='Send',
                                  size=(150, 60),
                                  size_hint=(None, None),
                                  background_normal='',
                                  background_color=(0, .6, 0, 1),
                                  pos=(0, 1),
                                  pos_hint={
                                      'top': 0.1,
                                      'right': 0.95
                                  })

        self.send_button.bind(on_press=self.send_slide_to_mc)

        self.slide_screen.add_widget(self.slide_player_code)
        self.slide_screen.add_widget(self.send_button)

        self.slide_player.register_player_events(dict())

    def register_monitor(self, monitor_class, monitor):
        pass

    def build(self):
        return self.sm

    def send_slide_to_mc(self, value):
        del value

        try:
            settings = YamlInterface.process(self.slide_player_code.text)
        except Exception as e:
            msg = str(e).replace('"', '\n')
            Popup(title='Error in your config',
                  content=Label(text=msg, size=(750, 350)),
                  size_hint=(None, None),
                  size=(Window.width, 400)).open()
            return

        try:
            settings = (self.slide_player.validate_config_entry(
                settings, 'slides'))
        except Exception as e:
            msg = str(e).replace('"', '\n')
            Popup(title='Error in your config',
                  content=Label(text=msg, size=(750, 350)),
                  size_hint=(None, None),
                  size=(Window.width, 400)).open()
            return

        if self._initialized:
            self.slide_player.clear_context('imc')
        else:
            self._initialized = True
        self.slide_player.play(settings, 'imc', 100)
        self.clock.loop.run_until_complete(
            asyncio.sleep(.1, loop=self.clock.loop))

    def set_machine_var(self, name, value):
        pass
Exemple #32
0
    def show_property(self, instance, value, key=None, index=-1, *l):
        # normal call: (tree node, focus, )
        # nested call: (widget, prop value, prop key, index in dict/list)
        if not value:
            return

        content = None
        if key is None:
            # normal call
            nested = False
            widget = instance.widget
            key = instance.key
            prop = widget.property(key)
            value = getattr(widget, key)
        else:
            # nested call, we might edit subvalue
            nested = True
            widget = instance
            prop = None

        dtype = None
        if isinstance(prop, AliasProperty) or nested:
            # trying to resolve type dynamicly
            if type(value) in (str, str):
                dtype = 'string'
            elif type(value) in (int, float):
                dtype = 'numeric'
            elif type(value) in (tuple, list):
                dtype = 'list'

        if isinstance(prop, NumericProperty) or dtype == 'numeric':
            content = TextInput(text=str(value) or '', multiline=False)
            content.bind(
                text=partial(self.save_property_numeric, widget, key, index))
        elif isinstance(prop, StringProperty) or dtype == 'string':
            content = TextInput(text=value or '', multiline=True)
            content.bind(
                text=partial(self.save_property_text, widget, key, index))
        elif isinstance(prop, ListProperty) or isinstance(
                prop, ReferenceListProperty) or dtype == 'list':
            content = GridLayout(cols=1, size_hint_y=None)
            content.bind(minimum_height=content.setter('height'))
            for i, item in enumerate(value):
                button = Button(text=repr(item), size_hint_y=None, height=44)
                if isinstance(item, Widget):
                    button.bind(
                        on_release=partial(self.highlight_widget, item, False))
                else:
                    button.bind(on_release=partial(self.show_property, widget,
                                                   item, key, i))
                content.add_widget(button)
        elif isinstance(prop, OptionProperty):
            content = GridLayout(cols=1, size_hint_y=None)
            content.bind(minimum_height=content.setter('height'))
            for option in prop.options:
                button = ToggleButton(
                    text=option,
                    state='down' if option == value else 'normal',
                    group=repr(content.uid),
                    size_hint_y=None,
                    height=44)
                button.bind(
                    on_press=partial(self.save_property_option, widget, key))
                content.add_widget(button)
        elif isinstance(prop, ObjectProperty):
            if isinstance(value, Widget):
                content = Button(text=repr(value))
                content.bind(on_release=partial(self.highlight_widget, value))
            elif isinstance(value, Texture):
                content = Image(texture=value)
            else:
                content = Label(text=repr(value))

        elif isinstance(prop, BooleanProperty):
            state = 'down' if value else 'normal'
            content = ToggleButton(text=key, state=state)
            content.bind(on_release=partial(self.save_property_boolean, widget,
                                            key, index))

        self.content.clear_widgets()
        if content:
            self.content.add_widget(content)
 def build(self):
     # create a button, and  attach animate() method as a on_press handler
     button = Button(size_hint=(None, None),
                     text='plop',
                     on_press=self.animate)
     return button
Exemple #34
0
            # widget at the current size. Take the best side, and fit to
            # it.

            if h_top < h_bottom:
                self.top = self.height = wy
            else:
                self.y = wtop
                self.height = win.height - wtop


if __name__ == '__main__':
    from kivy.uix.button import Button
    from kivy.base import runTouchApp

    def show_dropdown(button, *largs):
        dp = DropDown()
        dp.bind(on_select=lambda instance, x: setattr(button, 'text', x))
        for i in range(10):
            item = Button(text='hello %d' % i, size_hint_y=None, height=44)
            item.bind(on_release=lambda btn: dp.select(btn.text))
            dp.add_widget(item)
        dp.open(button)

    def touch_move(instance, touch):
        instance.center = touch.pos

    btn = Button(text='SHOW', size_hint=(None, None), pos=(300, 200))
    btn.bind(on_release=show_dropdown, on_touch_move=touch_move)

    runTouchApp(btn)
    def header_choices(self, axis):
        """ Dynamically construct the next pop-up screen """
        self.cur_axis = axis

        #  This will hold all the other elements
        self.chooseAxisScreen = FloatLayout()

        #  Inside of the float layout, we'll have a grid layout
        self.headerButtons = GridLayout(cols=2,
                                        size_hint_y=0.7,
                                        size_hint_x=0.9,
                                        pos_hint={
                                            'x': 0.05,
                                            'top': 0.9
                                        })
        self.chooseAxisScreen.add_widget(self.headerButtons)

        #  and a label which appears when the user doesn't make a selection
        self.axis_missing = Label(color=(1.0, .27, 0.0, 1.0),
                                  pos_hint={
                                      'x': 0.15,
                                      'y': 0.01
                                  },
                                  size_hint_y=0.1,
                                  size_hint_x=0.5)
        self.chooseAxisScreen.add_widget(self.axis_missing)

        #  and a label which appears when the user selects a non-numeric
        #  axis
        self.non_numeric_axis = Label(color=(1.0, .27, 0.0, 1.0),
                                      pos_hint={
                                          'x': 0.15,
                                          'y': 0.01
                                      },
                                      size_hint_y=0.1,
                                      size_hint_x=0.5)
        self.chooseAxisScreen.add_widget(self.non_numeric_axis)

        #  and a label which explains why non-numeric y-axis values
        #  are disabled
        #  Note:  size_hint_y used to be 0.1
        self.y_axis_disabled_label = Label(
            color=(1.0, .27, 0.0, 1.0),
            pos_hint={
                'x': 0.15,
                'y': 0.001
            },
            size_hint_y=0.3,
            size_hint_x=0.5,
        )
        self.chooseAxisScreen.add_widget(self.y_axis_disabled_label)

        if self.non_numeric_x_axis:
            #  and a checkbox that the user may select if they want to
            #  count the occurrences of their x-axis
            self.count_x_checkbox = CheckBox(
                size_hint_y=0.1,
                size_hint_x=0.5,
                pos_hint={
                    'x': .0,
                    'y': 0.9
                },
            )
            self.chooseAxisScreen.add_widget(self.count_x_checkbox)
            self.count_x_checkbox.bind(active=self.record_count_checkbox)

            self.count_x_label = Label(
                pos_hint={
                    'x': 0.2,
                    'y': 0.9
                },
                text=('Count the occurrences of my x-axis '
                      '\n instead of using a y-axis'),
                size_hint_y=0.1,
                size_hint_x=0.5,
                color=(0.22, 0.67, 0.91, 1))
            self.chooseAxisScreen.add_widget(self.count_x_label)

        #  Set arguments for the Next button on_press
        if (axis == 'x'):
            self.data_needed = 'x'
            self.next_axis = 'y'
        elif (axis == 'y'):
            self.data_needed = 'y'
            self.next_axis = None

        #  and a "Next" button
        #  Thanks to https://stackoverflow.com/questions/12368390
        #  for help with the lambda
        #  Setting on_press is not passing a callback to the button,
        #  but actually executing the function.
        #  Passing in an unnamed lambda function will call the
        #  desired function when the on_press event is raised
        #  Thanks to https://stackoverflow.com/questions/16215045
        #  for help with the throw-away argument _
        nextButton = Button(
            text='Next',
            size_hint_y=0.15,
            size_hint_x=0.2,
            pos_hint={
                'x': 0.79,
                'y': 0.01
            },
            on_press=lambda _: self.ensureInput(self.data_needed, self.
                                                axis_missing, self.next_axis))
        self.chooseAxisScreen.add_widget(nextButton)

        #  We want to disable the buttons which represent non-numerical
        #  values, if the user is currently selecting the data to
        #  use for their y-axis.  This disables them and explains to
        #  the user why the buttons are disabled.
        with open(self.filename, 'rU+') as f:
            df = pd.read_csv(f, sep=self.delim, index_col=False)

        someButtonsDisabled = False
        for header in self.headers:
            btn = Button(text=header)
            if self.cur_axis == 'y':
                if df[header].dtype == 'object':
                    btn.disabled = True
                    someButtonsDisabled = True
            if someButtonsDisabled:
                self.y_axis_disabled_label.text = self.y_axis_disabled_explanation
            else:
                self.y_axis_disabled_label.text = ''
            btn.bind(on_press=self.assign_header)
            self.headerButtons.add_widget(btn)
        content = self.chooseAxisScreen
        title = 'Select your ' + self.cur_axis + '-axis'
        self.popup = Popup(content=content, title=title, size_hint=(1.0, 1.0))
        self.popup.open()
 def build(self):
     return Button(text='Hello World')
Exemple #37
0
    def __init__(self, mpf_path, machine_path, args, **kwargs):

        super().__init__(**kwargs)

        self.config_validator = ConfigValidator(self)
        self.mpf_config_processor = MpfConfigProcessor()
        files = [
            os.path.join(mpfmc.__path__[0],
                         'tools/interactive_mc/imcconfig.yaml')
        ]
        self.machine_config = self.mpf_config_processor.load_config_files_with_cache(
            files, "machine")
        self.machine_config['mpf'] = dict()
        self.machine_config['mpf']['allow_invalid_config_sections'] = True
        self.config = self.machine_config
        self._initialized = False
        self.options = dict(bcp=True)
        self.clock = ClockBase(self)

        # needed for bcp
        self.settings = Settings()
        self.machine_vars = {}
        self.modes = []

        self.events = EventManager(self)
        self.mode_controller = ModeController(self)
        self.bcp = Bcp(self)
        self.slide_player = MpfSlidePlayer(self)
        self.slide_player.instances['imc'] = dict()

        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_1"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_2"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_3"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_4"))
        self.events.process_event_queue()
        self.clock.loop.run_until_complete(
            self.events.post_queue_async("init_phase_5"))

        self.sm = ScreenManager()
        self.slide_screen = Screen(name="Slide Player")
        self.widget_screen = Screen(name="Widget Player")
        self.sm.add_widget(self.slide_screen)
        self.sm.add_widget(self.widget_screen)
        self.slide_player_code = YamlCodeInput(lexer=YamlLexer(), tab_width=4)
        self.slide_player_code.bind(on_triple_tap=self.send_slide_to_mc)

        self.slide_player_code.text = '''my_test_slide:
    widgets:
      - type: text
        text: iMC
        color: red
      - type: line
        points: 1, 1, 1, 32, 128, 32, 128, 1, 1, 1
        color: lime
      - type: rectangle
        width: 50
        height: 20
        color: yellow
'''

        self.send_button = Button(text='Send',
                                  size=(150, 60),
                                  size_hint=(None, None),
                                  background_normal='',
                                  background_color=(0, .6, 0, 1),
                                  pos=(0, 1),
                                  pos_hint={
                                      'top': 0.1,
                                      'right': 0.95
                                  })

        self.send_button.bind(on_press=self.send_slide_to_mc)

        self.slide_screen.add_widget(self.slide_player_code)
        self.slide_screen.add_widget(self.send_button)

        self.slide_player.register_player_events(dict())
Exemple #38
0
    def build(self):
        wid = Widget()

        label = Label(text='0')

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

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

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

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

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

        return root
Exemple #39
0
    def build(self, **kwargs):
        self.layout = FloatLayout(size=(300, 300))
        #        with self.layout.canvas:
        #            BorderImage(source='GUIBackground.png',size=(800,600))
        #            Line(points=[450,0,450,1000],width=2)
        #            Line(points=[450,296,800,296],width=2)

        self.readings = Label(text='Setpoints',
                              font_size=40,
                              size_hint=(0.24, 0.24),
                              pos_hint={
                                  'center_x': 0.21,
                                  'center_y': 0.9
                              })
        self.layout.add_widget(self.readings)

        self.TemperatureReading = Label(text='Temperature',
                                        background=[1, 1, 1, 1],
                                        font_size=17,
                                        pos_hint={
                                            'center_x': 0.08,
                                            'center_y': 0.83
                                        })
        self.layout.add_widget(self.TemperatureReading)
        self.ATemperatureReading = Label(text='24',
                                         background=[1, 1, 1, 1],
                                         font_size=22,
                                         pos_hint={
                                             'center_x': 0.08,
                                             'center_y': 0.78
                                         })
        self.layout.add_widget(self.ATemperatureReading)

        self.LightIntensity = Label(text='Light Intensity',
                                    background=[1, 1, 1, 1],
                                    font_size=17,
                                    pos_hint={
                                        'center_x': 0.22,
                                        'center_y': 0.83
                                    })
        self.layout.add_widget(self.LightIntensity)
        self.ALightIntensity = Label(text='300',
                                     background=[1, 1, 1, 1],
                                     font_size=22,
                                     pos_hint={
                                         'center_x': 0.22,
                                         'center_y': 0.78
                                     })
        self.layout.add_widget(self.ALightIntensity)

        self.Humidity = Label(text='Humidity',
                              background=[1, 1, 1, 1],
                              font_size=17,
                              pos_hint={
                                  'center_x': 0.36,
                                  'center_y': 0.83
                              })
        self.layout.add_widget(self.Humidity)
        self.AHumidity = Label(text='100',
                               background=[1, 1, 1, 1],
                               font_size=22,
                               pos_hint={
                                   'center_x': 0.36,
                                   'center_y': 0.78
                               })
        self.layout.add_widget(self.AHumidity)

        self.Moisture = Label(text='Moisture',
                              background=[1, 1, 1, 1],
                              font_size=17,
                              pos_hint={
                                  'center_x': 0.50,
                                  'center_y': 0.83
                              })
        self.layout.add_widget(self.Moisture)
        self.AMoisture = Label(text='15000',
                               background=[1, 1, 1, 1],
                               font_size=22,
                               pos_hint={
                                   'center_x': 0.50,
                                   'center_y': 0.78
                               })
        self.layout.add_widget(self.AMoisture)
        ####################
        self.setpoints = Label(text='Actual Readings',
                               font_size=40,
                               size_hint=(0.24, 0.24),
                               pos_hint={
                                   'center_x': 0.135,
                                   'center_y': 0.67
                               })
        self.layout.add_widget(self.setpoints)
        self.Plant = Image(source='flower3.jpg',
                           size_hint=(0.50, 0.50),
                           pos_hint={
                               'center_x': 0.782,
                               'center_y': 0.748
                           })
        self.layout.add_widget(self.Plant)

        self.LightIntensityL = Label(text='Light Intensity',
                                     background=[1, 1, 1, 1],
                                     font_size=17,
                                     pos_hint={
                                         'center_x': 0.1,
                                         'center_y': 0.6
                                     })
        self.layout.add_widget(self.LightIntensityL)
        self.LightIntensity = Slider(min=0,
                                     max=100,
                                     size_hint=(0.4, 0.10),
                                     disabled=True,
                                     pos_hint={
                                         'center_x': 0.25,
                                         'center_y': 0.55
                                     })
        self.layout.add_widget(self.LightIntensity)
        self.LightIntensityV = Label(text=str(self.LightIntensity.value),
                                     font_size=20,
                                     pos_hint={
                                         'center_x': 0.4,
                                         'center_y': 0.6
                                     })
        self.layout.add_widget(self.LightIntensityV)

        self.TemperatureL = Label(text='Temperature',
                                  background=[1, 1, 1, 1],
                                  font_size=17,
                                  pos_hint={
                                      'center_x': 0.095,
                                      'center_y': 0.45
                                  })
        self.layout.add_widget(self.TemperatureL)
        self.TemperatureSlider = Slider(min=0,
                                        max=100,
                                        size_hint=(0.4, 0.10),
                                        disabled=True,
                                        pos_hint={
                                            'center_x': 0.25,
                                            'center_y': 0.40
                                        })
        self.layout.add_widget(self.TemperatureSlider)
        self.TemperatureV = Label(text=str(self.TemperatureSlider.value),
                                  font_size=20,
                                  pos_hint={
                                      'center_x': 0.4,
                                      'center_y': 0.45
                                  })
        self.layout.add_widget(self.TemperatureV)

        self.HumidityL = Label(text='Humidity',
                               background=[1, 1, 1, 1],
                               font_size=17,
                               pos_hint={
                                   'center_x': 0.08,
                                   'center_y': 0.30
                               })
        self.layout.add_widget(self.HumidityL)
        self.HumiditySlider = Slider(min=0,
                                     max=100,
                                     size_hint=(0.4, 0.10),
                                     disabled=True,
                                     pos_hint={
                                         'center_x': 0.25,
                                         'center_y': 0.25
                                     })
        self.layout.add_widget(self.HumiditySlider)
        self.HumidityV = Label(text=str(self.HumiditySlider.value),
                               font_size=20,
                               pos_hint={
                                   'center_x': 0.4,
                                   'center_y': 0.30
                               })
        self.layout.add_widget(self.HumidityV)

        self.MoistureL = Label(text='Moisture',
                               background=[1, 1, 1, 1],
                               font_size=17,
                               pos_hint={
                                   'center_x': 0.08,
                                   'center_y': 0.15
                               })
        self.layout.add_widget(self.MoistureL)
        self.MoistureSlider = Slider(min=0,
                                     max=100,
                                     size_hint=(0.4, 0.10),
                                     disabled=True,
                                     pos_hint={
                                         'center_x': 0.25,
                                         'center_y': 0.10
                                     })
        self.layout.add_widget(self.MoistureSlider)
        self.MoistureV = Label(text=str(self.MoistureSlider.value),
                               font_size=20,
                               pos_hint={
                                   'center_x': 0.4,
                                   'center_y': 0.15
                               })
        self.layout.add_widget(self.MoistureV)

        Clock.schedule_once(self.PWMstart, 1.0)
        Clock.schedule_interval(self.h_t_sensor, 2.0)
        Clock.schedule_interval(self.l_sensor, 2.0)
        Clock.schedule_interval(self.sm_sensor, 2.0)

        self.inc_temp = Button(text='temp',
                               font_size=40,
                               size_hint=(0.222, 0.245),
                               pos_hint={
                                   'center_x': 0.675,
                                   'center_y': 0.365
                               },
                               on_press=Clock.schedule_interval(
                                   self.adjustT, 1.0))
        self.layout.add_widget(self.inc_temp)

        self.inc_moist = Button(text='moist',
                                font_size=40,
                                size_hint=(0.222, 0.245),
                                pos_hint={
                                    'center_x': 0.675,
                                    'center_y': 0.125
                                },
                                on_press=Clock.schedule_interval(
                                    self.adjustM, 1.0))
        self.layout.add_widget(self.inc_moist)

        self.light = Button(text='light',
                            font_size=40,
                            size_hint=(0.222, 0.245),
                            pos_hint={
                                'center_x': 0.89,
                                'center_y': 0.365
                            },
                            on_press=Clock.schedule_interval(
                                self.adjustL, 1.0))
        self.layout.add_widget(self.light)

        self.water = Button(text='water',
                            font_size=40,
                            size_hint=(0.222, 0.245),
                            pos_hint={
                                'center_x': 0.89,
                                'center_y': 0.125
                            },
                            on_press=Clock.schedule_interval(
                                self.adjustW, 1.0))
        self.layout.add_widget(self.water)

        self.goback = Button(text='<== Go Back',
                             font_size=10,
                             size_hint=(0.1, 0.05),
                             pos_hint={
                                 'center_x': 0.05,
                                 'center_y': 0.98
                             },
                             on_press=self.GoBack)
        self.layout.add_widget(self.goback)

        return self.layout
 def build(self):  # building the app
     parent = Game()
     parent.serve_car()
     Clock.schedule_interval(parent.update, 1.0 / 60.0)
     self.painter = MyPaintWidget()
     clearbtn = Button(text='clear')
     savebtn = Button(text='save', pos=(parent.width, 0))
     loadbtn = Button(text='load', pos=(2 * parent.width, 0))
     clearbtn.bind(on_release=self.clear_canvas)
     savebtn.bind(on_release=self.save)
     loadbtn.bind(on_release=self.load)
     parent.add_widget(self.painter)
     parent.add_widget(clearbtn)
     parent.add_widget(savebtn)
     parent.add_widget(loadbtn)
     return parent
Exemple #41
0
    def __init__(self, **kwargs):
        super(AI, self).__init__(**kwargs)
        self.training = False
        self.dotting = False

        self.ciph1 = ToggleButton(text='Caesar cipher',
                                  id='caesar',
                                  group='ciph',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .15,
                                      'center_y': .6
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.ciph2 = ToggleButton(text='Affine cipher',
                                  id='affine',
                                  group='ciph',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .15,
                                      'center_y': .5
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.ciph3 = ToggleButton(text='Evan\'s test',
                                  id='evan',
                                  group='ciph',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .15,
                                      'center_y': .4
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.add_widget(self.ciph1)
        self.add_widget(self.ciph2)
        self.add_widget(self.ciph3)

        self.len1 = ToggleButton(text='1 words',
                                 id='1',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .8
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len2 = ToggleButton(text='2 words',
                                 id='2',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .7
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len3 = ToggleButton(text='4 words',
                                 id='4',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .6
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len4 = ToggleButton(text='8 words',
                                 id='8',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .5
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len5 = ToggleButton(text='16 words',
                                 id='16',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .4
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len6 = ToggleButton(text='32 words',
                                 id='32',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .3
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len7 = ToggleButton(text='64 words',
                                 id='64',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .2
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.add_widget(self.len1)
        self.add_widget(self.len2)
        self.add_widget(self.len3)
        self.add_widget(self.len4)
        self.add_widget(self.len5)
        self.add_widget(self.len6)
        self.add_widget(self.len7)

        self.lang1 = ToggleButton(text='English',
                                  id='eng',
                                  group='lang',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .6
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.lang2 = ToggleButton(text='Spanish',
                                  id='span',
                                  group='lang',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .5
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.lang3 = ToggleButton(text='French',
                                  id='fren',
                                  group='lang',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .4
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.add_widget(self.lang1)
        self.add_widget(self.lang2)
        self.add_widget(self.lang3)

        self.trainbutton = Button(text='Train model',
                                  size_hint=(.25, .15),
                                  pos_hint={
                                      'center_x': .75,
                                      'center_y': .725
                                  })
        self.trainbutton.bind(on_release=self.train_helper)
        self.add_widget(self.trainbutton)
        self.aistatus = Label(text='Model status',
                              size_hint=(.25, .15),
                              pos_hint={
                                  'center_x': .75,
                                  'center_y': .575
                              },
                              color=(0, 0, 0, 1))
        self.add_widget(self.aistatus)
        self.dotbutton = Button(text='Frequency analysis',
                                size_hint=(.25, .15),
                                pos_hint={
                                    'center_x': .75,
                                    'center_y': .425
                                })
        self.dotbutton.bind(on_release=self.dot_helper)
        self.add_widget(self.dotbutton)
        self.dotlabel = Label(text='Frequency analysis results',
                              size_hint=(.25, .15),
                              pos_hint={
                                  'center_x': .75,
                                  'center_y': .275
                              },
                              color=(0, 0, 0, 1))
        self.add_widget(self.dotlabel)
Exemple #42
0
 def build(self):
     return Button(text="This is a Button")
Exemple #43
0
    def __init__(self, **kwargs):
        super(OhmScreen, self).__init__(**kwargs)

        # Default value to be calculated.
        self.selected = "current"

        # Create a float layout.
        self.float_layout = FloatLayout()
        self.add_widget(self.float_layout)

        # Triangle image.
        self.triangle_image = Image(source="assets/images/I_318px-law_triangle.png",
                                    keep_ratio=False,
                                    #size_hint=(0.2, 0.2),
                                    size_hint=(None, None),
                                    width="150sp",
                                    height="150sp",
                                    allow_stretch=True,
                                    pos_hint={"center_x": 0.5, "top": 0.97})
        self.float_layout.add_widget(self.triangle_image)

        # Invisible grid layout and buttons for the triangle image.
        triangle_grid_layout = GridLayout(rows=2, cols=2,
                                          pos_hint={'center_x':0.5, "top": 0.97},
                                          size=("150sp", "150sp"),
                                          size_hint=(None, None))
        triangle_top_left_button = Button(id="triangle_top_left_button",
                                          size_hint_x=None, width="75sp",
                                          size_hint_y=None, height="75sp",
                                          opacity=0)
        triangle_top_left_button.bind(on_press=self.deactivate_sliders)
        triangle_grid_layout.add_widget(triangle_top_left_button)

        triangle_top_right_button = Button(id="triangle_top_right_button",
                                           size_hint_x=None, width="75sp",
                                           size_hint_y=None, height="75sp",
                                           background_color=(0, 0, 0, 0),
                                           background_normal="")
        triangle_top_right_button.bind(on_press=self.deactivate_sliders)
        triangle_grid_layout.add_widget(triangle_top_right_button)

        triangle_bottom_left_button = Button(id="triangle_bottom_left_button",
                                             size_hint_x=None, width="75sp",
                                             size_hint_y=None, height="75sp",
                                             background_color=(0, 0, 0, 0),
                                             background_normal="")
        triangle_bottom_left_button.bind(on_press=self.deactivate_sliders)
        triangle_grid_layout.add_widget(triangle_bottom_left_button)

        triangle_bottom_right_button = Button(id="triangle_bottom_right_button",
                                              size_hint_x=None, width="75sp",
                                              size_hint_y=None, height="75sp",
                                              background_color=(0, 0, 0, 0),
                                              background_normal="")
        triangle_bottom_right_button.bind(on_press=self.deactivate_sliders)
        triangle_grid_layout.add_widget(triangle_bottom_right_button)
        self.float_layout.add_widget(triangle_grid_layout)

        # Back to menu button.
        #self.back_to_menu_button = BackToMenuButton(pos_hint={"left":0, "bottom":1},
        #                                            size_hint=(0.2, 0.1))
        #self.float_layout.add_widget(self.back_to_menu_button)

        # Create a grid layout inside the float layout.
        self.grid_layout = GridLayout(rows=4,
                                      cols=3,
                                      pos_hint={"center_x":0.5, "bottom":0},
                                      size_hint=(0.5, 0.7))
        self.float_layout.add_widget(self.grid_layout)

        # Inside the grid layout, create the sliders.
        self.current_slider = Slider(id="current_slider",
                                     min=0.1,
                                     max=900,
                                     step=0.1,
                                     orientation='vertical',
                                     pos_hint={"x":0.5, "top":0.3},
                                     size_hint=(0.1, 0.6),
                                     value=0.1,
                                     value_track=True,
                                     value_track_color=(1, 0.96, 0.49, 1.0),
                                     disabled=True)
        self.current_slider.bind(value=self.calculate_ohm_values)
        self.grid_layout.add_widget(self.current_slider)

        self.voltage_slider = Slider(id="voltage_slider",
                                     min=0.1,
                                     max=9,
                                     step=0.1,
                                     orientation='vertical',
                                     pos_hint={"x":0.5, "top":0.3},
                                     size_hint=(0.1, 0.6),
                                     value_track=True,
                                     value_track_color=(1, 0.96, 0.49, 1.0),
                                     value=0.05)
        self.grid_layout.add_widget(self.voltage_slider)
        self.voltage_slider.bind(value=self.calculate_ohm_values)

        self.resistance_slider = Slider(id="resistance_slider",
                                        min=10,
                                        max=1000,
                                        step=0.1,
                                        orientation='vertical',
                                        pos_hint={"x":0.5, "top":0.3},
                                        size_hint=(0.1, 0.6),
                                        value_track=True,
                                        value_track_color=(1, 0.96, 0.49, 1.0),
                                        value=500)
        self.grid_layout.add_widget(self.resistance_slider)
        self.resistance_slider.bind(value=self.calculate_ohm_values)

        # Inside the grid layout, create the labels.
        self.current_label = Label(text=str(self.current_slider.value) + "\nmA",
                                   size_hint=(0.1, 0.1),
                                   halign='center')
        self.grid_layout.add_widget(self.current_label)
        self.voltage_label = Label(text=str(self.voltage_slider.value) + "\nV",
                                   size_hint=(0.1, 0.1),
                                   halign='center')
        self.grid_layout.add_widget(self.voltage_label)
        self.resistance_label = Label(text=str(self.resistance_slider.value) + "\nOhms",
                                      size_hint=(0.1, 0.1),
                                      halign='center')
        self.grid_layout.add_widget(self.resistance_label)

        # Add a button explaining how to use this section.
        self.ohm_instructions_button = InstructionsButton(pos_hint={"center_x": 0.1, "bottom": 1})
        self.ohm_instructions_button.bind(on_press=self.show_instructions)
        self.float_layout.add_widget(self.ohm_instructions_button)

        # Outside the grid layout (but inside the float layout), add the reset button.
        reset_ohm_button = ResetOhmButton(pos_hint={"right":1, "bottom":1},
                                          size_hint=(0.2, 0.1))
        self.float_layout.add_widget(reset_ohm_button)
Exemple #44
0
class AI(FloatLayout):
    def file_checker(self, ciph, length, lang):
        return os.path.exists(lang + '_' + str(length) + '_' + ciph[0:3] +
                              '.csv')

    def train_helper(self, not_used):
        threading.Thread(target=self.train).start()

    def train(self):
        # don't start training again with one currently active
        if self.training:
            return
        self.training = True

        # get cipher choice
        ciph_tb = next(
            (t for t in ToggleButton.get_widgets('ciph') if t.state == 'down'),
            None)
        if ciph_tb == None:
            self.aistatus.text = 'Please select a cipher'
            self.training = False
            return
        ciph = ciph_tb.id

        ##        if cipher == 'affine':
        ##            self.aistatus.text = 'Affine not yet implemented with the GUI.'
        ##            self.training = False
        ##            return

        # get length choice
        len_tb = next(
            (t for t in ToggleButton.get_widgets('len') if t.state == 'down'),
            None)
        if len_tb == None:
            self.aistatus.text = 'Please select a ciphertext length'
            self.training = False
            return
        length = int(len_tb.id)

        lang_tb = next(
            (t for t in ToggleButton.get_widgets('lang') if t.state == 'down'),
            None)
        if lang_tb == None:
            self.aistatus.text = 'Please select a language'
            self.training = False
            return
        lang = lang_tb.id

        self.aistatus.text = 'Checking necessary files...'
        files = self.file_checker(ciph, length, lang)
        if files:
            self.aistatus.text = 'Files exist. Moving directly to training...'
        else:
            self.aistatus.text = 'Files do not exist. Generating necessary files...'
        sleep(1)

        if ciph == 'evan':
            for msg in cgtrain():
                self.aistatus.text = msg
            self.training = False
            return

        import generator
        import train

        # actual work begins here
        languages = {'eng': 'English', 'span': 'Spanish', 'fren': 'French'}
        self.aistatus.text = 'Creating snippets in ' + languages[lang] + '...'
        generator.generate(length, lang)
        self.aistatus.text = 'Snippets created. Encrypting snippets for testing...'
        generator.encrypt(length, lang, ciph)
        self.aistatus.text = 'Encryption complete. Advancing to neural network.'
        for msg in train.train(length, lang, ciph):
            self.aistatus.text = msg
        self.training = False

    def dot_helper(self, not_used):
        threading.Thread(target=self.dot).start()

    def dot(self):
        if self.dotting:
            return
        self.dotting = True

        ciph_tb = next(
            (t for t in ToggleButton.get_widgets('ciph') if t.state == 'down'),
            None)
        if ciph_tb == None:
            self.dotlabel.text = 'Please select a cipher'
            self.dotting = False
            return

        len_tb = next(
            (t for t in ToggleButton.get_widgets('len') if t.state == 'down'),
            None)
        if len_tb == None:
            self.dotlabel.text = 'Please select a ciphertext length'
            self.dotting = False
            return

        length = int(len_tb.id)
        lang_tb = next(
            (t for t in ToggleButton.get_widgets('lang') if t.state == 'down'),
            None)
        if lang_tb == None:
            self.dotlabel.text = 'Please select a language'
            self.dotting = False
            return
        lang = lang_tb.id

        if ciph_tb.id != 'caesar':
            self.dotlabel.text = 'Frequency analysis currently only available for caesar cipher.'
            self.dotting = False
            return

        import train
        results = train.test_all(length, lang)
        self.dotlabel.text = 'Frequency analysis accuracy: ' + str(results)
        self.dotting = False

    def __init__(self, **kwargs):
        super(AI, self).__init__(**kwargs)
        self.training = False
        self.dotting = False

        self.ciph1 = ToggleButton(text='Caesar cipher',
                                  id='caesar',
                                  group='ciph',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .15,
                                      'center_y': .6
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.ciph2 = ToggleButton(text='Affine cipher',
                                  id='affine',
                                  group='ciph',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .15,
                                      'center_y': .5
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.ciph3 = ToggleButton(text='Evan\'s test',
                                  id='evan',
                                  group='ciph',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .15,
                                      'center_y': .4
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.add_widget(self.ciph1)
        self.add_widget(self.ciph2)
        self.add_widget(self.ciph3)

        self.len1 = ToggleButton(text='1 words',
                                 id='1',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .8
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len2 = ToggleButton(text='2 words',
                                 id='2',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .7
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len3 = ToggleButton(text='4 words',
                                 id='4',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .6
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len4 = ToggleButton(text='8 words',
                                 id='8',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .5
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len5 = ToggleButton(text='16 words',
                                 id='16',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .4
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len6 = ToggleButton(text='32 words',
                                 id='32',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .3
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.len7 = ToggleButton(text='64 words',
                                 id='64',
                                 group='len',
                                 size_hint=(.1, .1),
                                 pos_hint={
                                     'center_x': .3,
                                     'center_y': .2
                                 },
                                 background_normal='',
                                 background_color=(.6, .6, .6, 1))
        self.add_widget(self.len1)
        self.add_widget(self.len2)
        self.add_widget(self.len3)
        self.add_widget(self.len4)
        self.add_widget(self.len5)
        self.add_widget(self.len6)
        self.add_widget(self.len7)

        self.lang1 = ToggleButton(text='English',
                                  id='eng',
                                  group='lang',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .6
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.lang2 = ToggleButton(text='Spanish',
                                  id='span',
                                  group='lang',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .5
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.lang3 = ToggleButton(text='French',
                                  id='fren',
                                  group='lang',
                                  size_hint=(.1, .1),
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .4
                                  },
                                  background_normal='',
                                  background_color=(.6, .6, .6, 1))
        self.add_widget(self.lang1)
        self.add_widget(self.lang2)
        self.add_widget(self.lang3)

        self.trainbutton = Button(text='Train model',
                                  size_hint=(.25, .15),
                                  pos_hint={
                                      'center_x': .75,
                                      'center_y': .725
                                  })
        self.trainbutton.bind(on_release=self.train_helper)
        self.add_widget(self.trainbutton)
        self.aistatus = Label(text='Model status',
                              size_hint=(.25, .15),
                              pos_hint={
                                  'center_x': .75,
                                  'center_y': .575
                              },
                              color=(0, 0, 0, 1))
        self.add_widget(self.aistatus)
        self.dotbutton = Button(text='Frequency analysis',
                                size_hint=(.25, .15),
                                pos_hint={
                                    'center_x': .75,
                                    'center_y': .425
                                })
        self.dotbutton.bind(on_release=self.dot_helper)
        self.add_widget(self.dotbutton)
        self.dotlabel = Label(text='Frequency analysis results',
                              size_hint=(.25, .15),
                              pos_hint={
                                  'center_x': .75,
                                  'center_y': .275
                              },
                              color=(0, 0, 0, 1))
        self.add_widget(self.dotlabel)
Exemple #45
0
 def build(self):
     return Button(text='Hello World!',
                   on_press=self.click)
Exemple #46
0
class MainLayout(BoxLayout):
    _video_capture = None
    _face_cascade = None
    _frame_name = str(PROJECT_APP_PATH.user_cache / "face_detection_frame.jpg")

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

    def build_dropdown(self):
        dropdown_layout = DropDown()

        for index in range(10):
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn2 = Button(text=f"Model {index:d}", size_hint_y=None, height=20)

            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn2.bind(on_release=lambda btn: dropdown_layout.select(btn.text))

            # then add the button inside the dropdown
            dropdown_layout.add_widget(btn2)

        # create a big main button
        self._dropdown_btn = Button(text="Model", size_hint=(0.5, 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._dropdown_btn.bind(on_release=dropdown_layout.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        dropdown_layout.bind(on_select=self.on_select_model)

        return self._dropdown_btn

    def on_select_model(self, ins, model):
        self._selected_model = model
        self._dropdown_btn.text = model
        # setattr(self.dropdown_btn, 'text', model)

    def build(self):

        apply_btn = Button(text="Apply", bold=True)
        apply_btn.bind(on_press=self.settings_process)

        dropdown_btn = self.build_dropdown()

        kv_layout = GridLayout(cols=2)
        kv_layout.add_widget(Label(text="Model: ", bold=True))
        kv_layout.add_widget(dropdown_btn)

        settings_layout = BoxLayout(orientation="vertical")
        settings_layout.add_widget(kv_layout)
        settings_layout.add_widget(apply_btn)

        self._popup = Popup(title="Settings",
                            content=settings_layout,
                            size_hint=(0.6, 0.2))

    def start(self):
        if self.ids.status.text == "Stop":
            self.stop()
        else:
            self.start_cam()

    def start_cam(self):
        self.ids.status.text = "Stop"
        self._video_capture = cv2.VideoCapture(0)
        self._face_cascade = cv2.CascadeClassifier(
            cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
        Clock.schedule_once(self.update)

    def stop(self):
        self.ids.status.text = "Start"
        Clock.unschedule(self.update)
        self._video_capture.release()
        cv2.destroyAllWindows()

    def update(self, dt):
        ret, frame = self._video_capture.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        try:
            faces = self._face_cascade.detectMultiScale(gray,
                                                        scaleFactor=1.1,
                                                        minNeighbors=5,
                                                        minSize=(30, 30))

            for (x, y, w, h) in faces:
                cv2.rectangle(rgb, (x, y), (x + w, y + h), (0, 255, 0), 2)
        except Exception as e:
            print(e)

        imageio.imsave(self._frame_name, rgb)
        self.ids.image_source.reload()
        Clock.schedule_once(self.update)

    @staticmethod
    def close():
        App.get_running_app().stop()

    def settings(self):
        self._popup.open()

    def settings_process(self, btn):
        try:
            self._current_model = self._selected_model
        except:
            pass
        self._popup.dismiss()
    def __init__(self, **kwargs):
        super(Btn_Canvas, self).__init__(**kwargs)
        display_word2 = "休止"
        self.text = display_word2
        self.word_type = "3"  #発音音声タイプを入力してください 1:モーラ 2:音声記号表 3:ATR503
        self.panda = False

        if self.word_type == "1":
            self.word_dict = {
                "モーラ(あ)": "あ い う え お や ゆ よ",
                "モーラ(か)": "か き く け こ きゃ きゅ きょ",
                "モーラ(が)": "が ぎ ぐ げ ご ぎゃ ぎゅ ぎょ",
                "モーラ(さ)": "さ し す せ そ しゃ しゅ しょ",
                "モーラ(ざ)": "ざ じ ず ぜ ぞ じゃ じゅ じょ",
                "モーラ(た)": "た ち つ て と ちゃ ちゅ ちょ",
                "モーラ(だ)": "だ で ど",
                "モーラ(な)": "な に ぬ ね の にゃ にゅ にょ ",
                "モーラ(は)": "は ひ ふ へ ほ ひゃ ひゅ ひょ ",
                "モーラ(ぱ)": "ぱ ぴ ぷ ぺ ぽ ぴゃ ぴゅ ぴょ",
                "モーラ(ま)": "ま み む め も みゃ みゅ みょ",
                "モーラ(ら)": "ら り る れ ろ りゃ りゅ りょ",
                "モーラ(わ)": "わ"
            }
        elif self.word_type == "2":
            self.word_dict = {
                "音記(あ)": "あ い う え お ",
                "音記(か)": "か き く け こ きゃ きゅ きょ",
                "音記(さ)": "さ し す せ そ しゃ しゅ しょ",
                "音記(た)": "た ち つ て と ちゃ ちゅ ちょ",
                "音記(な)": "な に ぬ ね の にゃ にゅ にょ ",
                "音記(は)": "は ひ ふ へ ほ ひゃ ひゅ ひょ ",
                "音記(ま)": "ま み む め も みゃ みゅ みょ",
                "音記(や)": "や ゆ よ",
                "音記(ら)": "ら り る れ ろ りゃ りゅ りょ",
                "音記(わ)": "わ",
                "音記(が)": "が ぎ ぐ げ ご ぎゃ ぎゅ ぎょ",
                "音記(ざ)": "ざ じ ず ぜ ぞ じゃ じゅ じょ",
                "音記(だ)": "だ で ど",
                "音記(ば)": "ば び ぶ べ ぼ びゃ びゅ びょ",
                "音記(ぱ)": "ぱ ぴ ぷ ぺ ぽ ぴゃ ぴゅ ぴょ",
            }
        elif self.word_type == "3":
            df_ATR = pd.read_excel()
            ATR_list = df_ATR["発話文"].values.tolist()
            ATR_keys, ATR_values, ATR_keys2, ATR_values2 = [], [], [], []
            for ATR_word in ATR_list:
                if 'a' in ATR_word.split(":")[0]:
                    ATR_keys.append(ATR_word.split(":")[0])
                    ATR_values.append(ATR_word.split(":")[1])
            ATR_num = len(ATR_keys) // 5
            for i in range(ATR_num):
                ATR_keys2.append(f"ATR_a{i * 5 + 1}_{i * 5 + 5}")
                ATR_values2.append(
                    f"{ATR_values[i * 5]}/{ATR_values[i * 5 + 1]}/{ATR_values[i * 5 + 2]}/"
                    f"{ATR_values[i * 5 + 3]}/{ATR_values[i * 5 + 4]}")
            ATR_dict = dict(zip(ATR_keys2, ATR_values2))
            self.word_dict = ATR_dict
            self.c_display.font_size = 36

        word_list = list(self.word_dict.keys())
        for v_word in word_list:
            button = Button(text=v_word, size_hint=(.2, .25))
            button.bind(on_press=self.press_word)
            self.word_buttons.add_widget(button)
Exemple #48
0
 def build(self):
     return Button(text="hello world")
Exemple #49
0
    def update_details(self):
        self.details_container.clear_widgets()
        self.settings_widgets = []
        connected_color = [.5, .5, .5, 1]
        connected_text = "not connected"
        if self.device.connected:
            connected_color = [0, 1, 0, 1]
            connected_text = "connected"
        status_row = BoxLayout()
        connected_button = Button(
            text=connected_text,
            background_color=connected_color,
            height=30,
            size_hint_y=None,
        )
        connected_button.bind(
            on_press=lambda widget: self.app.update_devices())
        remove_button = Button(text="clear", height=30, size_hint_y=None)
        remove_button.bind(
            on_press=lambda widget: [self.parent.remove_widget(self)])
        status_row.add_widget(connected_button)
        status_row.add_widget(remove_button)
        self.details_container.add_widget(status_row)

        # device information
        for k, v in self.device.details.items():
            row = BoxLayout(height=30, size_hint_y=None)
            key = Label(text=str(k))
            value = Label(text=str(v))
            row.add_widget(key)
            row.add_widget(value)
            self.details_container.add_widget(row)

        # add adjustable values from the db
        # the db material is generated from xml
        # see enn-db and reference.xml
        try:
            # incorrect keys will be stored/reloaded from xml
            if "scripts" not in self.device.details:
                self.device.details["scripts"] = redis_conn.hget(
                    "device:script_lookup", self.device.details["name"])

            reference = redis_conn.hgetall("scripts:{}".format(
                self.device.details["scripts"]))
            for attribute, _ in reference.items():
                row = BoxLayout(height=30, size_hint_y=None)
                key = Label(text=str(attribute))
                value = TextInput(multiline=False)
                try:
                    value.text = self.device.settings[attribute]
                except KeyError as ex:
                    print(ex)
                    pass
                value.bind(
                    on_text_validate=lambda widget, attribute=attribute: self.
                    set_device_setting(attribute, widget.text, widget))
                # store to get set_device_setting before preview
                value.attribute = attribute
                self.settings_widgets.append(value)
                row.add_widget(key)
                row.add_widget(value)
                self.details_container.add_widget(row)
        except Exception as ex:
            print(ex)

        # preview
        self.view_call_input = TextInput(text=self.default_view_call,
                                         multiline=False,
                                         height=30,
                                         size_hint_y=None)
        self.view_call_input.bind(
            on_text_validate=lambda widget: self.check_call())
        preview_button = Button(
            text="preview",
            background_color=connected_color,
            height=60,
            size_hint_y=None,
        )
        preview_button.bind(on_press=lambda widget: self.preview())

        get_state_button = Button(text="get state",
                                  height=30,
                                  size_hint_y=None)
        set_state_button = Button(text="set state",
                                  height=30,
                                  size_hint_y=None)
        get_state_button.bind(on_press=lambda widget: self.get_state())
        set_state_button.bind(on_press=lambda widget: self.set_state())
        get_set_state_row = BoxLayout(height=30, size_hint_y=None)
        load_state_from_row = BoxLayout(height=30, size_hint_y=None)
        load_state_from_button = Button(text="load state from",
                                        height=30,
                                        size_hint_y=None)
        load_state_from_input = TextInput(hint_text="db key",
                                          multiline=False,
                                          height=30,
                                          size_hint_y=None)
        load_state_from_button.bind(
            on_press=lambda widget, state_source=load_state_from_input: self.
            load_state(load_state_from_input.text))
        get_set_state_row.add_widget(get_state_button)
        get_set_state_row.add_widget(set_state_button)
        self.details_container.add_widget(get_set_state_row)
        load_state_from_row.add_widget(load_state_from_button)
        load_state_from_row.add_widget(load_state_from_input)
        self.details_container.add_widget(load_state_from_row)
        self.details_container.add_widget(self.view_call_input)
        self.details_container.add_widget(preview_button)
        self.update_conditions()
Exemple #50
0
 def __init__(self, **kwargs):
     super(ButtonItem, self).__init__(**kwargs)
     b = Button()
     self.add_widget(b)
     self.my_button = b
 def required_list_main(self):
     count = 0
     total = 0
     self.root.ids.popup.dismiss()  # will be used later to dismiss pop up
     self.root.ids.itemDisplay.clear_widgets()  # clear everything
     required_list = sorted(self.list, key=operator.itemgetter(
         2))  # sort the items and out items in required_list
     self.root.ids.instructionMenu.text = "Click items to mark an item as completed. Priotities: RED (1), BLUE (2) and GREEN (3)"  # sending text to a bottom label
     for each_item in required_list:  # for every item in list
         if "r" in each_item[3]:
             if int(each_item[2]) == 1:  # checks priority
                 item_button = Button(
                     text="{} ${}".format(each_item[0], each_item[1]),
                     background_color=[1, 0, 0, 1]
                 )  #for giving background color based on priority and creating button
                 item_button.item = each_item
                 item_button.bind(
                     on_press=partial(self.mark_completed, "1")
                 )  # assigning function to a button and using partial tp pass object and a value
                 self.root.ids.itemDisplay.add_widget(
                     item_button)  # adding button to the widget
                 count += 1
                 total += float(each_item[1])
             elif int(each_item[2]) == 2:
                 item_button = Button(text="{} ${}".format(
                     each_item[0], each_item[1]),
                                      background_color=[0, 0, 1, 1])
                 item_button.item = each_item
                 item_button.bind(
                     on_press=partial(self.mark_completed, "1"))
                 self.root.ids.itemDisplay.add_widget(item_button)
                 count += 1
                 total += float(each_item[1])
             else:
                 item_button = Button(text="{} ${}".format(
                     each_item[0], each_item[1]),
                                      background_color=[0, 1, 0, 1])
                 item_button.item = each_item
                 item_button.bind(
                     on_press=partial(self.mark_completed, "1"))
                 self.root.ids.itemDisplay.add_widget(item_button)
                 count += 1
                 total += float(each_item[1])
     if count == 0:
         self.root.ids.itemInfo.text = "No required items"  # if no items are there sending this text to label
         self.root.ids.itemDisplay.clear_widgets(
         )  # clearing label in a widget
     else:
         self.root.ids.itemInfo.text = "Total price expected for {} items: ${}".format(
             count, total)  # sending instruction to label
Exemple #52
0
class SearchLayout(GridLayout):
    '''
    Here's a custom layout. Contain a show layout and text layout
    '''
    def __init__(self, sg=None, **kwargs):
        super(SearchLayout, self).__init__(**kwargs)
        self.cols = 2
        self.sg_t = sg

        self.search_keyword = TextInput(multiline=False,
                                        size_hint_y=None,
                                        height=40)
        self.search_keyword.bind(text=self.name_get_text)

        self.search_button = Button(text='Search Entity',
                                    size_hint_y=None,
                                    height=40,
                                    size_hint_x=None,
                                    width=250)
        self.search_button.bind(on_press=self.search)

        #print("Hello")
        #runTouchApp(self.search_button)

        #self.search_button = Button(text = 'Search Entity')
        #self.search_button.bind(on_press = self.search)
        self.add_widget(self.search_keyword)  #row=9
        self.add_widget(self.search_button)  #row=10

    def name_get_text(self, instance, value):
        '''
        Get value from input box
        '''
        self.name_text = value
        #print(")((**")

    def search(self, instance):
        '''
        search articles (as well as attributes) in the graph
        '''

        if self.name_text == '':
            pass
        else:
            self.dropdown = DropDown()
            file = open('..\\IdWithTitle.csv', 'r', encoding='utf-8')
            lines = file.readlines()
            file.close()
            show_text = ''
            self.idWithTitle = {}
            for line in lines:
                temp = line.split('\t')
                if self.name_text.lower() in temp[1].lower():
                    #print("!!!!")
                    self.idWithTitle[temp[0]] = temp[1]
                    show_text += temp[1]
            for k, v in self.idWithTitle.items():
                #print(v)
                btn = Button(text=v, size_hint_y=None, height=35)
                btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
                btn.bind(on_press=self.graphSearch)
                self.dropdown.add_widget(btn)

            self.search_button.bind(on_release=self.dropdown.open)
            self.dropdown.bind(on_select=lambda instance, x: setattr(
                self.search_button, 'text', x))

            #self.sg_t.frequency.text = show_text
    def graphSearch(self, instance):
        #print(instance)
        #print(value)
        #self.sg_t.frequency.text = instance.text
        file = open('..\\idWithAliasWithUniverse.csv', 'r', encoding='utf-8')
        lines = file.readlines()
        file.close()
        file1 = open('..\\Full_Info_Data.csv', 'r', encoding='utf-8')
        person = file1.readlines()
        file1.close()

        #print(instance.text)
        self.universe = ''
        self.pid = ''
        self.alias = ''
        self.universeWithCharacters = {}

        for line in person:
            temp = line.split('\t')
            if temp[1] in instance.text:
                self.pid = temp[0]

        for line in lines:
            temp = line.split('\t')
            if self.pid == temp[0]:
                self.universe = temp[2].replace('\n', '')
                self.alias = temp[1]

        for line in lines:
            temp = line.split('\t')
            if temp[2].replace('\n', '') in self.universe.replace(
                    '\n', '') and temp[0] != self.pid:
                self.universeWithCharacters[temp[0]] = [temp[1]]

        for line in person:
            temp = line.split('\t')
            if temp[1].replace('\n', '') in instance.text.replace('\n', ''):
                self.sg_t.frequency.text = "<id>\t" + temp[0] + "\n<title>\t" + temp[
                    1] + "<RealName>\t" + temp[2] + "\n<CurrentAlias>\t" + temp[
                        3] + "\n<Affiliation>\t" + temp[4] + "\n<Relatives>\t" + temp[
                            5] + "\n<Universe>\t" + temp[6] + "\n<Gender>\t" + temp[
                                7] + "\n<Height>\t" + temp[
                                    8] + "\n<Weight>\t" + temp[
                                        9] + "\n<Eyes>\t" + temp[
                                            10] + "\n<Hair>\t" + temp[
                                                11] + "\n<Citizenship>\t" + temp[
                                                    12] + "\n<Quotation>\t" + temp[
                                                        13] + "\n"

        for line in person:
            temp = line.split('\t')
            if temp[0] in self.universeWithCharacters.keys():
                tempName = self.universeWithCharacters[temp[0]]
                self.universeWithCharacters[temp[0]] = [tempName, temp[5]]
        #print(self.universe)
        #print(self.pid)
        #print(self.alias)
        #print("I'm here")
        count1 = 0
        #count2 = 0
        sgraph = igraph.Graph()
        sgraph.add_vertex(name=self.alias.replace('\n', ''),
                          label=self.alias.replace('\n', ''),
                          size=150,
                          color='red')
        sgraph.add_vertex(name=self.universe.replace('\n', ''),
                          label=self.universe.replace('\n', ''),
                          size=200,
                          color='orange')
        sgraph.add_edge(self.universe.replace('\n', ''),
                        self.alias.replace('\n', ''))
        for k, v in self.universeWithCharacters.items():
            #print(v[0])
            count1 += 1
            if self.alias.replace('\n', '') in v[1].replace('\n', ''):
                sgraph.add_vertex(name=v[0][0].replace('\n', ''),
                                  label=v[0][0].replace('\n', ''),
                                  size=100,
                                  color='blue')
                sgraph.add_edge(v[0][0].replace('\n', ''),
                                self.alias.replace('\n', ''))
                sgraph.add_edge(self.universe.replace('\n', ''),
                                v[0][0].replace('\n', ''))
            elif count1 < 25:
                sgraph.add_vertex(name=v[0][0].replace('\n', ''),
                                  label=v[0][0].replace('\n', ''),
                                  size=50,
                                  color='grey')
                sgraph.add_edge(self.universe.replace('\n', ''),
                                v[0][0].replace('\n', ''))
        layout = sgraph.layout("kk")
        igraph.plot(sgraph,
                    layout=layout,
                    bbox=(1300, 1000),
                    margin=100,
                    edge_width=10,
                    vertex_label_size=50).save(
                        self.alias.replace('\n', '') + self.universe +
                        "_search.png")
        self.sg_t.picture.source = self.alias.replace(
            '\n', '') + self.universe + "_search.png"
Exemple #53
0
 def __init__(self, **kwargs):
     super(MainLayout, self).__init__(**kwargs)
     self.add_widget(Button(text="Button1"))
     self.add_widget(Button(text="Button2"))
Exemple #54
0
class start(FloatLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        #Window.size = (800 , 480)  #Sets window sixe to size of display
        #Window.fullscreen = True
        super(start, self).__init__(**kwargs)
        self.add_widget(
            AsyncImage(source="/home/pi/carbon.jpeg",
                       size_hint=(1.5, 1.5),
                       pos_hint={
                           'center_x': .5,
                           'center_y': .5
                       }))
        self.startbtn = Button(text="START",
                               background_color=(0, 1, 0, 1),
                               size_hint=(.3, .3),
                               pos_hint={
                                   'center_x': .5,
                                   'center_y': .7
                               })
        self.startbtn.bind(on_press=self.btn_pressedstart)
        self.add_widget(self.startbtn)

        self.quitbtn = Button(text="SAVE AND QUIT",
                              background_color=(1, 0, 0, 1),
                              size_hint=(.2, .2),
                              pos_hint={
                                  'center_x': .5,
                                  'center_y': .3
                              })
        self.quitbtn.bind(on_press=self.btn_pressedquit)
        self.add_widget(self.quitbtn)

        with self.canvas.before:
            Color(0, 0, 0, 0)  # green; colors range from 0-1 instead of 0-255
            self.rect = Rectangle(size=self.size, pos=self.pos)

        self.bind(size=self._update_rect, pos=self._update_rect)

    def _update_rect(self, instance, value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size

    def btn_pressedstart(self, instance):
        self.remove_widget(self.startbtn)
        make_workbook()
        global wb
        global sheet1
        sheet1 = wb.add_worksheet('Power Phase')
        global sheet2
        sheet2 = wb.add_worksheet('Cadence')
        #Adds headers for different values
        sheet1.write(0, 0, 'Right Power')
        sheet1.write(0, 1, 'Right Crank Angle')
        sheet1.write(0, 2, 'Left Power')
        sheet1.write(0, 3, 'Left Crank Angle')
        sheet2.write(0, 0, 'Time')
        sheet2.write(0, 1, 'Average Cadence')

        print('Hello')
        data_processing()
        return

    def btn_pressedquit(self, instance):
        global wb
        wb.close()
        global bt_power
        bt_power = 0
        global p1
        p1.terminate()
        global p2
        p2.terminate()
        disconnect()
        print("Bye")
        self.add_widget(self.startbtn)
        MainApp.get_running_app().stop()
        Window.close()
 def FileLoadScreen(self):
     self.add_widget(
         Button(size_hint_y=(None),
                height=('48dp'),
                text='Select File',
                on_press=self.ImportFile))
Exemple #56
0
    def __init__(self, **kwargs):
        super(GameWindow, self).__init__(**kwargs)
        self.cols = 1
        self.rows = 2

        self.GameWindow1 = GridLayout()
        self.GameWindow1.cols = 1
        self.GameWindow1.rows = 3

        self.GameWindow1.add_widget(Label(text="COMPUTER DEALER", font_size=25, color=(1, 1, 1, 1), outline_width=1,
                                          outline_color=(0, 0.5, 0.5, 1), halign="center", valign="center"))

        self.GameWindow2 = GridLayout()
        self.GameWindow2.cols = 7
        self.GameWindow2.rows = 1

        self.GameWindow2.add_widget(Label(text=""))

        self.compCardImage1 = Image(source=imagePath + "blue_back.png")
        self.GameWindow2.add_widget(self.compCardImage1)

        self.compCardImage2 = Image(source=imagePath + "blue_back.png")
        self.GameWindow2.add_widget(self.compCardImage2)

        self.compCardImage3 = Image(source=imagePath + "blue_back.png")
        self.GameWindow2.add_widget(self.compCardImage3)

        self.compCardImage4 = Image(source=imagePath + "blue_back.png")
        self.GameWindow2.add_widget(self.compCardImage4)

        self.compCardImage5 = Image(source=imagePath + "blue_back.png")
        self.GameWindow2.add_widget(self.compCardImage5)

        self.GameWindow2.add_widget(Label(text=""))

        self.GameWindow3 = GridLayout()
        self.GameWindow3.cols = 1
        self.GameWindow3.rows = 1

        self.GameWindow4 = GridLayout()
        self.GameWindow4.cols = 1
        self.GameWindow4.rows = 3

        self.GameWindow5 = GridLayout()
        self.GameWindow5.cols = 7
        self.GameWindow5.rows = 1

        self.GameWindow5.add_widget(Label(text=""))

        self.playerCardImage1 = Image(source=imagePath + "blue_back.png")
        self.GameWindow5.add_widget(self.playerCardImage1)

        self.playerCardImage2 = Image(source=imagePath + "blue_back.png")
        self.GameWindow5.add_widget(self.playerCardImage2)

        self.playerCardImage3 = Image(source=imagePath + "blue_back.png")
        self.GameWindow5.add_widget(self.playerCardImage3)

        self.playerCardImage4 = Image(source=imagePath + "blue_back.png")
        self.GameWindow5.add_widget(self.playerCardImage4)

        self.playerCardImage5 = Image(source=imagePath + "blue_back.png")
        self.GameWindow5.add_widget(self.playerCardImage5)

        self.GameWindow5.add_widget(Label(text=""))

        self.GameWindow6 = GridLayout()
        self.GameWindow6.cols = 1
        self.GameWindow6.rows = 1

        self.GameWindow6.add_widget(Label(text="PLAYER", font_size=25, color=(1, 1, 1, 1), outline_width=1,
                                          outline_color=(0, 0.5, 0.5, 1), halign="center", valign="center"))

        self.GameWindow7 = GridLayout()
        self.GameWindow7.cols = 7
        self.GameWindow7.rows = 1

        self.GameWindow7.add_widget(Label(text=""))

        self.GameWindow7.add_widget(Label(text=""))

        self.hitButton = Button(text="HIT", font_size=25, background_color=(0, 1, 1, 1))

        self.GameWindow7.add_widget(self.hitButton)

        self.GameWindow7.add_widget(Label(text=""))

        self.stayButton = Button(text="STAY", font_size=25, background_color=(0, 1, 1, 1))

        self.GameWindow7.add_widget(self.stayButton)

        self.GameWindow7.add_widget(Label(text="TOTAL :", font_size=25, color=(1, 1, 1, 1), outline_width=1,
                                          outline_color=(0, 0.5, 0.5, 1), halign="center", valign="center"))

        self.PlayerTotalLabel = Label(text="0", font_size=25, color=(1, 1, 1, 1), outline_width=1,
                                      outline_color=(0, 0.5, 0.5, 1), halign="center", valign="center")

        self.GameWindow7.add_widget(self.PlayerTotalLabel)

        self.add_widget(self.GameWindow1)
        self.GameWindow1.add_widget(self.GameWindow2)
        self.GameWindow1.add_widget(self.GameWindow3)

        self.add_widget(self.GameWindow4)
        self.GameWindow4.add_widget(self.GameWindow5)
        self.GameWindow4.add_widget(self.GameWindow6)
        self.GameWindow4.add_widget(self.GameWindow7)

        # initialization
        deck = Deck()
        deck.shuffle()
        # playerCoins = Coins()

        playerHandList = []
        compHandList = []

        # creating starting status of the game
        playerHand = Hand()
        playerHand.addCard(deck.deal())
        playerHand.addCard(deck.deal())
        playerHand.adjustForAce()

        compHand = Hand()
        compHand.addCard(deck.deal())
        compHand.addCard(deck.deal())
        compHand.adjustForAce()

        # appending starting cards into respective lists
        for i in playerHand.cards:
            playerHandList.append(str(i))
        for i in compHand.cards:
            compHandList.append(str(i))

        # displaying starting cards in gui
        self.playerCardImage1.source = imagePath + playerHandList[0]
        self.playerCardImage2.source = imagePath + playerHandList[1]
        self.compCardImage1.source = imagePath + compHandList[0]

        # Displaying value of cards in gui
        self.PlayerTotalLabel.text = str(playerHand.value)

        # function for displaying result in pop up window
        def displayResult():

            # resetting bet screen
            self.parent.clear_widgets()
            # self.parent.add_widget(Factory.GameWindow(name = "Game"))
            self.parent.add_widget(Factory.NewBetWindow(name="newBet"))

            # changing screen for displaying game result
            self.parent.current = "newBet"

            pw = PopupWindow()

            playerHandList1 = ", ".join(playerHandList)
            compHandList1 = ", ".join(compHandList)

            #Experimental
            playerHandList1 = playerHandList1.replace(".png", "").replace("H", " of Hearts").\
                replace("D", " of Diamonds").replace("S", " of Spades").replace("C", " of Clubs").\
                replace("J", "Jack").replace("Q", "Queen").replace("K", "King").replace("A", "Ace")

            compHandList1 = compHandList1.replace(".png", "").replace("H", " of Hearts").\
                replace("D", " of Diamonds").replace("S", " of Spades").replace("C", " of Clubs").\
                replace("J", "Jack").replace("Q", "Queen").replace("K", "King").replace("A", "Ace")

            # setting the text of popup window label according to the game result
            if playerHand.value > 21:
                playerCoins.lose()

                pw.popupLabel.text = "PLAYER BUSTS!\nYour coins: {0}\n\nPlayer\'s hand value = {1}" \
                                     "\n{2}\n(Greater than 21!)\n\nComputer\'s hand value is = {3}" \
                                     "\n{4}".format(str(playerCoins.total),
                                                    str(playerHand.value),
                                                    playerHandList1,
                                                    str(compHand.value),
                                                    compHandList1)

            elif compHand.value > 21:
                playerCoins.win()

                pw.popupLabel.text = "COMPUTER BUSTS!\nYour coins: {0}\n\nPlayer\'s hand value = {1}" \
                                     "\n{2}\n\nComputer\'s hand value is = {3}" \
                                     "\n{4}\n(Greater than 21!)".format(str(playerCoins.total),
                                                                        str(playerHand.value),
                                                                        playerHandList1,
                                                                        str(compHand.value),
                                                                        compHandList1)

            elif compHand.value > playerHand.value:
                playerCoins.lose()

                pw.popupLabel.text = "COMPUTER WINS!\nYour coins: {0}\n\nPlayer\'s hand value = {1}" \
                                     "\n{2}\n\nComputer\'s hand value is = {3}" \
                                     "\n{4}\n(Greater than Player's Hand)".format(str(playerCoins.total),
                                                                                  str(playerHand.value),
                                                                                  playerHandList1,
                                                                                  str(compHand.value),
                                                                                  compHandList1)

            elif compHand.value < playerHand.value:
                playerCoins.win()

                pw.popupLabel.text = "PLAYER WINS!\nYour coins: {0}\n\nPlayer\'s hand value = {1}" \
                                     "\n{2}\n(Greater than Computer's Hand)\n\nComputer\'s hand value is = {3}" \
                                     "\n{4}".format(str(playerCoins.total),
                                                    str(playerHand.value),
                                                    playerHandList1,
                                                    str(compHand.value),
                                                    compHandList1)

            # setting the contents of popup window
            popupWindow = Popup(title="RESULT", content=pw, size_hint=(None, None), size=(500, 500))
            popupWindow.open()

        # function for asking for another card if player clicks HIT button
        def hitFunction(instance):
            # new card added in player's hand object (background)
            playerHand.addCard(deck.deal())

            # appending newly added card in player's hand list
            for i in playerHand.cards:
                if str(i) not in playerHandList:
                    playerHandList.append(str(i))
            playerHand.adjustForAce()

            # Displaying value of cards in gui
            self.PlayerTotalLabel.text = str(playerHand.value)

            # adding new cards to player's hand in gui
            if len(playerHandList) == 3:
                self.playerCardImage3.source = imagePath + playerHandList[2]
                self.compCardImage2.source = imagePath + compHandList[1]
                time.sleep(1)

            elif len(playerHandList) == 4:
                self.playerCardImage4.source = imagePath + playerHandList[3]
                time.sleep(1)

            elif len(playerHandList) == 5:
                self.playerCardImage5.source = imagePath + playerHandList[4]
                time.sleep(1)

            # printing all details/logs on console
            print("HIT button pressed!")
            print("Player's cards:", playerHandList)
            print("Player's total:", playerHand.value)
            print("Computer's cards:", compHandList)
            print("Computer's total:", compHand.value)

            # checking if game ends or not
            if playerHand.value > 21 or compHand.value > 21 or compHand.value > playerHand.value \
                    or compHand.value < playerHand.value:
                displayResult()

        # function for playing computer's hand if  player clicks stay
        def stayFunction(instance):
            # if player isn't busted then adding a card to computer's hand
            if playerHand.value <= 21:
                self.compCardImage2.source = imagePath + compHandList[1]
                time.sleep(1)

                # while compHand.value < 17:
                while True:

                    # new card added in computers's hand object (background)
                    compHand.addCard(deck.deal())

                    # appending newly added card in computer's hand list
                    for i in compHand.cards:
                        if str(i) not in compHandList:
                            compHandList.append(str(i))
                        compHand.adjustForAce()

                    # adding new cards to computer's hand in gui
                    # self.compCardImage2.source = imagePath + compHandList[1]
                    time.sleep(1)

                    if len(compHandList) == 3:
                        self.compCardImage3.source = imagePath + compHandList[2]
                        time.sleep(1)

                    elif len(compHandList) == 4:
                        self.compCardImage4.source = imagePath + compHandList[3]
                        time.sleep(1)

                    elif len(compHandList) == 5:
                        self.compCardImage5.source = imagePath + compHandList[4]
                        time.sleep(1)

                    time.sleep(1)

                    # printing all details/logs on console
                    print("STAY button pressed!")
                    print("Player's cards:", playerHandList)
                    print("Player's total:", playerHand.value)
                    print("Computer's cards:", compHandList)
                    print("Computer's total:", compHand.value)

                    if playerHand.value > 21 or compHand.value > 21 or compHand.value > playerHand.value \
                            or compHand.value < playerHand.value:
                        break

            time.sleep(1)
            # checking if game ends or not
            if playerHand.value > 21 or compHand.value > 21 or compHand.value > playerHand.value \
                    or compHand.value < playerHand.value:
                displayResult()

        # binding buttons with functions
        self.hitButton.bind(on_press=hitFunction)
        self.stayButton.bind(on_press=stayFunction)
Exemple #57
0
    def build(self):  # For building the app
        parent = Game()
        parent.serve_car()  # Set car's initial config (line no. 301)
        '''
			Use 'Clock' object to schedule an event to be called every <timeout> seconds, using 
			'schedule_interval()' method.
			Reference => https://kivy.org/doc/stable/api-kivy.clock.html#kivy.clock.CyClockBase.schedule_interval
		'''
        Clock.schedule_interval(callback=parent.update, timeout=(1.0 / 60.0))

        clearBtn = Button(text="Clear")
        clearBtn.bind(on_release=self.clear_canvas)

        saveBtn = Button(text="Save", pos=(parent.width, 0))
        saveBtn.bind(on_release=self.save_brain)

        loadBtn = Button(text="Load", pos=((parent.width * 2), 0))
        loadBtn.bind(on_release=self.load_brain)

        self.painter = PaintWidget()
        parent.add_widget(self.painter)
        parent.add_widget(clearBtn)
        parent.add_widget(saveBtn)
        parent.add_widget(loadBtn)
        return parent
Exemple #58
0
 def build(self):
     self.button = Button(text="0",
                          font_size=48,
                          background_color=[1, 1, 1, 1],
                          on_press=self.click)
     return self.button
Exemple #59
0
    def __init__(self, data, tot, spent, alll, **kwargs):
        super(Results, self).__init__(**kwargs)
        self.one = data.keys()
        self.two = data.values()
        self.tot = float(sum(tot))
        self.allofit = alll
        self.spent = spent
        self.title = 'Income managements'.title()
        self.title_size = 30
        self.title_size = '20dp'
        self.title_align = 'center'
        self.auto_dismiss = False
        self.size_hint = [.9, .9]
        self.pos_hint = {'x': .05, 'y': .05}
        self.caption1 = MDLabel(text='monthly spendings:'.title(),
                                italic=True,
                                halign='left',
                                underline=True,
                                size_hint=(1, .1),
                                theme_text_color='Custom',
                                text_color=[.6, 0, 0, 1],
                                pos_hint={
                                    'x': 0,
                                    'top': 1
                                })

        self.box0 = BoxLayout(size_hint=(.1, .5),
                              pos_hint={
                                  "top": .92,
                                  "center_x": .55
                              },
                              orientation='vertical',
                              spacing=14)
        self.box1 = BoxLayout(size_hint=(.55, .5),
                              pos_hint={
                                  "top": .92,
                                  "x": 0
                              },
                              orientation='vertical',
                              spacing=14)
        self.box2 = BoxLayout(size_hint=(.45, .5),
                              pos_hint={
                                  "top": .92,
                                  "x": .53
                              },
                              orientation='vertical',
                              spacing=14)
        for item in self.one:
            self.lbl = MDLabel(text=str(item),
                               bold=True,
                               text_color=[1, 1, 1, 1],
                               halign='left',
                               theme_text_color='Custom')
            self.box1.add_widget(self.lbl)
        for item2 in self.two:
            self.lbl = MDLabel(text=str(item2) + '$',
                               bold=True,
                               text_color=[1, 1, 1, 1],
                               halign='right',
                               theme_text_color='Custom')
            self.box2.add_widget(self.lbl)
        for item2 in self.one:
            self.lbl = Label(text=":", bold=True, color=[1, 1, 1, 1])
            self.box0.add_widget(self.lbl)

        self.total = MDLabel(text='total spendings'.title(),
                             theme_text_color='Custom',
                             text_color=[.6, 0, 0, 1],
                             bold=True,
                             halign='left')
        self.box1.add_widget(self.total)
        self.colom = Label(text=':', color=[1, 1, 1, 1], bold=True)
        self.box0.add_widget(self.colom)
        self.res = MDLabel(text=str(self.tot) + "$",
                           theme_text_color='Custom',
                           text_color=[.6, 0, 0, 1],
                           bold=True,
                           halign='right')
        self.box2.add_widget(self.res)

        self.txt = MDLabel(
            text=
            f'- you still have an amount of  [b][color=#980000]{str(self.spent)}$[/color][/b]  from your monthly income.'
            .lower(),
            markup=True,
            theme_text_color='Custom',
            text_color=[1, 1, 1, 1],
            halign='left',
            size_hint=(1, .2),
            pos_hint={
                "top": .45,
                "x": 0
            })
        self.txt2 = MDLabel(
            text=
            f'- you spent a percentage of  [b][color=#980000]{str(100-((float(self.spent)*100)/float(self.allofit)))}%[/color][/b]  from your monthly income'
            .lower(),
            markup=True,
            theme_text_color='Custom',
            text_color=[1, 1, 1, 1],
            halign='left',
            size_hint=(1, .2),
            pos_hint={
                "top": .35,
                "x": 0
            })
        self.txt3 = MDLabel(
            text='- this is how much is spent from your monthly income:'.title(
            ),
            bold=True,
            theme_text_color='Custom',
            text_color=[1, 1, 1, 1],
            halign='left',
            size_hint=(1, .2),
            pos_hint={
                "top": .25,
                "x": 0
            })

        self.bar = MDProgressBar(
            value=float(100 -
                        ((float(self.spent) * 100) / float(self.allofit))),
            color=[1, 1, 1, 1],
            size_hint=(.6, .1),
            pos_hint={
                "x": .05,
                "top": .15
            })

        self.txt4 = MDLabel(text=str(
            int(100 - ((float(self.spent) * 100) / float(self.allofit)))) +
                            "%",
                            theme_text_color='Custom',
                            text_color=[1, 1, 1, 1],
                            size_hint=(.1, .1),
                            pos_hint={
                                "top": .15,
                                "x": 0.73
                            },
                            halign='left')

        self.cancel = Button(text='OK',
                             background_normal='',
                             color=[0, 0, 0, 1],
                             background_color=[1, 1, 1, 1],
                             size_hint=(.9, .06),
                             pos_hint={
                                 "x": .05,
                                 'top': .07
                             },
                             bold=True)
        self.cancel.bind(on_release=lambda x: self.dismiss())
        self.float = FloatLayout(size_hint=(1, 1), pos_hint={'top': 1})
        self.float.add_widget(self.caption1)
        self.float.add_widget(self.box1)
        self.float.add_widget(self.box2)
        self.float.add_widget(self.box0)
        self.float.add_widget(self.txt)
        self.float.add_widget(self.txt2)
        self.float.add_widget(self.txt3)
        self.float.add_widget(self.txt4)
        self.float.add_widget(self.cancel)
        self.float.add_widget(self.bar)
        self.add_widget(self.float)
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen

# Create the manager
sm = ScreenManager()


def switch_to_screen_two(screen_manager, *args):
    screen_manager.current = 'screen two'


def switch_to_screen_one(screen_manager, *args):
    screen_manager.current = 'screen one'


go_screen_two = Button(text="Go to screen two")
go_screen_two.bind(on_release=partial(switch_to_screen_two, sm))
screen_one = Screen(name="screen one")
screen_one.add_widget(go_screen_two)

go_screen_one = Button(text="Go to screen one")
go_screen_one.bind(on_release=partial(switch_to_screen_one, sm))
screen_two = Screen(name="screen two")
screen_two.add_widget(go_screen_one)

sm.add_widget(screen_one)
sm.add_widget(screen_two)

sm.current = "screen one"