コード例 #1
0
def DropDownCreation(data):
    Dropdown = DropDown()
    for i in data:
        drop_option = Button(text = i, size_hint_y = None, height = 40)
        drop_option.bind(on_release = lambda drop_option: Dropdown.select(drop_option.text))
        Dropdown.add_widget(drop_option)
    return Dropdown
コード例 #2
0
ファイル: tx_dialog.py プロジェクト: vialectrum/vialectrum
    def update_action_button(self):
        action_button = self.ids.action_button
        options = (
            ActionButtonOption(text=_('Sign'), func=lambda btn: self.do_sign(), enabled=self.can_sign),
            ActionButtonOption(text=_('Broadcast'), func=lambda btn: self.do_broadcast(), enabled=self.can_broadcast),
            ActionButtonOption(text=_('Bump fee'), func=lambda btn: self.do_rbf(), enabled=self.can_rbf),
            ActionButtonOption(text=_('Remove'), func=lambda btn: self.remove_local_tx(), enabled=self.is_local_tx),
        )
        num_options = sum(map(lambda o: bool(o.enabled), options))
        # if no options available, hide button
        if num_options == 0:
            action_button.disabled = True
            action_button.opacity = 0
            return
        action_button.disabled = False
        action_button.opacity = 1

        if num_options == 1:
            # only one option, button will correspond to that
            for option in options:
                if option.enabled:
                    action_button.text = option.text
                    self._action_button_fn = option.func
        else:
            # multiple options. button opens dropdown which has one sub-button for each
            dropdown = DropDown()
            action_button.text = _('Options')
            self._action_button_fn = dropdown.open
            for option in options:
                if option.enabled:
                    btn = Button(text=option.text, size_hint_y=None, height=48)
                    btn.bind(on_release=option.func)
                    dropdown.add_widget(btn)
コード例 #3
0
ファイル: dropdown-simple-son.py プロジェクト: mbaser/kivy-tr
class acilirKutu(App):

    def secim(self, nesne):
        # Önceden seçilmiş bir düğme var ise, arka plan rengini
        # ön tanımlı renge dönüştürelim
        if self.acilirkutu.secim:
            self.acilirkutu.secim.background_color= [1, 1, 1, 1]
            
        self.acilirkutu.select(nesne.text)
        self.anadugme.text=nesne.text
        
        # secim özelliğine yeni nesneyi ekleyelim ve
        # arka plan rengini kırmızı yapalım
        self.acilirkutu.secim=nesne
        nesne.background_color= 1, 0, 0, 1

    def build(self):
        duzen = BoxLayout()
        self.anadugme = Button(text='Başlat', size_hint=(None, None))

        self.acilirkutu = DropDown()
        self.acilirkutu.secim=None
        
        for x in ( "Mustafa", "Dilek", "Fatih", "Melike"):
            dugme=Button(text=x, size_hint_y=None, height=25)
            dugme.bind(on_release=self.secim)
            self.acilirkutu.add_widget(dugme)

        self.anadugme.bind(on_release=self.acilirkutu.open)
        duzen.add_widget(self.anadugme)
 
        return duzen
コード例 #4
0
ファイル: inCastle.py プロジェクト: SuperToad/SmartphoneGame
	def ouvrirMenuAttaque(self):
		box = BoxLayout(orientation='vertical')
		self.fenetreAttaque = Popup(title="Attaque")
		dropdown = DropDown()
		stats = Label(text='Veuillez selectionner une cible')
		confirm = Button(text="Voir")
		attaquer = Button(text="Attaquer")
		
		for key in store:
			btn = Button(text=store.get(key)['nom'], size_hint_y=None, height=44)
			btn.bind(on_release=lambda btn: dropdown.select(btn.text))  
			dropdown.add_widget(btn)
		mainbutton = Button(text='Cible :', size_hint=(None, None))
		mainbutton.bind(on_release=dropdown.open)
		dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
		box2 = BoxLayout(orientation='horizontal')
		
		fermer = Button(text="Fermer", font_size=20)
		box.add_widget(mainbutton)
		box.add_widget(stats)
		box2.add_widget(confirm)
		box2.add_widget(attaquer)
		box.add_widget(box2)
		box.add_widget(fermer)
		self.fenetreAttaque.add_widget(box)
		mainbutton.size_hint=(1,.1)
		confirm.size_hint=(.1,.1)
		fermer.size_hint=(1,.1)
		attaquer.size_hint=(.1,.1)
		confirm.bind(on_press=lambda x: self.actualise(stats, mainbutton.text))
		attaquer.bind(on_press=lambda x: self.attaque(mainbutton.text))
		fermer.bind(on_press=self.fenetreAttaque.dismiss)
		self.fenetreAttaque.open()
コード例 #5
0
ファイル: screens.py プロジェクト: Smug28/Mobile-TetriNET
class SettingsScreen(ActionBarScreen):
    STR_SETTINGS = StringProperty()
    STR_RESET_DEFAULTS = StringProperty()
    STR_RESET_DEFAULTS_HELP = StringProperty()
    STR_RESET = StringProperty()
    STR_LANGUAGE_CHANGE = StringProperty()
    def __init__(self, **kwargs):   # inicializace
        self.root = kwargs['root']
        self.root.insertStrings.append((self, ))
        super(SettingsScreen, self).__init__(**kwargs)
        self.dropdown = DropDown()
        for index in LANGUAGES.itervalues():
            btn = Button(text=index, size_hint_y=None, height=44, font_size='24dp', font_name="font/Roboto-Regular.ttf")
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)
        self.language.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.language, 'text', x))
        self.language.bind(text=self.change)
    
    def reset_defaults(self, *args):
        # Výmaz konfiguračního souboru po stisku tlačítka reset
        self.root.Cfg = ['' for y in range(4)]
        self.root.refreshCfg()
    
    def on_pre_enter(self, *args):
        # Před vstupem na obrazovku načte jazyky
        self.language.text = LANGUAGES.get(self.root.Cfg[0])
    
    def change(self, *args):
        # Změní jazyk, znovu načte řetězce
        self.root.Cfg[0] = [y[0] for y in LANGUAGES.items() if y[1] == self.language.text][0]
        self.root.refreshCfg()
        self.root.doStrInsert()
コード例 #6
0
 def build(self):
     self.title = 'Quick-Keys'
     self.icon = '1479186122476.png'
     Window.size = (winheight, winwidth)
     parent = FloatLayout()
     #parent.size = Window.size
     for i in range(len(symbols)):
         #btn[i] = Button(text = symbols[str(i+1)], size_hint = (widspacex, widspacey), pos_hint = widspaces[i])
         #btn[i].bind(on_press = callback)
         #parent.add_widget(btn[i])
         popup[i] = Popup(title = 'replace ' + symbols[str(i + 1)] + ' with',
                          content = TextInput(text = symbols[str(i+1)],
                          multiline = False))
         #print popup[i].content.text
         popup[i].bind(on_dismiss = popup_callback) #newSymbol(str(i+1), popup[i].content.text))
         btn[i] = addbutton(symbols[str(i+1)], (widspacex, widspacey), widspaces[i], popup[i].open, parent)
     
     serports = serial_ports()
     #print len(serports)
     port = DropDown()
     for i in range(len(serports)):
         dropbtn = Button(text = serports[i], size_hint_y = None, height = 44)
         dropbtn.bind(on_release = lambda dropbtn: port.select(dropbtn.text))
         port.add_widget(dropbtn)
         
     portbtn = Button(text = ser.port, size_hint = (2/3, widspacey), pos_hint = {'x' : 0, 'y' : 0})
     portbtn.bind(on_release = port.open)
     port.bind(on_select=lambda instance, x: setattr(portbtn, 'text', x))
     parent.add_widget(portbtn)
     applybtn = addbutton('save', (1/3, widspacey), {'x' : 2/3, 'y' : 0}, callback, parent)
     #applybtn.bind(on_press = ser
     #applybtn = Button(text = 'apply', size_hint = (1/3, widspacey), pos_hint = {'x' : 2/3, 'y' : 0})
     #applybtn.bind(on_press = callback)
     #parent.add_widget(applybtn)
     return parent
コード例 #7
0
def addDetails(*args):
	print("In procedure to add details")
	gridlayout = args[0]
	btn_add = args[1]
	label = Label(text="Argument Value Type: ",color=(1,0,0,1),font_size=10)
	label2 = Label(text="Default Argument Parameter: ",color=(1,0,0,1),font_size=10)
	label3 = Label(text="Default Value",color=(1,0,0,1),font_size=10)
	textInput = TextInput(id="textInputIDForDefaultArgParameter")
	textInput2 = TextInput(id="textInputIDForDefaultValue")
	gridlayout.add_widget(label)
	btnMain = Button(text="ValueType",id="valueTypeID")	
	gridlayout.add_widget(btnMain)
	gridlayout.add_widget(label2)
	gridlayout.add_widget(textInput)
	gridlayout.add_widget(label3)
	gridlayout.add_widget(textInput2)
	kindOfValues = ['ABP','NSR','NER','STR','NBR']
	dropdown = DropDown()
	for eachType in kindOfValues:
		btn_tmp = Button(text=eachType, size_hint_y=None, height=20)
		btn_tmp.bind(on_release=lambda btn_tmp: dropdown.select(btn_tmp.text))
		dropdown.add_widget(btn_tmp)
			
	btnMain.bind(on_release=dropdown.open)
	dropdown.bind(on_select=lambda instance, x: setattr(btnMain,'text',x))
	
	btn_add.disabled = False
コード例 #8
0
  def __init__(self, widget, **kwargs):
    super(DataBindingEditor, self).__init__(**kwargs)
    dropdown = DropDown()
    
    for variable in variables:
      # when adding widgets, we need to specify the height manually (disabling
      # the size_hint_y) so the dropdown can calculate the area it needs.
      btn = Button(text='%s' % variable, size_hint_y=None, height=40)

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

      # then add the button inside the dropdown
      dropdown.add_widget(btn)

    # create a big main button
    mainbutton = Button(text=widget.variable.name, size_hint=(None, None), pos_hint={'center_x': 0.5, 'center_y': 0.5})

    # 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.).
    mainbutton.bind(on_release=dropdown.open)

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

    self.add_widget(mainbutton)
コード例 #9
0
 def addButtons(self):
     for i, button_text_label in enumerate(self.buttonList):
         temp_button = MyButton(text = button_text_label)
         #if these two colors are not redefined in the inherited class, the default is used
         temp_button.color = self.menu_color_letters
         temp_button.background_color =  [.8, .7,0, .9]
         #now add dropdown buttons
         dropdown = DropDown()
         #if in parameter settings, combine dict to string
         if i is 1:
             for y in self.paradigm_setup_values:
                 submenu_string = y+': '+str(self.paradigm_setup_values[y])
                 btn = Button(text=submenu_string, size_hint_y=None, height=44)
                 btn.background_color =  [.8, .9,.7, .9]
                 btn.bind(on_release=lambda btn: dropdown.select(btn.text))
                 dropdown.add_widget(btn)
         else:
             for submenu_string in self.menu_items[i]:
                 # when adding widgets, we need to specify the height manually (disabling
                 # the size_hint_y) so the dropdown can calculate the area it needs.
                 btn = Button(text=submenu_string, size_hint_y=None, height=44)
                 btn.background_color =  [.8, .9,.7, .9]
                 # for each button, attach a callback that will call the select() method
                 # on the dropdown. We'll pass the text of the button as the data of the
                 # selection.
                 btn.bind(on_release=lambda btn: dropdown.select(btn.text))
                 #then add the button inside the dropdown
                 dropdown.add_widget(btn)
         #bind the dropdown to the main menu button
         temp_button.bind(on_release = dropdown.open) 
         dropdown.bind(on_select=lambda instance, x: self.menu_function_handler(x))
         #get info about what has been pressed
         #dropdown.bind(on_select=lambda instance, x: setattr(temp_button, 'text', x))
         self.layout_top_menu.add_widget(temp_button)
コード例 #10
0
ファイル: dropdown.py プロジェクト: mustafa-altinisik/test2
class Uygulama(App):
    def secim(self,nesne):
        if nesne.text=="mavi":
            self.resim.color=(0,0,1,1)
        elif nesne.text=="kirmizi":
            self.resim.color=(1,0,0,1)
        elif nesne.text=="yeşil":
            self.resim.color=(0,1,0,1)
        self.dropdown.select(nesne.text)
        self.anaDugme.text=nesne.text
    def build(self):
        self.renkler=(["mavi"],["kirmizi"],["yeşil"])
        duzen=BoxLayout()
        self.dropdown=DropDown()
        self.resim=Image()
        for renk in self.renkler:
            dugme=Button(text=renk[0],size_hint_y=None,height=50)
            dugme.bind(on_relase=self.secim)
            self.dropdown.add_widget(dugme)
        self.anaDugme=Button(text="Renkler",size_hint=(None,None))
        self.anaDugme.bind(on_relase=self.dropdown.open)
        duzen.add_widget(self.anaDugme)
        duzen.add_widget(self.resim)

        return duzen
コード例 #11
0
 def __init__(self,*args,**kwargs):
     super(MenuScreen, self).__init__(*args, **kwargs)
     self.drop_down = CustomDropDown()
     notes_dropdown = ObjectProperty(None)
     dropdown = DropDown()
     notes = ['Features', 'Suggestions', 'Abbreviations', 'Miscellaneous']
     for note in notes:
         # when adding widgets, we need to specify the height manually (disabling
         # the size_hint_y) so the dropdown can calculate the area it needs.
         btn = Button(text='%r' % note, size_hint_y=None, height=30)
         # for each button, attach a callback that will call the select() method
         # on the dropdown. We'll pass the text of the button as the data of the
         # selection.
         btn.bind(on_release=lambda btn: dropdown.select(btn.text))
         # then add the button inside the dropdown
         dropdown.add_widget(btn)
     # create a big main button
     mainbutton = Button(text='Usage Notes 2', size_hint=(1, 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.).
     mainbutton.bind(on_release=dropdown.open)
     #dd_btn.bind(on_release=dropdown.open)
     # one last thing, listen for the selection in the dropdown list and
     # assign the data to the button text.
     dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
     #dropdown.bind(on_select=lambda instance, x: setattr(dd_btn, 'text', x))
     self.top_layout.add_widget(mainbutton)
コード例 #12
0
def make_dropdown(labels, callback, width = 80, line_height = 30):
    dropdown = DropDown(auto_width=False, width=width)
    for name in labels:
        btn = Button(text=str(name), size_hint_y=None, height=line_height)
        btn.bind(on_release=lambda btn: dropdown.select(btn.text))
        dropdown.add_widget(btn)
    dropdown.bind(on_select=callback)
    return dropdown
コード例 #13
0
ファイル: main.py プロジェクト: rev20/Time-Tracker
	def comment_pop(instance):
		""" Creates a Popup to Log Task into timesheet  """

		con=lite.connect('TimeTracker.db')
		with con:
		    cur=con.cursor()
		    cur.execute("SELECT DISTINCT TASK FROM Timesheet ORDER BY TASK ")
		    rows = cur.fetchall()
		    task_list=['OTHER']
		    for row in rows:
				task_list.append(row[0])
		if con:
		    con.close()
		f=FloatLayout()
		global popup1
		popup1 = Popup(title='Task Desciption',
		content=f,
		size_hint=(1.0, 0.6), size=(400, 400))
		g=GridLayout(cols=2,row_force_default=True, row_default_height=40,
					 padding=(1,0,1,0))
		g.add_widget(Label(text="SELECT TASK ",pos=(400,800)))
		global task
		task=TextInput(size_hint=(1,0.75),write_tab=False,text_size=(2,None))
		dropdown = DropDown()
		for index in range(len(rows)+1):
		    btn = Button(text=task_list[index], size_hint_y=None, height=44)
		    btn.bind(on_release=lambda btn: dropdown.select(btn.text))
		    dropdown.add_widget(btn)
		global mainbutton
		mainbutton = Button(text='TASK', size_hint=(None, None),size=(100, 44),
							pos_hint={'center_x': .5, 'center_y': .5})
		mainbutton.bind(on_release=dropdown.open)
		dropdown.bind(on_select=MyApp.select_task)
		g.add_widget(mainbutton)
		g.add_widget(Label(text="ADD TASK",pos=(400,600)))
		g.add_widget(task)
		g.add_widget(Label(text="COMMENTS",pos=(400,400)))
		global comment
		comment=TextInput(size_hint=(1,0.75),write_tab=False)
		g.add_widget(comment)
		global msg
		msg=Label(text="Please enter the task and comment to save the task \n",
				  pos=(popup1.width-350,popup1.height-200))
		comment.bind(on_text=
					 msg.setter("Please enter the task and comment to save the task \n"))
		btn1=Button(text='SAVE',size_hint=(0.2,0.1),pos=(popup1.width-350,
					popup1.height-250))
		btn1.bind(on_press=MyApp.update_timesheet)
		btn2=Button(text='CANCEL',size_hint=(0.2,0.1),
					pos=(popup1.width-50,popup1.height-250))
		f.add_widget(msg)
		f.add_widget(btn1)
		f.add_widget(btn2)
		f.add_widget(g)
		popup1.open()
		btn2.bind(on_press=popup1.dismiss)
コード例 #14
0
ファイル: kivyUpdate.py プロジェクト: riyaan/ekkamai
    def __init__(self, **kwargs):
        super(UpdateScreen, self).__init__(**kwargs)
        self.cols = 2

        dropDown = DropDown()
        for index in range(10):
            btn = Button(Text="Value %d" % index, size_hint_y=None, height=44)
            dropDown.add_widget(btn)

        self.add_widget(dropDown)
コード例 #15
0
class LeaderBoardLayout(Widget):
    def __init__(self, **kwargs):
        """ Creates the buttons, text inputs and labels to be used by the other functions
        :param kwargs:
        :return:
        """
        super(LeaderBoardLayout, self).__init__(**kwargs)
        self.choice_button = Button(text="Get results")
        self.results_label = Label(text="High scores", font_size="20sp")
        self.name_input = TextInput(text="Enter username here.", multiline=False)
        self.options_dropdown = DropDown()
        self.dropdown_button = Button(text="Select an option")
        self.dropdown_button.bind(on_release=self.options_dropdown.open)
        self.layout = GridLayout(rows=5)
        self.drop_down_options = ["Top 10 Scores", "Add New User", "Top scores for user"]
        self.selected_url = "None"

    def create_layout(self):
        """Adds the objects created in __init__ to a GridLayout and creates a drop down
        :return:
        """
        self.choice_button.bind(on_press=self.callback)

        for d in self.drop_down_options:
            btn = Button(text=d, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: self.options_dropdown.select(btn.text))
            self.options_dropdown.add_widget(btn)
        self.options_dropdown.bind(on_select=lambda instance, x: setattr(self.dropdown_button, "text", x))

        self.layout.add_widget(self.dropdown_button)
        self.layout.add_widget(self.name_input)
        self.layout.add_widget(self.choice_button)
        self.layout.add_widget(self.results_label)
        return self.layout

    def server_results(self, request, results):
        """ Outputs the request result into a label
        """
        self.results_label.text = str(results)

    def callback(self, event):
        """Depending on which drop down option was selected a request a URL is
        chosen to request data from teh server. """
        playername = self.name_input.text[:3]
        self.name_input.text = playername
        self.results_label.text = "Getting scores"

        if self.dropdown_button.text == "Top 10 Scores":
            self.selected_url = "http://bsccg04.ga.fal.io/top10.py"
        elif self.dropdown_button.text == "Add New User":
            self.selected_url = "http://bsccg04.ga.fal.io/new_user.py?playername=" + playername
        elif self.dropdown_button.text == "Top scores for user":
            self.selected_url = "http://bsccg04.ga.fal.io/users_high_score.py?playername=" + playername

        request = UrlRequest(self.selected_url, self.server_results)
コード例 #16
0
ファイル: main.py プロジェクト: GuruShiva/UIDgen
    def __init__(self, **kwargs):
        super(ApplicationDisplay, self).__init__(**kwargs)
        self.text= Label (text = str (UID_result))
        self.add_widget(self.text)


        dropdown = DropDown()




        ApplicationList = ["Gmail","Vault"]



        for index in ApplicationList:
        # when adding widgets, we need to specify the height manually (disabling
        # the size_hint_y) so the dropdown can calculate the area it needs.
           btn = Button(text=str(index), size_hint_y=None, height=44)

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

         # then add the button inside the dropdown
           dropdown.add_widget(btn)





        # create a big main button
        mainbutton = Button(text='Application Menu', size_hint=(1, None))

         # 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.).
        mainbutton.bind(on_release=dropdown.open)

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.


        dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))







        self.add_widget(mainbutton)
コード例 #17
0
 def populate_drop_down(self, entries, attribute, location):
     """Populate a drop down menu."""
     drop_down = DropDown()
     for entry in entries:
         Logger.info("populate dropdown for {}: {}"
                     "".format(attribute, entry))
         button = Button(
             text=entry.name, height=44, size_hint_y=None,
             on_release=lambda a, entry=entry:
                 setattr(self, attribute, entry))
         drop_down.add_widget(button)
     drop_down.open(location)
コード例 #18
0
ファイル: main.py プロジェクト: fitzerc/backstockmanager
 def changeSecurity(self):
     security = [1, 2, 3, 4, 5]
     #Create Dropdown
     dropdown = DropDown()
     #Fill DropDown
     for row in range(len(security)):
             btn = Button(text= str(security[row]), size_hint_y = None, height=44)
             btn.bind(on_release=lambda btn: dropdown.select(btn.text))
             dropdown.add_widget(btn)
     mainbutton = self.ids.security
     mainbutton.bind(on_release=dropdown.open)
     dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
コード例 #19
0
ファイル: main.py プロジェクト: lwiz851/uip-prog3-1
class MyDrop(App):
    def __init__(self, **kwargs):
        super(MyDrop, self).__init__(**kwargs)

        api = 'http://127.0.0.1:3000/api/1.0/places.json'
        resp = requests.get(api)
        places = []

        try:
            if not resp.status_code == 200:
                raise Exception('ApiException', 'Error found while calling the API backend')

            for data in [resp.json()[key] for key in resp.json().keys() if key == 'data']:
                for place in data:
                    places.append(place['name'])

            self.lista = tuple(places)
        except Exception as err:
            return err

    def d(self, n):
        self.dropdown.select(n.text)

    def build(self):
        self.box = FloatLayout()
        self.l = Label(pos_hint={'x': 0.5 / 2, 'center_y': 0.9},
                       size_hint=(0.5, 0.2),
                       text='[color=ff3333][b][size=35]TARIFAS DE TAXI[/b][/color]',
                       markup=True)
        self.dropdown = DropDown()

        for i in self.lista:
            b1 = Button(text=i, size_hint_y=None, height=50)
            b1.bind(on_release=self.d)
            self.dropdown.add_widget(b1)

        self.b2 = Button(pos_hint={'x': 0, 'center_y': .4},
                         size_hint=(0.5, 0.2),
                         text='[color=3333ff][size=24]ORIGEN[/color]',
                         markup=True)
        self.b2.bind(on_release=self.dropdown.open)
        self.b3 = Button(pos_hint={'x': 0.5, 'center_y': .4}, size_hint=(0.5, 0.2),
                         text='[color=3333ff][size=24]DESTINO[/color]', markup=True)
        self.b3.bind(on_release=self.dropdown.open)
        self.b_calcular = Button(pos_hint={'x': 0.5 / 2, 'center_y': .1}, size_hint=(0.5, 0.2),
                                 text='[color=3333ff][size=24]CALCULAR TARIFA[/color]', markup=True)
        self.b_calcular.bind()
        self.box.add_widget(self.b2)
        self.box.add_widget(self.b3)
        self.box.add_widget(self.b_calcular)
        self.box.add_widget(self.l)
        return self.box
コード例 #20
0
    def __init__(self, *args, **kwargs):
        super(topBar, self).__init__(*args, **kwargs)

        dropdown = DropDown()
        self.dropdown = dropdown

        os.chdir("./SavedTMs/")
        turingMachines = []
        for file in glob.glob("*.xml"):
            turingMachines.append(str(file))

        #Check that there is a file to load, if not display "No saved Files"
        if len(turingMachines) == 0:
            # the size_hint_y) so the dropdown can calculate the area it needs.
            btn = Button(text="No Saved Files", size_hint_y=None, height=30)
            # then add the button inside the dropdown
            dropdown.add_widget(btn)

        for tms in turingMachines:
            # when adding widgets, we need to specify the height manually (disabling
            # the size_hint_y) so the dropdown can calculate the area it needs.
            btn = Button(text='%s' % tms, size_hint_y=None, height=30)

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

            # then add the button inside the dropdown
            dropdown.add_widget(btn)

        # create a big main button
        mainbutton = Button(text='Load Turing Machine', size_hint=(1, 1))
        print 'load Turing Machine has been selected'
        self.mainbutton = mainbutton

        # 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.).
        mainbutton.bind(on_release=dropdown.open)
        #dd_btn.bind(on_release=dropdown.open)

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

        # USE THE BELOW CODE TO CALL METHODS FROM THIS CLASS
        dropdown.bind(on_select=lambda instance, x: self.printMeth(getattr(x,'text',x)))


        self.top_layout.add_widget(mainbutton)
コード例 #21
0
ファイル: commission.py プロジェクト: abrarisme/inversion
    def display_verbs(self):
        dropdown = DropDown()
        verbs = get_all_verbs(False)

        for verb in verbs:
            new_option = ComOption(verb)
            new_option.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(new_option)

        mainbutton = self.ids.verb
        mainbutton.text = 'Did'
        mainbutton.bind(on_release=dropdown.open)
        dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
コード例 #22
0
ファイル: main.py プロジェクト: fitzerc/backstockmanager
	def fillSubcategory(self):
		#Create Dropdown
		dropdown = DropDown()
		#Fill Dropdown
		for index in range(4):
			btn = Button(text='Value %d' % index, size_hint_y = None, height=44)
			btn.bind(on_release=lambda btn: dropdown.select(btn.text))
			dropdown.add_widget(btn)
		#Bind new text to original button
		mainbutton = self.ids.subcatDrop
		mainbutton.bind(on_release=dropdown.open)
		dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
		bsdb.close()
コード例 #23
0
ファイル: inputItem.py プロジェクト: ATT-JBO/CLC-configurator
    def showModes(self, relativeTo):
        """show the list of modes"""
        try:
            dropdown = DropDown(auto_width=True)

            btn = Button(text='Disabled', markup=True,  size_hint_y=None, height='44dp')
            btn.bind(on_press=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

            btn = Button(text='Toggle', markup=True,  size_hint_y=None, height='44dp')
            btn.bind(on_press=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

            btn = Button(text='Button', markup=True,  size_hint_y=None, height='44dp')
            btn.bind(on_press=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

            btn = Button(text='Analog', markup=True,  size_hint_y=None, height='44dp')
            btn.bind(on_press=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

            dropdown.bind(on_select=self.ModeSelected)
            dropdown.open(relativeTo)
        except Exception as e:
            showError(e)
コード例 #24
0
ファイル: main.py プロジェクト: oukiar/DevsHub
class NoteItem(BoxLayout):
    def __init__(self, **kwargs):
        super(NoteItem, self).__init__(**kwargs)
        self.dropdown = DropDown()

    def addNoteItem(self, w):
        """
        inventoryitem = Inventarios()
        inventoryitem.Clave = w.parent.txt_clave.text
        inventoryitem.Producto = w.parent.txt_producto.text
        inventoryitem.Existencias = w.parent.txt_existencias.text
        inventoryitem.Minimo = w.parent.txt_minimo.text
        inventoryitem.Maximo = w.parent.txt_maximo.text
        inventoryitem.Precio = w.parent.txt_precio.text
        inventoryitem.save()
        """

        newitem = NoteItem()
        w.text = "X"

        table = app.root.ventas.lst_note

        table.add_widget(newitem, index=len(table.layout.children))

        app.root.ventas.txt_total.text = str(float(app.root.ventas.txt_total.text) + float(w.parent.txt_total.text))

    def on_completeproduct(self, w):
        print w.text
        if len(w.text) > 2:

            self.dropdown.clear_widgets()

            # for item in app.root.inventarios:
            for item in app.root.inventarios:
                if w.text.upper() in item.Producto.upper():
                    but = WhiteButton(text=item.Producto, size_hint_y=None, height=40)
                    but.bind(on_press=self.fillProduct)
                    but.Item = item
                    self.dropdown.add_widget(but)

            self.dropdown.open(w)

    def fillProduct(self, w):

        self.txt_producto.text = w.text
        self.txt_precio.text = w.Item.Precio
        if self.txt_cant.text != "":
            self.txt_total.text = str(float(self.txt_cant.text) * float(self.txt_precio.text))

        self.dropdown.dismiss()
コード例 #25
0
    def createMenu(self):
        d = DropDown()

        for user in users:
            btn = Button(text=str(user), size_hint_y=None, height=35)
            btn.bind(on_press=lambda btn: d.select(btn.text))
            d.add_widget(btn)

        self.mainbutton = Button(text="Select User", size_hint=[.4, .05], pos_hint={'x': .3, 'y': .5})
        self.mainbutton.bind(on_release=d.open)

        d.bind(on_select=lambda d, x: setattr(self.mainbutton, 'text', x))

        self.add_widget(self.mainbutton)
コード例 #26
0
ファイル: realmain.py プロジェクト: CINF/cinfdata_app
    def on_cinfdata(self, instance, value):
        """Setup the setup selection page, when the cinfdata ObjectProperty is set
        (happens only on startup)"""

        dropdown = DropDown()

        for setup in self.cinfdata.get_setups():
            btn = SetupButton(text='Setup: ' + setup['title'], size_hint_y=None,
                              height=44, setup=setup)
            btn.bind(on_release=lambda btn: dropdown.select(btn))
            dropdown.add_widget(btn)

        self.mainbutton.bind(on_release=lambda widget: dropdown.open(widget))
        dropdown.bind(on_select=self._select)
コード例 #27
0
ファイル: main.py プロジェクト: fitzerc/backstockmanager
	def fillToteSize(self):
		bsdb = sqlite3.connect('backstockdb')
		cursor = bsdb.cursor()
		sql = "SELECT value FROM miscFields WHERE param = 'toteSize'"
		
		#Create Dropdown
		dropdown = DropDown()
		#Fill DropDown
		for row in cursor.execute(sql):
			btn = Button(text=row[0], size_hint_y = None, height=44)
			btn.bind(on_release=lambda btn: dropdown.select(btn.text))
			dropdown.add_widget(btn)
		mainbutton = self.ids.toteSize
		mainbutton.bind(on_release=dropdown.open)
		dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
コード例 #28
0
def dropdown():
    dropdown = DropDown()
    for index in range(10):
        btn = Button(text= "Value %d" % index, size_hint_y= None, height=44)
        btn.bind(on_release=lambda btn: dropdown.select(btn.text))
        dropdown.add_widget(btn)

    mainbutton = Button(text='hello', size_hint=(None,None))


    mainbutton.bind(on_release=dropdown.open)


    dropdown.bind(on_select=lambda instance, x: setattr(mainbutton,'text',x))
    return dropdown
コード例 #29
0
ファイル: addpanel.py プロジェクト: yahyakesenek/Book
 def on_enter(self, *args):
     super(PanelScreen,self).on_enter(*args)
     self.entered=True
     self.selectedCat=None
     js=JsonStore("titles.json")
     titles=js.get("titles")
     drop=DropDown()
     for t in titles["all"]:
         btn=MiButton(text=titles["all"][t],size_hint_y=None,height=50,key=t)
         btn.bind(on_release=lambda btn:drop.select(btn))
         drop.add_widget(btn)
     def set_select(inst,btn):
         self.drp.text=btn.text
         self.selectedCat=btn.key
     drop.bind(on_select=set_select)
     self.drp.bind(on_release=drop.open)
コード例 #30
0
ファイル: dropdown-simple-kv.py プロジェクト: mbaser/kivy-tr
class acilirKutuKv(App):

    def secim(self, nesne):
        self.acilirkutu.select(nesne.text)
        self.root.ids.anadugme.text=nesne.text

    def build(self):
        self.root=Builder.load_string(kv)
        self.acilirkutu = DropDown()

        for x in ( "Mustafa", "Dilek", "Fatih", "Melike"):
            dugme=Button(text=x, size_hint_y=None, height=25)
            dugme.bind(on_release=self.secim)
            self.acilirkutu.add_widget(dugme)

        return self.root
コード例 #31
0
ファイル: main.py プロジェクト: Quantum-Droid/HowA-1
class MainScreen(GridLayout):
	
	def __init__(self, **kwargs):
		self.cols = 2
		self.currentMode = 'week'
		self.calendar = Calendar(self.height-60)

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

		self.bind(height=self.drawCalendar)
		self.bind(width=self.drawCalendar)
		self.drawCalendar()

	def openScreenButtons(self, instance):
		if self.openSelectScreen == False:
			self.openSelectScreen = True
			self.selectScreen.open(instance)
		else:
			self.openSelectScreen = False
			self.selectScreen.dismiss()
	
	def changeSelectText(self, value):
		self.screenMode = value
		if value == 'day':
			self.calendar.setMode('day')
			self.selectScreenButton.text = CalendarUtils.returnCurrentDate()
		else:
			self.calendar.setMode('week')
			self.selectScreenButton.text = CalendarUtils.returnCurrentMonth()
	
	def changeCurrentScreen(self, instance):
		self.openSelectScreen = False
		self.selectScreen.dismiss()
		if instance.text == 'Day mode':
			self.currentMode = 'day'
			self.calendar.setMode('day')
			self.changeSelectText('day')
		elif instance.text == 'Week mode':
			self.currentMode = 'week'
			self.calendar.setMode('week')
			self.changeSelectText('week')
		elif instance.text == 'Add activity':
			mainScreen.current = 'Activities Screen'
		elif instance.text == 'Help Screen':
			mainScreen.current = instance.text
		else:
			raise ValueError
	
	def drawCalendar(self, *l):
		self.clear_widgets()
		#Main title design
		self.leftScreen = GridLayout(rows=2, size_hint_x=None, width=int(3*self.width//5))
		self.mainTitle = BoxLayout(background_color=(9, 9, 9, 1), size_hint_y=None, height=60)
		self.selectScreen = DropDown()
		self.openSelectScreen = False
		for option in ['Day mode', 'Week mode', 'Add activity', 'Help Screen']:
			tempButton = Button(text=option, size_hint_y=None, height=60)
			tempButton.bind(on_release=self.changeCurrentScreen)
			self.selectScreen.add_widget(tempButton)
		self.selectScreenButton = Button(text='Screens', size_hint=(None, None), font_size=16, height=60, width=300)
		self.selectScreenButton.bind(on_release=self.openScreenButtons)
		self.changeSelectText(self.currentMode)
		self.mainTitle.add_widget(self.selectScreenButton)

		#Initialize Main Calendar
		self.calendar = Calendar(self.height-60)
		self.calendar.setMode(self.currentMode)
		self.mainCalendar = ScrollView()
		self.mainCalendar.add_widget(self.calendar)

		#Add the main title and the calendar to the screen
		self.leftScreen.add_widget(self.mainTitle)
		self.leftScreen.add_widget(self.mainCalendar)
		self.add_widget(self.leftScreen)

		#Initialize homeworks and projects lists
		self.rightScreen = GridLayout(cols=1)

		#Change right up screen values Homeworks
		self.rightScreen.add_widget(Button(text='Homeworks/Projects', font_size=16, size_hint_y=None, height=60))
		self.proHome = ScrollView()
		self.proHomeContent = ProHomeContent(ProHomeContent(self.height-60))
		self.proHome.add_widget(self.proHomeContent)
		self.rightScreen.add_widget(self.proHome)
		self.add_widget(self.rightScreen)
コード例 #32
0
ファイル: main.py プロジェクト: EKO135/sick_lad_cipher
    def build(self):

        # Basic Window Stuff
        Window.size = (500, 750)
        self.icon = "dog.png"
        self.title = "Super Epic Program"
        self.my_font = "ComicSansMSBold.ttf"

        # Keybinds to close, encrypt, decrypt, etc..
        Window.bind(on_keyboard=self.on_keyboard)  # bind our handler
        # Just declaring the bool for later use
        self.is_encrypt = True

        # button colors
        self.green = [0, 1, 0, 1]
        self.blue = [0, 0, 1, 1]
        self.black = [0, 0, 0, 0]
        self.white = [1, 1, 1, 1]

        # layouts in order
        superBox = BoxLayout(orientation='vertical')
        HB = BoxLayout(orientation='horizontal', size_hint=(1, 0.3), padding=2)
        VB = BoxLayout(orientation='vertical')
        HB2 = BoxLayout(padding=10,
                        spacing=20,
                        orientation='horizontal',
                        size_hint=(1, 0.5))
        VB2 = BoxLayout(orientation='vertical')
        VB3 = BoxLayout(orientation='vertical', size_hint=(1, 0.3))

        # First split the top into 4 horizontaly
        # put empty label at left and right so middle can be for title and input shifts
        # App title
        self.title_label = Label(text="SICK LAD",
                                 font_name=self.my_font,
                                 font_size=20)

        HB.add_widget(Label())
        HB.add_widget(self.title_label)

        # Create dropdown menu
        # dont need self for the delow screw what everyone says
        dropdown = DropDown()
        # Items in the menu
        shifts = [
            69420, 12345, 98765, 239234, 34343, 'custom number',
            'custom word key'
        ]
        for item in shifts:
            btn = Button(text='%r' % item, size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

        # Need self for the button so the other functions can access its text
        self.change_shift_button = Button(text='69420',
                                          size_hint=(1, 1),
                                          font_name=self.my_font,
                                          font_size=20)
        self.change_shift_button.bind(on_release=dropdown.open)
        dropdown.bind(on_select=lambda instance, x: setattr(
            self.change_shift_button, 'text', x))

        # Add that button
        HB.add_widget(self.change_shift_button)
        HB.add_widget(Label())

        # The input text
        self.input_text = TextInput(hint_text="Enter message here",
                                    multiline=True)
        VB.add_widget(self.input_text)

        # Buttons
        self.encrypt_btn = Button(text="Encrypt",
                                  background_color=self.green,
                                  font_size=25,
                                  size_hint=(1, 1))

        self.decrypt_btn = Button(text="Decrypt",
                                  background_color=self.blue,
                                  font_size=25,
                                  size_hint=(1, 1))

        # HB represents the horizontal boxlayout orientation
        self.encrypt_btn.bind(on_press=self.Crypt)
        HB2.add_widget(self.encrypt_btn)

        # there is probably a more efficient way but im used to using booleans to switch things
        self.decrypt_btn.bind(on_press=self.make_decrypt)
        self.decrypt_btn.bind(on_press=self.Crypt)
        HB2.add_widget(self.decrypt_btn)

        self.output_text = TextInput(hint_text="Output", multiline=True)
        VB2.add_widget(self.output_text)

        VB3.add_widget(
            Label(
                text=
                "No joke 100% legit best encryption software on the web (Don't check)"
            ))

        # superbox used to again align the orented widgets
        # this is nesting the layouts in another main layout
        superBox.add_widget(HB)  #title
        superBox.add_widget(VB)  #input
        superBox.add_widget(HB2)  #buttons
        superBox.add_widget(VB2)  #output
        superBox.add_widget(VB3)  #bottom

        return superBox
コード例 #33
0
class GeneScreen(Screen):

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

        # Widget Container
        screen_container = BoxLayout(orientation='vertical',
                                     padding=[1])

        # *Logo----------------------------------------------------------------
        self.logo = HomeButton()
        screen_container.add_widget(self.logo)

        # *Gene Selection Title------------------------------------------------
        screen_container.add_widget(Label(text='Gene Selection',
                                          size_hint=(1, .1),
                                          color=(0, .1, .25, .75)))

        # *Drop Down Menu------------------------------------------------------
        self.dropdown = DropDown()
        self.dropdown.bind(on_select=self.set_gene)
        self.dd_btns = []  # A list of drop down buttons for easy deletion

        #       Populate when top button hit
        self.mainbutton = CustomButton(text='Select a gene',
                                       size_hint=(1, .2))
        self.mainbutton.bind(on_release=self.load_genes)  # Populate dropdown
        self.dropdown.bind(on_select=lambda instance, x:
                           setattr(self.mainbutton, 'text', x))
        #       Place on screen
        screen_container.add_widget(self.mainbutton)

        # *Gene Buttons--------------------------------------------------------
        #       Declarations
        self.button_holder = BoxLayout(orientation='horizontal')

        #       Edit Button
        self.edit_btn = CustomButton(text="Edit",
                                     size_hint=(.3, .3))
        self.edit_btn.bind(on_release=self.switch_screen)

        #       New Button
        self.new_btn = CustomButton(text="New",
                                    size_hint=(.3, .3))
        self.new_btn.bind(on_release=self.switch_screen)

        #       Delete Button
        self.delete_btn = CustomButton(text="Delete",
                                       size_hint=(.3, .3))
        self.delete_btn.bind(on_release=self.delete)

        #       Placement
        self.button_holder.add_widget(self.edit_btn)
        self.button_holder.add_widget(self.new_btn)
        self.button_holder.add_widget(self.delete_btn)
        screen_container.add_widget(self.button_holder)  # Place Container
        #       Pack all widgets
        self.add_widget(screen_container)

        # Reset drop down when screen is loaded
        self.bind(on_enter=self.reset_menu)

    def load_genes(self, *args):
        """Called when drop down is opened"""

        self.dropdown.clear_widgets()  # Clear any packaged buttons
        del self.dd_btns[:]  # Clear drop down button list

        # Grab relevant genes
        genes = global_data.groups[global_data.active_group]

        for gene in genes:
            btn = CustomButton(text=gene.name,
                               size_hint_y=None,
                               height=self.height/9)

            btn.bind(on_release=lambda button:
                     self.dropdown.select(button.text))
            self.dropdown.add_widget(btn)  # Add button to menu
            self.dd_btns.append(btn)  # Store button in delety-list

        self.dropdown.open(args[0])

    def set_gene(self, *args):
        # Storing which group is selected for use in gene screen
        global_data.active_gene = args[1]  # args[1] - Name of gene

    def delete(self, *args):

        def delete_gene():
            group = global_data.active_group  # Get active group
            gene = global_data.active_gene  # Get active gene

            # Iterate through genes because we need to check the name of each
            for index, _gene in enumerate(global_data.groups[group]):

                if _gene.name == gene:

                    # Delete the gene
                    del global_data.groups[group][index]
                    # Remove from drop down
                    self.dropdown.remove_widget(self.dd_btns[index])
                    log(f"Gene {gene} deleted.")
                    break

            group_mngr.save_groups(global_data.groups)  # Save the groups

            global_data.active_gene = ''  # No active gene
            self.dropdown.select('Select a gene')

            popup.dismiss()

        if global_data.active_gene != '':

            # *Deletion Confirmation-------------------------------------------
            content = BoxLayout(orientation='vertical')
            content.add_widget(Label(text=f"Delete "
                                     f"{global_data.active_gene}?"))

            # *Confirmation Buttons--------------------------------------------
            options = BoxLayout(orientation='horizontal',
                                spacing=2)

            confirm_btn = CustomButton(text="Delete",  # Confirm button
                                       size_hint=(.3, .3))

            cancel_btn = CustomButton(text="Cancel",  # Cancel button
                                      size_hint=(.3, .3))
            #       Add Widgets to container
            options.add_widget(confirm_btn)
            options.add_widget(cancel_btn)
            content.add_widget(options)

            # *Popup Settings--------------------------------------------------
            popup = Popup(title="Delete?",
                          content=content,
                          size_hint=(None, None),
                          size=(400, 400),
                          separator_color=[1., 1., 1., 1.])

            confirm_btn.bind(on_press=delete_gene)
            cancel_btn.bind(on_press=popup.dismiss)

            popup.open()

    def switch_screen(*args):

        if args[1].text == "New":
            sm.current = 'editgene'

        elif args[1].text == "Edit":
            if global_data.active_gene != '':
                sm.current = 'editgene'

    def reset_menu(self, *args):
        # Need to make sure the menu text is defaulted when screen is entered
        self.dropdown.select('Select a gene')
        global_data.active_gene = ''
コード例 #34
0
    def build(self):
        # ici on creer le floatlayout

        parent = FloatLayout()
        self.painter = MyPaintWidget()
        self.painter.build()
        # Bouton clear:

        clearbtn = Button(text='Clear', font_size=35, size_hint=(0.17, 0.1), pos_hint={'x': .652, 'y': 0.9})
        clearbtn.bind(on_press=self.clear_canvas)
        # Listes :

        self.liste_trait = [1, 5, 10, 15, 20, 40, 50]
        self.liste_trait_nom = ["0", "5", "10", "15", "20", '40', '50']
        self.liste_taille_nom = ["1", '2', '3', '4', '5', '6', '7', '8', '9', '10']
        self.liste_taille = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        self.liste_couleurs = ["Jaune", "Rouge", "Vert", "Bleu", "Violet", "Noir", "Bleu Clair", ]
        self.liste_RGBA = [[1, 0.8, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0.7, 0, 0.7, 1], [0, 0, 0, 1],
                           [0, 1, 1, 1]]
        self.liste_couleur = ["Jaune", "Rouge", "Vert", "Bleu", "Violet", "Noir", "Bleu Clair", "Blanc"]
        self.liste_RGB = [[1, 0.8, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0.7, 0, 0.7, 1], [0, 0, 0, 1],
                          [0, 1, 1, 1], [1, 1, 1, 1]]

        self.Liste_Boutons_Fond = []
        self.Liste_Boutons_couleurs = []
        self.Liste_Boutons_tailles = []
        self.Liste_Boutons_traits = []

        # creation des dropdown:

        self.Bouton_couleur = Button(text='Couleur', font_size=33, size_hint=(0.18, 0.1), pos_hint={'x': .0, 'y': 0.9},
                                     background_color=[0.9, 0.9, 0.9, 1])

        dropdown = DropDown()

        for index in range(0, len(self.liste_couleurs)):
            self.Liste_Boutons_couleurs.append(Button())
            self.Liste_Boutons_couleurs[index].text = self.liste_couleurs[index]
            self.Liste_Boutons_couleurs[index].size_hint_y = None
            self.Liste_Boutons_couleurs[index].height = 60
            self.Liste_Boutons_couleurs[index].id = str(index)
            self.Liste_Boutons_couleurs[index].font_size = 32
            self.Liste_Boutons_couleurs[index].bind(on_release=lambda btn: dropdown.select(btn.text))
            self.Liste_Boutons_couleurs[index].bind(on_press=self.Couleur)

            dropdown.add_widget(self.Liste_Boutons_couleurs[index])

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

        self.Liste_Boutons_couleurs[0].color = self.liste_RGBA[0]
        self.Liste_Boutons_couleurs[1].color = self.liste_RGBA[1]
        self.Liste_Boutons_couleurs[2].color = self.liste_RGBA[2]
        self.Liste_Boutons_couleurs[3].color = self.liste_RGBA[3]
        self.Liste_Boutons_couleurs[4].color = self.liste_RGBA[4]
        self.Liste_Boutons_couleurs[5].color = self.liste_RGBA[5]
        self.Liste_Boutons_couleurs[6].color = self.liste_RGBA[6]

        self.Bouton_taille = Button(text='Taille', font_size=35, size_hint=(0.15, 0.1), pos_hint={'x': .178, 'y': 0.9},
                                    background_color=[0.9, 0.9, 0.9, 1])

        drop_down = DropDown()

        for index in range(0, len(self.liste_taille_nom)):
            self.Liste_Boutons_tailles.append(Button())
            self.Liste_Boutons_tailles[index].text = self.liste_taille_nom[index]
            self.Liste_Boutons_tailles[index].size_hint_y = None
            self.Liste_Boutons_tailles[index].height = 45
            self.Liste_Boutons_tailles[index].id = str(index)
            self.Liste_Boutons_tailles[index].bind(on_release=lambda btn: drop_down.select(btn.text))
            self.Liste_Boutons_tailles[index].bind(on_press=self.Taille)
            self.Liste_Boutons_tailles[index].font_size = 30
            drop_down.add_widget(self.Liste_Boutons_tailles[index])

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

        self.Bouton_trait = Button(text='Profondeur', font_size=23, size_hint=(0.15, 0.1),
                                   pos_hint={'x': .326, 'y': 0.9}, background_color=[0.9, 0.9, 0.9, 1])

        dropdown2 = DropDown()

        for index in range(0, len(self.liste_trait_nom)):
            self.Liste_Boutons_traits.append(Button())
            self.Liste_Boutons_traits[index].text = self.liste_trait_nom[index]
            self.Liste_Boutons_traits[index].size_hint_y = None
            self.Liste_Boutons_traits[index].height = 50
            self.Liste_Boutons_traits[index].id = str(index)
            self.Liste_Boutons_traits[index].bind(on_release=lambda btn: dropdown2.select(btn.text))
            self.Liste_Boutons_traits[index].bind(on_press=self.Trait)
            self.Liste_Boutons_traits[index].font_size = 30
            dropdown2.add_widget(self.Liste_Boutons_traits[index])

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

        self.Bouton_ScreenShot = Button(text='ScreenShot', font_size=28, size_hint=(0.18, 0.1),
                                        pos_hint={'x': .474, 'y': 0.9}, background_color=[0.7, 0.7, 0.7, 1])

        self.Bouton_ScreenShot.bind(on_press=self.photo)

        self.Bouton_Fond = Button(text='Couleur_Fond', font_size=23, size_hint=(0.18, 0.1),
                                  pos_hint={'x': .82, 'y': 0.9}, background_color=[0.9, 0.9, 0.9, 1])

        dropdown3 = DropDown()

        for index in range(0, len(self.liste_couleur)):
            self.Liste_Boutons_Fond.append(Button())
            self.Liste_Boutons_Fond[index].text = self.liste_couleur[index]
            self.Liste_Boutons_Fond[index].size_hint_y = None
            self.Liste_Boutons_Fond[index].height = 55
            self.Liste_Boutons_Fond[index].id = str(index)
            self.Liste_Boutons_Fond[index].bind(on_release=lambda btn: dropdown3.select(btn.text))
            self.Liste_Boutons_Fond[index].bind(on_press=self.Fonds)
            self.Liste_Boutons_Fond[index].font_size = 32

            dropdown3.add_widget(self.Liste_Boutons_Fond[index])

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

        self.Liste_Boutons_Fond[0].color = self.liste_RGB[0]
        self.Liste_Boutons_Fond[1].color = self.liste_RGB[1]
        self.Liste_Boutons_Fond[2].color = self.liste_RGB[2]
        self.Liste_Boutons_Fond[3].color = self.liste_RGB[3]
        self.Liste_Boutons_Fond[4].color = self.liste_RGB[4]
        self.Liste_Boutons_Fond[5].color = self.liste_RGB[5]
        self.Liste_Boutons_Fond[6].color = self.liste_RGB[6]
        self.Liste_Boutons_Fond[7].color = self.liste_RGB[7]

        # ici on integre tout au widget

        parent.add_widget(self.painter)
        parent.add_widget(self.Bouton_Fond)
        parent.add_widget(self.Bouton_taille)
        parent.add_widget(self.Bouton_couleur)
        parent.add_widget(self.Bouton_trait)
        parent.add_widget(self.Bouton_ScreenShot)
        parent.add_widget(clearbtn)

        self.size = Window.size
        self.Fond_Couleur = [1, 1, 1, 1]

        with parent.canvas.before:
            self.Fond_couleurs = Color(self.Fond_Couleur)
            self.rectangle = Rectangle(size=self.size)

        return parent
コード例 #35
0
class OptionsLay(Screen):
    """ layout zawierający możliwość zmainy opcji, czyli ścieżki pobierania narazie """
    save_btn = ObjectProperty(None)
    dir_input = ObjectProperty(None)
    channel_input = ObjectProperty(None)
    change_file_type_dropdown_main_btn = ObjectProperty(None)

    def __init__(self, layout_manager, **kwargs):
        super(OptionsLay, self).__init__(**kwargs)
        self.maked_dropdown = False
        self.layout_manager = layout_manager

    def go_return(self):
        self.layout_manager.window_manager.transition.direction = 'down'
        self.layout_manager.window_manager.current = 'menu_lay'

    def save_options(self):
        """ zapisuje opcje, jeśli zmieniono kanał to czyści załadowne opcje i blokuje pobieranie, aby uniknąć błędów """
        options_dict = JsonOperations.load_json('../data/config.json')

        options_dict['save_path'] = self.dir_input.text
        options_dict[
            'file_type'] = self.change_file_type_dropdown_main_btn.text

        if self.parse_yt_channel_name():
            self.format_channel_input()
            self.check_channel_options(self.channel_input.text)
            if options_dict['channel'] != self.channel_input.text:
                self.block_on_change_channel()
                options_dict['channel'] = self.channel_input.text

            self.save_btn.text = 'Saved'
        else:
            self.save_btn.text = 'Bad channel'
        JsonOperations.save_json(options_dict, '../data/config.json')
        Clock.schedule_once(self.change_text_save_btn, 0.8)

    def change_text_save_btn(self, _):
        self.save_btn.text = 'Save'

    def parse_yt_channel_name(self):
        """ za pomocą zewnętrznej funkcji sprawdza czy podany adres jest poprwany, czyli czy jest po  nazwie lub id """
        if parse_yt_channel_name(self.channel_input.text):
            return True
        return False

    def format_channel_input(self):
        """ odcina niepotrzebną końcówkę w adresie """
        txt = self.channel_input.text
        if len(txt.split("/")) != 5:
            self.channel_input.text = "/".join(txt.split("/")[:5])

    @staticmethod
    def check_channel_options(new_channel):
        """ jeśli nowego kanału nie ma w bazie ostanich utworów to go dodaje """
        last_track_dict = JsonOperations.load_json('../data/last_track.json')
        if new_channel not in last_track_dict.keys():
            last_track_dict[new_channel] = ''
            JsonOperations.save_json(last_track_dict,
                                     '../data/last_track.json')

    def block_on_change_channel(self):
        """ czyści liste utworów w layoucie i blokuje pobieranie przy zmianie kanału w opcjach """
        self.layout_manager.inst_main_chill_layout.clear_scroll()
        self.layout_manager.inst_main_chill_layout.un_or_block_btn(
            list_btn_to_block=[
                self.layout_manager.inst_main_chill_layout.new_download_btn,
                self.layout_manager.inst_main_chill_layout.select_songs_btn
            ],
            block=True)

    def make_options(self):
        conf_dict = DownloaderOperations.get_all_config()
        self.dir_input.text = conf_dict['save_path']
        self.channel_input.text = conf_dict['channel']
        self.change_file_type_dropdown_main_btn.text = conf_dict['file_type']
        if not self.maked_dropdown:
            self.make_dropdown()

    def make_dropdown(self):
        self.dropdown = DropDown()
        self.dropdown.dismiss_on_select = False
        for ft_name in SUPPORTED_FORMAT_TYPES:
            dd_btn = Button(
                text=ft_name,
                size_hint_y=None,
                height=50,
                background_normal='',
                border=(16, 16, 16, 16),
                background_color=[0.81640625, 0.3125, 0.43359375, 1])
            dd_btn.bind(on_release=self.release_dropdown_button)
            self.dropdown.add_widget(dd_btn)
        self.change_file_type_dropdown_main_btn.bind(
            on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, dd_main_text: setattr(
            self.change_file_type_dropdown_main_btn, 'text', dd_main_text))
        self.maked_dropdown = True

    def release_dropdown_button(self, instance):
        self.dropdown.select(instance.text)
        self.dropdown.dismiss()
コード例 #36
0
class DropDownController(BaseController):
    """A drop down type controller.
    
       The value is selected from a drop down list. """
    option_list = StringProperty('')
    options = ListProperty([])
    grey_on_zero = BooleanProperty(False)

    def sub_setup(self):
        """Creates the drop down list for the controller."""
        self.dropdown = DropDown()
        self.extra_options = []
        self._add_options_from_kivy()
        self.main_button = [
            widget for widget in self.children if isinstance(widget, Button)
        ][0]

        for option in self.options:
            btn = Button(text=option, size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.main_button.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=self._select_option)
        self.dropdown.bind(on_dismiss=self._on_dismiss)

    def _on_dismiss(self, button):
        """display selected option if dropdwon is dismissed"""
        self.display_selected()

    def _select_option(self, i, option):
        """Sets controller value to chosen option."""
        if option not in [o.name for o in self.extra_options]:
            self.value = self.options.index(option)
        else:
            for extra_option in self.extra_options:
                if option == extra_option.name:
                    if extra_option.value:
                        self.value = extra_option.value
                    else:
                        try:
                            self.value = extra_option.saved_value
                        except AttributeError:
                            self.value = extra_option.minimum

    def add_options(self, options):
        """sets list of options on the dropdown"""
        self.options = options

    def _add_options_from_kivy(self):
        """adds any extra options from kivy file"""
        for child in self.children:
            if type(child) == Option:
                self.extra_options.append(child)
                self.options.append(child.name)

    def display_selected(self):
        """Displays chosen option."""
        self.main_button.text = 'Off'
        self.main_button.state = 'normal'

        list_options = len(self.options) - len(self.extra_options)
        if list_options and 0 <= self.value < list_options:
            self.main_button.text = self.options[self.value]
            self.main_button.state = 'down'
        else:
            for option in self.extra_options:
                if option.value:
                    if self.value == option.value:
                        self.main_button.text = option.name
                        self.main_button.state = 'down'
                        break
                elif option.minimum <= self.value <= option.maximum:
                    self.main_button.text = option.name
                    self.main_button.state = 'down'
                    option.saved_value = self.value
                    break

        if self.main_button.text == 'Off'\
          or (self.grey_on_zero and not self.value):
            self.main_button.state = 'normal'
コード例 #37
0
ファイル: tangle_ui.py プロジェクト: galencm/machinic-tangle
class DropDownInput(TextInput):
    def __init__(self,
                 preload=None,
                 preload_attr=None,
                 preload_clean=True,
                 **kwargs):
        self.multiline = False
        self.drop_down = DropDown()
        self.drop_down.bind(on_select=self.on_select)
        self.bind(on_text_validate=self.add_text)
        self.preload = preload
        self.preload_attr = preload_attr
        self.preload_clean = preload_clean
        self.not_preloaded = set()
        super(DropDownInput, self).__init__(**kwargs)
        self.add_widget(self.drop_down)

    def add_text(self, *args):
        if args[0].text not in [
                btn.text for btn in self.drop_down.children[0].children
                if hasattr(btn, "text")
        ]:
            btn = Button(text=args[0].text, size_hint_y=None, height=44)
            self.drop_down.add_widget(btn)
            btn.bind(on_release=lambda btn: self.drop_down.select(btn.text))
            if "preload" not in args:
                self.not_preloaded.add(btn)

    def on_select(self, *args):
        self.text = args[1]
        if args[1] not in [
                btn.text for btn in self.drop_down.children[0].children
                if hasattr(btn, "text")
        ]:
            self.drop_down.append(Button(text=args[1]))
        # call on_text_validate after selection
        # to avoid having to select textinput and press enter
        self.dispatch("on_text_validate")

    def on_touch_down(self, touch):
        preloaded = set()
        if self.preload:
            for thing in self.preload:
                if self.preload_attr:
                    # use operator to allow dot access of attributes
                    thing_string = str(
                        operator.attrgetter(self.preload_attr)(thing))
                else:
                    thing_string = str(thing)
                self.add_text(Button(text=thing_string), "preload")
                preloaded.add(thing_string)

        # preload_clean removes entries that
        # are not in the preload source anymore
        if self.preload_clean is True:
            added_through_widget = [
                btn.text for btn in self.not_preloaded if hasattr(btn, "text")
            ]
            for btn in self.drop_down.children[0].children:
                try:
                    if (btn.text not in preloaded
                            and btn.text not in added_through_widget):
                        self.drop_down.remove_widget(btn)
                except Exception as ex:
                    pass

        return super(DropDownInput, self).on_touch_down(touch)

    def on_touch_up(self, touch):
        if touch.grab_current == self:
            self.drop_down.open(self)
        return super(DropDownInput, self).on_touch_up(touch)
コード例 #38
0
ファイル: main.py プロジェクト: stdgn/kivy-tr
class KivySQLiteApp(App):

    def build(self):
        self.recent_path=os.getcwd()
        self.cursor=None
        self.set_language('en')
        self.conn=None
        self.table_dropdown = DropDown()
        return Builder.load_file('main.kv')
          
          
          
    def newTableForm(self):
        popup=newTableForm(title=_("Create New Table"), me=self)
        popup.open()
          
          
    def showError(self, text):
        content=Label(text=text, markup=True)
        popup = Popup(title=_('Warning !'), content=content)
        popup.size_hint = (0.7,0.7)

        popup.open()

          
    def fileOpenDialog(self):
        form = fileOpenForm()
        form.open()


   


    def openDB(self, db_select):

        self.closeDB()

        try: 
            self.conn = lite.connect(db_select.selection[0])
        except:
            self.showError(_("Error open db"))
            return

        self.cursor = self.conn.cursor()
        self.update_tables_tree()
        self.root.ids.new_table_action.disabled=False
        self.root.ids.delete_table_action.disabled=False
       

        
    def update_tables_tree(self):
    
        for node in self.root.ids.table_tree.iterate_all_nodes():
    
            self.root.ids.table_tree.remove_node(node)
    
        self.table_dropdown = DropDown()
        if self.conn:
            for typ in ('table','view'):
                self.cursor.execute("SELECT name FROM sqlite_master WHERE type = '%s'" % typ)
                result=self.cursor.fetchall()
                if result:
                
                
                
                    tvlabeltext='{0} ({1})'.format( _(typ.title()+'s'), len(result) )
                    tvlabel=TreeViewLabel(text=tvlabeltext)
                    parent_node=self.root.ids.table_tree.add_node(tvlabel)
                    for tb in result:
                        tvlabel=TreeViewLabel(text=tb[0], markup=True)
                        tvlabel.tbtype=typ
                        tvlabel.tbname=tb[0]
                        tb_node=self.root.ids.table_tree.add_node(tvlabel, parent_node)
                        
                        self.cursor.execute('PRAGMA TABLE_INFO(`%s`)' % tb[0])
                        
                        #populate dropdown list in browse data tab. 
                        if not tb[0]=='sqlite_sequence':     
                            btn = Button(text=tb[0], size_hint_y=None, height=20)
                            self.table_dropdown.add_widget(btn)
                            btn.bind(on_release=lambda btn: self.table_dropdown.select(btn.text))
      
                        for field in self.cursor.fetchall():
                            tvlabeltext='[b]{0}[/b]    {1}'.format( field[1], field[2] )
                            tvlabel=TreeViewLabel(text=tvlabeltext, markup=True)               
                            self.root.ids.table_tree.add_node(tvlabel, tb_node)

            self.table_dropdown.bind(on_select=self.set_browse_data_main_button_text)
          
    def set_browse_data_main_button_text(self, instance, x):
        self.root.ids.browse_data_main_button.text=x
        self.update_data_display_grid(x)
          
    def update_data_display_grid(self, table=None):
        for cx in  self.root.ids.data_display_grid.children[:]:
            self.root.ids.data_display_grid.remove_widget(cx)
        if table:
            self.cursor.execute("SELECT rowid, * FROM `%s`" % table)
            self.root.ids.data_display_grid.cols=len(self.cursor.description)-1

            for cn in self.cursor.description[1:]:
                self.root.ids.data_display_grid.add_widget(Label(text="[b]%s[/b]" % cn[0], markup=True, size_hint=( None, None)))
            result=self.cursor.fetchmany(20)
            self.root.ids.data_display_grid.bind(minimum_width=self.root.ids.data_display_grid.setter('width'))
            for i, r in enumerate(result):
                for j,c in enumerate(r[1:]):
 
                    
                    t=TextInput(text=str(c),size_hint= (None, None), size=(200,30), multiline=False)
                    t.tablename=table
                    t.rowid=r[0]
                    t.fieldname=self.cursor.description[j+1][0]
                    t.bind(on_text_validate=self.metin)
                    self.root.ids.data_display_grid.add_widget(t)
        
        
    def metin(self, textinput):
        self.cursor.execute('UPDATE `%s` SET `%s`="%s" WHERE rowid=%d' % (textinput.tablename, textinput.fieldname, textinput.text,textinput.rowid))
        self.conn.commit()
        
        
    def deleteTableDialog(self):
        tb=self.root.ids.table_tree.selected_node
        if hasattr(tb,'tbtype'):
            form = ConfirmPopup(text=_("All data in the table you selected will be deleted!\n Are you sure you want to delete table [b]%s[/b]?") % tb.text)

            form.bind(on_answer=self.delete_table)
            form.open()
        
        
    def closeDB(self):
        if self.conn:
            self.conn.close()
            self.conn=None
            self.update_tables_tree()
            self.root.ids.delete_table_action.disabled=True
            self.root.ids.new_table_action.disabled=True
        
        
    def tree_view_expanded(self):
        pass
        
    def delete_table(self, instance, answer):
        tb=self.root.ids.table_tree.selected_node
        
        if hasattr(tb,'tbtype'):
            if answer=='yes':
                try:
                    self.cursor.execute('DROP TABLE `%s`' % tb.tbname)
                except Exception as error:
                    self.showError(_("An error occurred while droping table.\nThe message returned by sqlite engine is:")+"\n"+str(error))
                
                self.update_tables_tree()
        
        instance.dismiss()
      
    def set_language(self,selectedLanguage):
        self.t = gettext.translation('kivysqlite', 'language', languages=[selectedLanguage], fallback=True)

 
    def get_text(self, *args):
        return self.t.ugettext(*args)
コード例 #39
0
ファイル: Security.py プロジェクト: TheSociologist/PharmGUI
    def build(self):
        def SecuritySwitcher(option):
            print(option)

        SecurityScreen = Screen(name='security')
        SecurityLayout = BoxLayout(orientation='horizontal')

        GridLayout(cols=2,
                   rows=5,
                   size_hint_y=None,
                   height=400,
                   row_force_default=True,
                   col_force_default=True,
                   col_default_width=350,
                   row_default_height=45,
                   pos=(75, -90))

        SecurityMethod = Label(text="Security Method",
                               color=Black,
                               font_size=25,
                               font_name=DefaultFont,
                               halign='left',
                               disabled=False)
        SecurityMethodDropDown = DropDown()

        FingerprintOpButton = Button(text="Fingerprint",
                                     color=Black,
                                     font_size=40,
                                     font_name=DefaultFont,
                                     size_hint_y=None,
                                     height=10,
                                     background_color=Black)
        FingerprintOpButton.bind(on_press=lambda: SecurityMethodDropDown.
                                 select(FingerprintOpButton.text))

        PINOpButton = Button(text="PIN",
                             color=White,
                             font_size=40,
                             font_name=DefaultFont,
                             size_hint_y=None,
                             height=10,
                             background_color=Black)
        PINOpButton.bind(
            on_press=lambda: SecurityMethodDropDown.select(PINOpButton.text))

        PasswordOpButton = Button(text="Password",
                                  color=Black,
                                  size_hint_y=None,
                                  height=10)
        PINOpButton.bind(on_press=lambda: SecurityMethodDropDown.select(
            PasswordOpButton.text))

        MasterButton = Button(text="Options", size=(30, 30), pos=(0, 0))
        MasterButton.bind(on_press=SecurityMethodDropDown.open)

        SecurityMethodDropDown.add_widget(FingerprintOpButton)
        SecurityMethodDropDown.add_widget(PINOpButton)
        SecurityMethodDropDown.add_widget(PasswordOpButton)

        #SecurityLayout.add_widget(SecurityMethod)
        SecurityLayout.add_widget(MasterButton)
        SecurityScreen.add_widget(SecurityLayout)

        return SecurityScreen
コード例 #40
0
class MainScreen(FloatLayout):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.dropdown = DropDown()

        self.thread = None
        self.started = False
        self.testing_module = ''

        self.module = {
            '1': 'Core Module R2.2',
            '2': 'Core Module R2.3',
            '3': 'Core Module NR',
            '4': 'Climate Module',
            '5': 'PIR Module',
            '6': 'Button Module',
            '7': 'LCD Module',
            '8': 'CO2 Module',
            '9': 'GPS Module',
            '10': 'Sensor Module',
            '11': 'Relay Module',
            '12': 'Encoder Module',
            '13': 'Power Module',
            '14': 'LoRa Module',
            '15': 'Sigfox Module',
            '16': '1-Wire Module',
            '17': 'Infra Grid Module',
            '18': 'Battery Module',
            '19': 'Mini Battery Module',
            '20': 'Temperature Tag',
            '21': 'Humidity Tag',
            '22': 'Barometer Tag',
            '23': 'Lux Meter Tag',
            '24': 'NFC Tag',
            '25': 'VOC Tag',
            '26': 'VOC-LP Tag'
        }

        self.testing_sequence = {
            'Core Module R2.2': 'CoreModuleR22',
            'Core Module R2.3': 'CoreModuleR23',
            'Core Module NR': 'CoreModuleNR',
            'Climate Module': 'ClimateModule',
            'PIR Module': 'PIRModule',
            'Button Module': 'ButtonModule',
            'LCD Module': 'LCDModule',
            'CO2 Module': 'CO2Module',
            'GPS Module': 'GPSModule',
            'Sensor Module': 'SensorModule',
            'Relay Module': 'RelayModule',
            'Encoder Module': 'EncoderModule',
            'Power Module': 'PowerModule',
            'LoRa Module': 'LoRaModule',
            'Sigfox Module': 'SigfoxModule',
            '1-Wire Module': 'OneWireModule',
            'Infra Grid Module': 'InfraGridModule',
            'Battery Module': 'BatteryModule',
            'Mini Battery Module': 'MiniBatteryModule',
            'Temperature Tag': 'TemperatureTag',
            'Humidity Tag': 'HumidityTag',
            'Barometer Tag': 'BarometerTag',
            'Lux Meter Tag': 'LuxMeterTag',
            'NFC Tag': 'NFCTag',
            'VOC Tag': 'VOCTag',
            'VOC-LP Tag': 'VOC_LPTag'
        }

        self.sign = {
            '0': ['Status', [1, 1, 1, 1]],
            '1': ['', [1, 1, 1, 1]],
            '2': ['', [1, 1, 1, 1]],
            '3': ['', [1, 1, 1, 1]],
            '4': ['', [1, 1, 1, 1]],
            '5': ['', [1, 1, 1, 1]],
            '6': ['', [1, 1, 1, 1]],
            '7': ['', [1, 1, 1, 1]],
            '8': ['', [1, 1, 1, 1]],
            '9': ['', [1, 1, 1, 1]]
        }

        self.data = {
            '0': ['Waiting for choice module', [1, 1, 1, 1]],
            '1': ['', [1, 1, 1, 1]],
            '2': ['', [1, 1, 1, 1]],
            '3': ['', [1, 1, 1, 1]],
            '4': ['', [1, 1, 1, 1]],
            '5': ['', [1, 1, 1, 1]],
            '6': ['', [1, 1, 1, 1]],
            '7': ['', [1, 1, 1, 1]],
            '8': ['', [1, 1, 1, 1]],
            '9': ['', [1, 1, 1, 1]]
        }

        self.status = {
            '0': ['', [1, 0, 0, 1]],
            '1': ['', [1, 0, 0, 1]],
            '2': ['', [1, 0, 0, 1]],
            '3': ['', [1, 0, 0, 1]],
            '4': ['', [1, 0, 0, 1]],
            '5': ['', [1, 0, 0, 1]],
            '6': ['', [1, 0, 0, 1]],
            '7': ['', [1, 0, 0, 1]],
            '8': ['', [1, 0, 0, 1]],
            '9': ['', [1, 0, 0, 1]]
        }

        for x in self.module:
            btn = Button(text=self.module[x],
                         size_hint_y=None,
                         height=80,
                         font_size=30)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.mainlabel = Label(text="HARDWARIO Tester",
                               font_size=40,
                               size_hint=(1, 0.2),
                               pos_hint={
                                   'x': 0,
                                   'y': 0.8
                               })
        self.githublabel = Label(text="github.com/VPetras/bc-tester",
                                 font_size=25,
                                 size_hint=(1.6, 0.1),
                                 pos_hint={
                                     'x': 0.08,
                                     'y': 0
                                 })
        self.mainbutton = Button(text='Choice Modul which you wanna test',
                                 font_size=30,
                                 size_hint=(0.3, 0.1),
                                 pos_hint={
                                     'x': 0.01,
                                     'y': 0.75
                                 })
        self.button = Button(text='end testing',
                             font_size=30,
                             size_hint=(0.3, 0.1),
                             pos_hint={
                                 'x': 0.35,
                                 'y': 0.01
                             })
        self.button.bind(on_press=self.stop_btn)
        self.mainbutton.bind(on_release=self.dropdown.open)
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self.mainbutton, 'text', x))
        self.dropdown.bind(on_select=self.callback)
        self.add_widget(self.mainlabel)
        self.add_widget(self.githublabel)
        self.add_widget(self.mainbutton)
        self.add_widget(self.button)
        self.button.disabled = True

        self.show()
        self.update()

    def runtime_module_test(self):
        seq = self.testing_sequence[self.testing_module]
        seq = globals()[seq]()
        self.sign = seq.sign
        self.update()

        while self.started:

            print("running module test")

            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            seq.test0()

            time.sleep(1)

            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            seq.test1()
            time.sleep(1)

            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            seq.test2()
            time.sleep(1)

            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            seq.test3()
            time.sleep(1)

            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            seq.test4()
            time.sleep(1)

            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            time.sleep(1)
            seq.clean()
            self.sign = seq.sign
            self.data = seq.data
            self.status = seq.status
            self.update()

            time.sleep(1)

    def threaded_program(self):
        self.mainbutton.disabled = True
        self.button.disabled = False
        self.running = True

        print(self.testing_module)

        self.runtime_module_test()

        self.running = False
        print('thread is gone')
        self.mainbutton.disabled = False
        self.button.disabled = True
        self.erase()

    def stop(self):
        print("stoping module test")
        self.started = False

    def start(self):
        if self.started:
            return

        print('starting thread')
        self.started = True
        self.thread = threading.Thread(target=self.threaded_program, args=())
        self.thread.start()

    def stop_btn(self, x):
        print(x.text)
        self.button.disabled = True
        self.stop()

    def callback(self, instance, x):
        for i in range(len(self.module)):
            if x == self.module[str(i + 1)]:
                print(self.module[str(i + 1)])
                self.testing_module = x
                self.start()

    def show(self):
        self.sign0 = Label(text='',
                           font_size=35,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.70
                           })
        self.sign1 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.65
                           })
        self.sign2 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.60
                           })
        self.sign3 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.55
                           })
        self.sign4 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.50
                           })
        self.sign5 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.45
                           })
        self.sign6 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.40
                           })
        self.sign7 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.35
                           })
        self.sign8 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.30
                           })
        self.sign9 = Label(text='',
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.0,
                               'y': 0.25
                           })

        self.add_widget(self.sign0)
        self.add_widget(self.sign1)
        self.add_widget(self.sign2)
        self.add_widget(self.sign3)
        self.add_widget(self.sign4)
        self.add_widget(self.sign5)
        self.add_widget(self.sign6)
        self.add_widget(self.sign7)
        self.add_widget(self.sign8)
        self.add_widget(self.sign9)

        self.data0 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.7
                           })
        self.data1 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.65
                           })
        self.data2 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.60
                           })
        self.data3 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.55
                           })
        self.data4 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.50
                           })
        self.data5 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.45
                           })
        self.data6 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.40
                           })
        self.data7 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.35
                           })
        self.data8 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.30
                           })
        self.data9 = Label(text='',
                           color=[1, 0.5, 0, 1],
                           font_size=30,
                           size_hint=(1, 0.2),
                           pos_hint={
                               'x': 0.125,
                               'y': 0.25
                           })

        self.add_widget(self.data0)
        self.add_widget(self.data1)
        self.add_widget(self.data2)
        self.add_widget(self.data3)
        self.add_widget(self.data4)
        self.add_widget(self.data5)
        self.add_widget(self.data6)
        self.add_widget(self.data7)
        self.add_widget(self.data8)
        self.add_widget(self.data9)

        self.status0 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.7
                             })
        self.status1 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.65
                             })
        self.status2 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.60
                             })
        self.status3 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.55
                             })
        self.status4 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.50
                             })
        self.status5 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.45
                             })
        self.status6 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.40
                             })
        self.status7 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.35
                             })
        self.status8 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.30
                             })
        self.status9 = Label(text='',
                             color=[1, 0, 0, 1],
                             font_size=30,
                             size_hint=(1, 0.2),
                             pos_hint={
                                 'x': 0.25,
                                 'y': 0.25
                             })

        self.add_widget(self.status0)
        self.add_widget(self.status1)
        self.add_widget(self.status2)
        self.add_widget(self.status3)
        self.add_widget(self.status4)
        self.add_widget(self.status5)
        self.add_widget(self.status6)
        self.add_widget(self.status7)
        self.add_widget(self.status8)
        self.add_widget(self.status9)

    def update(self):
        self.sign0.text = self.sign['0'][0]
        self.sign1.text = self.sign['1'][0]
        self.sign2.text = self.sign['2'][0]
        self.sign3.text = self.sign['3'][0]
        self.sign4.text = self.sign['4'][0]
        self.sign5.text = self.sign['5'][0]
        self.sign6.text = self.sign['6'][0]
        self.sign7.text = self.sign['7'][0]
        self.sign8.text = self.sign['8'][0]
        self.sign9.text = self.sign['9'][0]

        self.data0.text = self.data['0'][0]
        self.data1.text = self.data['1'][0]
        self.data2.text = self.data['2'][0]
        self.data3.text = self.data['3'][0]
        self.data4.text = self.data['4'][0]
        self.data5.text = self.data['5'][0]
        self.data6.text = self.data['6'][0]
        self.data7.text = self.data['7'][0]
        self.data8.text = self.data['8'][0]
        self.data9.text = self.data['9'][0]

        #for i in range(10):
        #    data = getattr(self, 'data{}'.format(i))
        #    assert data
        #    data.text = self.data[str(i)]

        self.status0.text = self.status['0'][0]
        self.status0.color = self.status['0'][1]
        self.status1.text = self.status['1'][0]
        self.status1.color = self.status['1'][1]
        self.status2.text = self.status['2'][0]
        self.status2.color = self.status['2'][1]
        self.status3.text = self.status['3'][0]
        self.status3.color = self.status['3'][1]
        self.status4.text = self.status['4'][0]
        self.status4.color = self.status['4'][1]
        self.status5.text = self.status['5'][0]
        self.status5.color = self.status['5'][1]
        self.status6.text = self.status['6'][0]
        self.status6.color = self.status['6'][1]
        self.status7.text = self.status['7'][0]
        self.status7.color = self.status['7'][1]
        self.status8.text = self.status['8'][0]
        self.status8.color = self.status['8'][1]
        self.status9.text = self.status['9'][0]
        self.status9.color = self.status['9'][1]

    def erase(self):
        for i in range(10):
            self.sign[str(i)][0] = ''
            self.data[str(i)][0] = ''
            self.status[str(i)][0] = ''
        self.sign['0'][0] = 'Status'
        self.data['0'][0] = 'Waiting for choice module'
        self.update()
コード例 #41
0
ファイル: MONA.py プロジェクト: jeremow/MONA_Kivy
    def select_volume(self, obj):

        choose_volume_layout = FloatLayout()

        volumes = win32api.GetLogicalDriveStrings()
        volumes = volumes.split('\000')[:-1]
        for i, element in enumerate(volumes):
            volumes[i] = element.replace('/', '')

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

            btn = Button(text=volumes[i], 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.
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))

            # then add the button inside the dropdown
            dropdown.add_widget(btn)

        # create a big main button
        main_button = Button(text='Choose the Volume',
                             size_hint=(.7, .3),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .7
                             })

        # 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.).
        main_button.bind(on_release=dropdown.open)

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

        connect_btn = Button(text="Confirm selection",
                             size_hint=(.7, .3),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .3
                             })

        choose_volume_layout.add_widget(main_button)
        choose_volume_layout.add_widget(connect_btn)

        popup_volume = Popup(title='Volume chooser',
                             content=choose_volume_layout,
                             size_hint=(None, None),
                             size=(300, 200))
        popup_volume.open()

        # Attach close button press with popup.dismiss action

        connect_btn.bind(on_release=lambda info: self.connect_to_folder(
            volume=main_button.text))
コード例 #42
0
ファイル: main.py プロジェクト: scattenlaeufer/pybaccm
class NewArmyListPopup(Popup):

    army_list_name = None

    def __init__(self, army_list, **kwargs):
        super(NewArmyListPopup, self).__init__(**kwargs)
        self.army_list = army_list
        self.list_name = None
        self.nation_dropdown = DropDown()
        for nation in theater_selector_dict.keys():
            button = DropDownButton(text=nation)
            button.bind(
                on_release=lambda btn: self.nation_dropdown.select(btn.text))
            self.nation_dropdown.add_widget(button)
        self.ids["button_nation_selection"].bind(
            on_release=self.nation_dropdown.open)
        self.nation_dropdown.bind(on_select=self.set_nationality)
        self.theater_dropdown = DropDown()
        self.ids["button_theater_selector"].bind(
            on_release=self.theater_dropdown.open)
        self.theater_dropdown.bind(on_select=self.set_theater_selector)

    def set_nationality(self, instance, nationality):
        self.theater_dropdown.dismiss()
        if nationality != self.ids["button_nation_selection"].text:
            self.ids["button_nation_selection"].text = nationality
            self.ids["button_theater_selector"].text = "select"
            self.theater_dropdown.clear_widgets()
            for selector in theater_selector_dict[nationality]:
                button = DropDownButton(text=selector)
                button.bind(on_release=lambda btn: self.theater_dropdown.
                            select(btn.text))
                self.theater_dropdown.add_widget(button)

    def set_theater_selector(self, instance, theater_selector):
        self.ids["button_theater_selector"].text = theater_selector

    def cancel(self):
        self.dismiss()

    def ok(self):
        if self.ids["textinput_name"].text == "":
            MessagePopup("List With No Name",
                         "Please give your new list a name")
        elif self.ids["textinput_name"].text in self.army_list["lists"].keys():
            MessagePopup(
                "List already exist",
                "There already is a army list with the name {}".format(
                    self.ids["textinput_name"].text),
            )
        elif self.ids["button_nation_selection"].text == "select":
            MessagePopup("No nation selected", "Please select a nation.")
        elif self.ids["button_theater_selector"].text == "select":
            MessagePopup("No theater selector selected",
                         "Please select a theater selector")
        else:
            self.list_name = self.ids["textinput_name"].text
            lists_dict = self.army_list["lists"]
            lists_dict[self.list_name] = default_list_dict["lists"]["default"]
            lists_dict[self.list_name]["nationality"] = self.ids[
                "button_nation_selection"].text
            lists_dict[self.list_name]["theater_selector"] = self.ids[
                "button_theater_selector"].text
            self.army_list["lists"] = lists_dict
            self.dismiss()
コード例 #43
0
def addAtom(canv, objLocs, objSize, obj):
    x = mult * obj.fields["settings(6194)"].fields[
        "desktop_settings(612)"].fields["x(17)"]
    y = height - obj.fields["settings(6194)"].fields[
        "desktop_settings(612)"].fields["y(18)"]
    flag = 0
    name = ''
    if (len(objLocs) < obj.id):
        for i in range(obj.id - len(objLocs) + 1):
            objLocs.append((-1, -1))
            objSize.append((-1, -1))
    nameIn = obj.classname
    #values
    if nameIn == 'float_core.decimal_value_atom(289)':
        name = obj.fields["name(374)"]
        val = obj.fields["value_type(702)"].fields["default_value(891)"]
        width = 15 + 6 * len(name)
        name += '\n' + str(val)[:6]
        objSize[obj.id] = (width, 40)
        flag = 1
    elif nameIn == 'float_core.boolean_value_atom(87)':
        name = obj.fields["name(374)"]
        val = obj.fields["value_type(702)"].fields["default_value(6957)"]
        width = 15 + 6 * len(name)
        name += '\n' + str(val)
        objSize[obj.id] = (width, 40)
        flag = 1
    elif nameIn == 'float_core.indexed_value_atom(180)':
        name = obj.fields["name(374)"]
        width = 15 + 6 * len(name)
        vals = obj.fields["value_type(702)"].fields["items(393)"]
        dropdown = DropDown()
        i = 0
        for val in vals:
            btn = Button(text=val.fields["name(651)"],
                         font_size='12sp',
                         size_hint_y=None,
                         height=20)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)
            i += 1
        objSize[obj.id] = (width, 40)
        mainbutton = Button(text=name + '\n' + vals[0].fields["name(651)"],
                            font_size='12sp',
                            pos=(x, y - 40),
                            size_hint=(None, None),
                            size=objSize[obj.id])
        mainbutton.bind(on_release=dropdown.open)
        dropdown.bind(on_select=lambda instance, x: setattr(
            mainbutton, 'text', name + '\n' + x))
        canv.add_widget(mainbutton)
    elif nameIn == 'float_core.integer_value_atom(394)':
        name = obj.fields["name(374)"]
        val = obj.fields["value_type(702)"].fields["default_value(6956)"]
        width = 15 + 6 * len(name)
        name += '\n' + str(val)
        objSize[obj.id] = (width, 40)
        flag = 1
    elif nameIn == 'float_common_atoms.constant_value_atom(314)':
        name = str(obj.fields["constant_value(750)"])[:5]
        width = 15 + 6 * len(name)
        objSize[obj.id] = (width, 40)
        flag = 1
    elif nameIn == 'float_common_atoms.constant_integer_value_atom(298)':
        name = str(obj.fields["constant_value(720)"])
        width = 15 + 6 * len(name)
        objSize[obj.id] = (width, 40)
        flag = 1
    #atoms
    elif nameIn == 'float_common_atoms.nitro_atom(1721)':
        name = 'nitro'
        val = obj.fields["code(6264)"][:19]
        width = 15 + 6 * len(val)
        name += '\n' + str(val)
        objSize[obj.id] = (width, 40)
        flag = 1
    elif nameIn == 'float_common_atoms.mix_atom(301)':
        name = 'MIX'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.polyphonic_note_voice_atom(350)':
        name = 'PolyNoteVoice'
        objSize[obj.id] = (90, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.note_delay_compensation_atom(1435)':
        name = 'NoYo'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.delay_compensation_atom(1371)':
        name = 'oYo'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_core.modulation_source_atom(766)':
        name = obj.fields["name(3639)"] + '\no->'
        width = 15 + 6 * (len(name) - 4)
        objSize[obj.id] = (width, 30)
        flag = 1
    elif nameIn == 'float_core.value_led_atom(189)':
        name = 'led'
        objSize[obj.id] = (20, 20)
        flag = 1
    #other atoms
    elif nameIn == 'float_common_atoms.decimal_event_filter_atom(400)':
        name = 'decFilter'
        val1 = obj.fields["comparison(842)"]
        val2 = obj.fields["comparison_value(843)"]
        width = 15 + 6 * len(name)
        name += '\n' + str(val1) + '\n' + str(val2)
        objSize[obj.id] = (width, 60)
        flag = 1
    elif nameIn == 'float_common_atoms.multiplexer_atom(1188)':
        name = 'MUX'
        val = obj.fields["inputs(4763)"]
        objSize[obj.id] = (10 * val + 20, 30)
        name += ' ' + str(val)
        flag = 1
    elif nameIn == 'float_common_atoms.deinterleave_atom(368)':
        name = 'L/R'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.indexed_lookup_table_atom(344)':
        name = 'lookup'
        vals = obj.fields["row_data(744)"]
        length = obj.fields["row_count(743)"]
        name += '\n'
        for i in range(length):
            name += str(
                vals[i].fields["cells(726)"][0].fields["value(739)"]) + '|'
        width = 6 * (len(name) - 6)
        objSize[obj.id] = (width, 40)
        flag = 1
    #math
    elif nameIn == 'float_common_atoms.constant_add_atom(308)':
        name = '+'
        val = obj.fields["constant_value(750)"]
        name += '\n' + str(val)
        objSize[obj.id] = (40, 40)
        flag = 1
    elif nameIn == 'float_common_atoms.constant_multiply_atom(303)':
        name = 'x'
        val = obj.fields["constant_value(750)"]
        name += '\n' + str(val)[:5]
        objSize[obj.id] = (40, 40)
        flag = 1
    elif nameIn == 'float_common_atoms.add_atom(337)':
        name = '+'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.multiply_atom(367)':
        name = 'x'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.subtract_atom(343)':
        name = '-'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.multiply_add_atom(304)':
        name = 'x+'
        objSize[obj.id] = (obj.fields["multiplier_pairs(724)"] * 20 + 10, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.sum_atom(305)':
        name = '+++'
        val = obj.fields["inputs(725)"]
        name += str(val)
        objSize[obj.id] = (val * 10 + 10, 40)
        flag = 1
    #DSP
    elif nameIn == 'float_common_atoms.svf_filter_atom(578)':
        name = 'filter'
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_common_atoms.surge_classic_oscillator_atom(491)':
        name = 'surge osc'
        objSize[obj.id] = (100, 30)
        flag = 1
    #components
    elif nameIn == 'float_core.proxy_in_port_component(154)':
        name = 'IN'
        #val = obj.fields["port(301)"].fields["decorated_name(499)"]
        #name += '\n' + val
        objSize[obj.id] = (30, 30)
        flag = 1
    elif nameIn == 'float_core.proxy_out_port_component(50)':
        name = 'OUT'
        #val = obj.fields["port(301)"].fields["decorated_name(499)"]
        #name += '\n' + val
        objSize[obj.id] = (30, 30)
        y -= 300
        flag = 1
    elif nameIn == 'float_core.nested_device_chain_slot(587)':
        name = 'nest'
        val = obj.fields["name(835)"]
        name += '\n' + val
        objSize[obj.id] = (40, 40)
        flag = 1
    #everything else
    else:
        dot = 0
        paren = 0
        name = ''
        num = ''
        for i in range(len(nameIn)):
            if nameIn[i] == '(':
                paren = 1
            if dot and not paren:
                if nameIn[i] == '_':
                    name += ' '
                else:
                    name += nameIn[i]
            elif paren:
                num += nameIn[i]
            if nameIn[i] == '.':
                dot = 1
        if not name:
            name = num
        width = 8 * len(name) + 16
        objSize[obj.id] = (width, 30)
        flag = 1
    if flag:
        #canv.add_widget(DragButt(text=name, pos = (x,y-objSize[obj.id][1]), font_size='12sp', size_hint=(None, None), size=objSize[obj.id], drag_rectangle=(x, y, objSize[obj.id][0], objSize[obj.id][1]), drag_timeout=10000000, drag_distance=0))
        canv.add_widget(
            Button(text=name,
                   pos=(x, y - objSize[obj.id][1]),
                   font_size='12sp',
                   size_hint=(None, None),
                   size=objSize[obj.id]))
    objLocs[obj.id] = (x / mult, height - y)
コード例 #44
0
    def __init__(self, **kwargs):
        super(VisualSearchDesigner, self).__init__(**kwargs)
        with self.canvas.before:
            Color(.2, .2, .2, 1)
            self.rect = Rectangle(size=self.size, pos=self.pos)
        self.bind(size=self._adjustRect, pos=self._adjustRect)

        label = Label(text='Visual Search',
                      size_hint=(0.895, 0.495),
                      pos_hint={
                          'center_x': 0.45,
                          'center_y': 0.75
                      })
        self.addButton = Button(text='+',
                                size_hint=(0.095, 0.495),
                                pos_hint={
                                    'center_x': 0.95,
                                    'center_y': 0.75
                                })

        self.mainContrastButton = Button(text='1 Contrast',
                                         size_hint=(0.495, 0.495),
                                         pos_hint={
                                             'center_x': 0.25,
                                             'center_y': 0.25
                                         })
        self.mainConditionButton = Button(text='24 Stimuli',
                                          size_hint=(0.495, 0.495),
                                          pos_hint={
                                              'center_x': 0.75,
                                              'center_y': 0.25
                                          })

        self.add_widget(label)
        self.add_widget(self.addButton)
        self.add_widget(self.mainContrastButton)
        self.add_widget(self.mainConditionButton)

        dropdownContrast = DropDown()
        for s in ['1 Contrast', '2 Contrasts']:
            btn = Button(text=s,
                         size_hint_y=None,
                         height=self.mainContrastButton.height / 2)
            btn.bind(on_release=lambda btn: dropdownContrast.select(btn.text))
            dropdownContrast.add_widget(btn)
        self.mainContrastButton.bind(on_release=dropdownContrast.open)
        dropdownContrast.bind(
            on_select=lambda _, x: setattr(self.mainContrastButton, 'text', x))

        dropdownCondition = DropDown()
        for s in [
                '6 Stimuli', '12 Stimuli', '24 Stimuli', '48 Stimuli',
                '64 Stimuli'
        ]:
            btn = Button(text=s,
                         size_hint_y=None,
                         height=self.mainConditionButton.height / 2)
            btn.bind(on_release=lambda btn: dropdownCondition.select(btn.text))
            dropdownCondition.add_widget(btn)
        self.mainConditionButton.bind(on_release=dropdownCondition.open)
        dropdownCondition.bind(on_select=lambda _, x: setattr(
            self.mainConditionButton, 'text', x))
コード例 #45
0
class PlotPopup(Popup):
    '''popup containing the graph'''
    def __init__(self, x_range, y_range, plot_list, **kwargs):
        super(PlotPopup, self).__init__(**kwargs)
        self._plot_list = plot_list
        self.x_range = list(x_range)
        self.y_range = [0, y_range[1]]
        self.legend = DropDown(dismiss_on_select=False)
        self._color_list = [
            [0.2, 1.0, 0, 1], [1, 0, 0.2, 1], [0, 0.2, 1, 1],
            [0.6, 0, 0.8, 1], [1, 0.4, 0.2, 1], [1, 0.8, 0, 1],
            [0.8, 1.0, 0.1, 1]
            ]
        self.make_graph()
        self.make_legend()
    def make_graph(self):
        '''makes a graph and plots'''
        colors = itertools_cycle(self._color_list)
        y_ticks = [0.05, 0.1, 0.2, 0.5, 1, 5, 10]
        x_ticks = [1, 2, 5, 10, 20, 30, 50, 100, 200,
                   300, 500, 1000, 2000, 5000]
        for text_pts in self._plot_list:
            color_ = next(colors)
            self.ids['graph'].add_plot(MeshLinePlot(points=text_pts[1],
                                                    color=color_))
        #get numbers for graph ticks
        x_tick_num = (self.x_range[1]-self.x_range[0])/9.
        for tick in x_ticks:
            if x_tick_num < tick:
                x_tick_num = tick
                break
        y_tick_num = (self.y_range[1]-self.y_range[0])/20.
        for tick in y_ticks:
            if y_tick_num < tick:
                y_tick_num = tick
                break
        self.x_range[0] -= self.x_range[0] % x_tick_num
        #adjust font size according to tick numbers
        current = self.ids['graph'].font_size
        font_factor = 1.
        if x_tick_num > 49:
            font_factor = 0.75
        if x_tick_num > 99:
            font_factor = 0.66
        if x_tick_num > 499:
            font_factor = 0.5

        self.ids['graph'].font_size = int(font_factor * current)
        self.ids['graph'].x_ticks_major = x_tick_num
        self.ids['graph'].y_ticks_major = y_tick_num
        self.ids['graph'].xmin = self.x_range[0]
        self.ids['graph'].ymin = -y_tick_num
        self.ids['graph'].xmax = self.x_range[1]
        self.ids['graph'].ymax = self.y_range[1]
    def make_legend(self):
        '''created the dropdown menu that's called by 'legend' button'''
        colors = itertools_cycle(self._color_list)
        for text, pts in self._plot_list:
            btn = ListButton(text=text, size_hint=(None, None),
                             height=80, lst=pts, color=next(colors),
                             valign='middle')
            btn.bind(on_release=self.legend.select)
            self.legend.add_widget(btn)
        self.legend.on_select = self.flash_plot
        self.ids['legend'].bind(on_release=self.legend.open)
        self.ids['legend'].bind(on_release=self.resize)
        self.legend.bind(on_dismiss=self.shrink_button)
    def shrink_button(self, event):
        '''make legend button small again after dismiss drop down'''
        self.ids['legend'].width = self.ids['legend'].texture_size[0]
    def resize(self, *args):
        '''on release, resize drop down to fit widest button'''
        widths = [self.ids['legend'].texture_size[0]]
        for btn in self.legend.children[0].children:
            #height control for multiline buttons
            single_line_ht = btn.texture_size[1]
            lines, remainder = divmod(int(btn.texture_size[0] + 10),
                                      int(self.parent.width))
            lines += bool(remainder)
            #make long btn.text multiline
            split_at, remainder = divmod(len(btn.text), lines)
            split_at += bool(remainder)
            new_text_lst = []
            copy = btn.text
            while len(copy) > split_at:
                new_text_lst.append(copy[:split_at])
                copy = copy[split_at:]
            new_text_lst.append(copy)
            btn.text = '\n'.join(new_text_lst)

            btn.width = min(btn.texture_size[0] + 10, self.parent.width)
            btn.height = max(self.ids['legend'].height, single_line_ht * lines)
            widths.append(btn.width)
        self.ids['legend'].width = max(widths)
    def flash_plot(self, btn, second_time=False, flash_time=0.5):
        '''on press, highlight selected graph'''
        for plot in self.ids['graph'].plots:
            if plot.points == btn.lst:
                #temp_color = [1, 1, 1, 1]
                temp_color = [1-val for val in btn.color]
                temp_color[3] = 1
                self.ids['graph'].remove_plot(plot)
                new_plot = MeshLinePlot(points=btn.lst, color=temp_color)
                self.ids['graph'].add_plot(new_plot)
        if second_time:
            Clock.schedule_once(
                lambda dt: self._callback(btn, flash_time, second_time=True),
                flash_time)
        else:
            Clock.schedule_once(lambda dt: self._callback(btn, flash_time),
                                flash_time)
    def _callback(self, btn, flash_time, second_time=False):
        '''resets graph to original color'''
        for plot in self.ids['graph'].plots:
            if plot.points == btn.lst:
                plot.color = btn.color
        if not second_time:
            Clock.schedule_once(lambda dt: self.flash_plot(btn, True),
                                flash_time)
コード例 #46
0
class GameOptionsScreen(Screen):
    def __init__(self, **kwargs):
        super(GameOptionsScreen, self).__init__(**kwargs)
        self.name = 'options'

        self.home_button = Button(text='home')
        self.home_button.size_hint = (1 / 8, 1 / 12)
        self.home_button.pos_hint = {'x': 0.02, 'y': 0.02}
        self.home_button.background_color = _COLOR_1

        self.start_button = Button(text='start',
                                   size_hint=(1 / 8, 1 / 12),
                                   pos_hint={
                                       'right': 0.98,
                                       'y': 0.02
                                   },
                                   background_color=_COLOR_1)

        self.build_num_teams_drop_down()
        # self.build_question_selection_drop_down()
        self.add_widget(self.home_button)
        self.add_widget(self.start_button)

    def build_num_teams_drop_down(self):
        MAX_TEAMS = 3
        self.main_button = Button()
        self.main_button.text = "Select Number of Teams"
        self.main_button.size_hint = (0.4, 0.15)
        self.main_button.pos_hint = {'center_x': 0.5, 'top': 0.8}
        self.main_button.font_size = 30
        self.main_button.background_color = _COLOR_1

        self.drop_down = DropDown()
        for i in range(MAX_TEAMS):
            btn = Button(text=f"{i + 1}", size_hint_y=None, height=30)
            btn.bind(on_press=self.get_team_names)

            self.drop_down.add_widget(btn)

        self.main_button.bind(on_release=self.drop_down.open)
        self.drop_down.bind(
            on_select=lambda instance, x: setattr(self.main_button, 'text', x))
        self.add_widget(self.main_button)

    def get_team_names(self, instance):
        self.drop_down.select(instance.text)
        try:
            self.team_name_grid.clear_widgets()
        except:
            self.team_name_grid = GridLayout()
            self.add_widget(self.team_name_grid)

        self.team_name_grid.rows = int(instance.text)
        self.team_name_grid.size_hint = (0.3, 0.1 * int(instance.text))
        self.team_name_grid.pos_hint = {'center_x': 0.5, 'center_y': 0.5}
        for i in range(int(instance.text)):
            text = TextInput()
            text.hint_text = (f"Enter Team {i + 1} name")
            self.team_name_grid.add_widget(text)

    def update_team_names(self):
        children = self.team_name_grid.children
        self.parent.game_play.team_names = []
        self.parent.game_play.teams = []
        for child in children:
            self.parent.game_play.team_names.append(child.text)

        # make players:
        for child in children:
            plyr = player.player(f'{child.text}')
            self.parent.game_play.teams.append(plyr)

        self.parent.game_play.number_of_teams = len(
            self.parent.game_play.teams)

    def build_question_selection_drop_down(self):
        '''
        need to hook this up to QCA system to query
        all the questions that are available
        '''

        # Temp list of random names to simulate QCA querry result
        self.set_list = ['set1', 'set2', 'set3', 'set4', 'set5', 'set6']
        self.question_button = Button()
        self.question_button.text = "Select Question Set"
        self.question_button.size_hint = (0.4, 0.15)
        self.question_button.pos_hint = {'center_x': 0.5, 'top': 0.45}
        self.question_button.font_size = 30
        self.question_button.background_color = _COLOR_1

        self.question_drop_down = DropDown()
        for name in self.set_list:
            btn = Button(text=name, size_hint_y=None, height=30)
            btn.bind(
                on_press=lambda btn: self.question_drop_down.select(btn.text))
            self.question_drop_down.add_widget(btn)

        self.question_button.bind(on_release=self.question_drop_down.open)
        self.question_drop_down.bind(on_select=lambda instance, x: setattr(
            self.question_button, 'text', x))
        self.add_widget(self.question_button)
コード例 #47
0
ファイル: gui.py プロジェクト: trashtatur/cliff-sarsa-python
class GameGridApp(App):
    def __init__(self, c, r, **kwargs):
        super().__init__(**kwargs)
        self.grid = GridLayout(cols=c, rows=r, spacing=2)
        self.window_container = BoxLayout(orientation="vertical")
        self.config = BoxLayout(orientation="horizontal",
                                spacing=10,
                                size_hint=(1, 0.08))
        self.display = BoxLayout(id="display",
                                 orientation="horizontal",
                                 spacing=10,
                                 size_hint=(1, 0.08))
        self.is_playing = None
        self.time_delay = 0.5
        self.current_cell = None
        self.generationField = None
        self.scoreField = None
        self.exploreField = None
        self.deathField = None
        self.algoTypeField = None
        self.world = World.World(c, r)
        self.start_dropdown = DropDown()
        self.prepare_config()
        self.prepare_display()
        self.load_info_to_grid()
        self.load_windows()

    def prepare_config(self):

        pre = TextInput(id="pre",
                        hint_text="Pretraining...",
                        multiline=False,
                        input_filter="int",
                        background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.config.add_widget(pre)

        alpha = TextInput(
            id="alpha",
            hint_text="α value (=0.2)",
            multiline=False,
            input_filter="float",
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.config.add_widget(alpha)
        self.config.add_widget(
            Button(text="set α",
                   background_color=[0 / 255, 203 / 255, 255 / 255, 0.5],
                   on_press=lambda x: self.adjust_alpha(alpha.text)))

        epsilon = TextInput(
            id="explore",
            hint_text="ε value (=0.1)",
            multiline=False,
            input_filter="float",
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.config.add_widget(epsilon)
        self.config.add_widget(
            Button(text="set ε",
                   background_color=[0 / 255, 203 / 255, 255 / 255, 0.5],
                   on_press=lambda x: self.adjust_epsilon(epsilon.text)))

        gamma = TextInput(
            id="gamma",
            hint_text="γ value (=0.9)",
            multiline=False,
            input_filter="float",
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.config.add_widget(gamma)
        self.config.add_widget(
            Button(text="set γ",
                   background_color=[0 / 255, 203 / 255, 255 / 255, 0.5],
                   on_press=lambda x: self.adjust_gamma(gamma.text)))

        choose = self.build_dropdown()
        self.config.add_widget(choose)

        self.config.add_widget(
            Button(text="START",
                   background_normal='',
                   background_color=[0 / 255, 140 / 255, 165 / 255, 1],
                   on_press=lambda a: self.reset_and_start(
                       choose.text, pre.text, epsilon.text, alpha.text, gamma.
                       text)))

        self.config.add_widget(
            Button(text="PLAY/PAUSE",
                   background_normal="",
                   background_color=[0 / 255, 140 / 255, 165 / 255, 1],
                   on_press=lambda a: self.pause_resume()))

    def adjust_gamma(self, text):
        if text is not "":
            self.world.agent.ai.gamma = float(text)
            print(self.world.agent.ai.gamma)

    def adjust_alpha(self, text):
        if text is not "":
            self.world.agent.ai.alpha = float(text)

    def adjust_epsilon(self, text):
        if text is not "":
            self.world.agent.ai.epsilon = float(text)
            print(self.world.agent.ai.epsilon)

    def build_dropdown(self):

        sarsa = Button(text="sarsa",
                       height=22,
                       size_hint_y=None,
                       background_normal='',
                       background_color=[0 / 255, 140 / 255, 165 / 255, 1])

        sarsa.bind(
            on_release=lambda btn: self.start_dropdown.select(sarsa.text))

        self.start_dropdown.add_widget(sarsa)

        qlearn = Button(text="qlearn",
                        height=22,
                        size_hint_y=None,
                        background_normal='',
                        background_color=[0 / 255, 140 / 255, 165 / 255, 1])
        qlearn.bind(
            on_release=lambda btn: self.start_dropdown.select(qlearn.text))

        self.start_dropdown.add_widget(qlearn)

        choose_button = Button(
            text="Choose",
            background_normal='',
            background_color=[0 / 255, 140 / 255, 165 / 255, 1])

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

        return choose_button

    def prepare_display(self):
        self.display.add_widget(Label(text="algo"))
        self.algoTypeField = TextInput(
            id="AlgoType",
            readonly=True,
            text="",
            multiline=False,
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.display.add_widget(self.algoTypeField)

        self.display.add_widget(Label(text="gen"))
        self.generationField = TextInput(
            id="generation",
            readonly=True,
            text="0",
            multiline=False,
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.display.add_widget(self.generationField)

        self.display.add_widget(Label(text="score"))
        self.scoreField = TextInput(
            id="score",
            readonly=True,
            text="0",
            multiline=False,
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.display.add_widget(self.scoreField)

        self.display.add_widget(Label(text="deaths"))
        self.deathField = TextInput(
            id="deaths",
            readonly=True,
            text="0",
            multiline=False,
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5])
        self.display.add_widget(self.deathField)

        self.display.add_widget(Label(text="explore"))
        self.exploreField = (TextInput(
            id="explore",
            readonly=True,
            text="0",
            multiline=False,
            background_color=[0 / 255, 203 / 255, 255 / 255, 0.5]))
        self.display.add_widget(self.exploreField)

    def load_windows(self):
        self.window_container.add_widget(self.config)
        self.window_container.add_widget(self.display)
        self.window_container.add_widget(self.grid)

    def reset_and_start(self, agent_type, pretraining, epsilon, alpha, gamma):
        eps = 0.1
        al = 0.2
        ga = 0.9
        pre = 0
        if epsilon is not "":
            eps = float(epsilon)
        if alpha is not "":
            al = float(alpha)
        if gamma is not "":
            ga = float(gamma)
        if pretraining is not "":
            pre = int(pretraining)

        if agent_type is not "Choose":
            if self.is_playing is not None:
                self.is_playing.cancel()
            self.generationField.text = "0"
            self.deathField.text = "0"
            self.exploreField.text = "0"
            self.algoTypeField.text = agent_type
            self.reset_all_qvals()
            self.world.add_agent(agent_type, eps, al, ga)
            self.world.do_pretraining(pre)
            if pre is not 0:
                self.set_agent_pos(self.world.agent.cell.name)
            self.generationField.text = str(pre)
            self.update_all_qvals()
            threading.Thread(target=self.do_the_loop()).start()

    def update_display(self):
        self.deathField.text = str(self.world.agent.deaths)
        self.scoreField.text = str(self.world.agent.score)
        self.exploreField.text = str(self.world.agent.ai.explore)

    def update_callback(self, dt):
        new_cell_name = self.world.agent.update_status()
        self.set_agent_pos(new_cell_name)
        self.update_generation()
        self.update_display()
        self.update_all_qvals()

    def update_generation(self):
        gen_int = int(self.generationField.text)
        gen_int += 1
        self.generationField.text = str(gen_int)

    def pause_resume(self):
        if self.algoTypeField.text is not "":
            if self.is_playing is None:
                self.do_the_loop()
            else:
                self.is_playing.cancel()
                self.is_playing = None

    def do_the_loop(self):

        self.is_playing = Clock.schedule_interval(self.update_callback,
                                                  self.time_delay)

    def update_all_qvals(self):
        for key, value, in self.world.agent.ai.qvalues:
            qval = str(self.world.agent.ai.qvalues[key, value])
            if len(qval) > 6:
                qval = qval[:6] + ".."
            cell = self.find_cell(key)
            action = value
            cell.update_qval(action, qval)

    def reset_all_qvals(self):
        for cell in self.grid.children:
            cell.reset_qvals()

    def find_cell(self, cellname):
        for cell in self.grid.children:
            if cell.name is cellname:
                return cell
        return None

    def set_agent_pos(self, newcellname):

        for agentvalue in self.current_cell.children:

            if agentvalue.id is "Agent":
                agentvalue.id = "agentPlaceholder"
                agentvalue.background_color = [0, 0, 0, 0]

        for cell in self.grid.children:

            if cell.name is newcellname:

                self.current_cell = cell

                for agentvalue in cell.children:

                    if agentvalue.id is "agentPlaceholder":
                        agentvalue.id = "Agent"
                        agentvalue.background_color = [
                            248 / 255, 255 / 255, 0, 1
                        ]

    def load_info_to_grid(self):

        self.world.build_gamegrid()

        for cell in self.world.gamegrid:

            cell_id = None

            if cell.start:
                cell_id = "start"
            if cell.goal:
                cell_id = "goal"
            if cell.cliff:
                cell_id = "cliff"
            if cell.field:
                cell_id = "normal"

            grid_cell = GridLabelCellHolder(cell.name,
                                            id=cell_id,
                                            cols=3,
                                            rows=3)

            if cell.start:
                self.current_cell = grid_cell

            self.grid.add_widget(grid_cell)

    def build(self):
        return self.window_container
コード例 #48
0
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
dropdown = DropDown()
for index in range(10):
    btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
    btn.bind(on_release=lambda btn: dropdown.select(btn.text))
    dropdown.add_widget(btn)
mainbutton = Button(text='Hello', size_hint=(None, None))
mainbutton.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))

コード例 #49
0
    def __init__(self, **kwargs):
        super(UI,self).__init__(**kwargs)
        
        # initialize this so that we can access later on
        self.region = ""
        
        # change background color of app
        Window.clearcolor = (1,1,1,1)
        
        # By default, the size_hint is (1, 1), so a Widget will take the full size of the parent
        # here we want to make the top section narrower
        top_layout = GridLayout(cols = 3, 
                                size_hint_y = 0.2) 
        self.add_widget(top_layout)
        
        # add a placeholder image for the bottom section when app is first started
        # using self so that can access the image source and update later
        self.wimg = Image(source = 'images/Seeds in a Pot Final Version Updated.png')
        self.add_widget(self.wimg)
        
        # add label and dropdown to top (selection)
        l1 = MyLabel(text="Select Region", 
                     font_size=24,
                     #halign='left', 
                     valign='middle',
                     color = (0,0,0,1))
        top_layout.add_widget(l1)
        
        dropdown = DropDown()
        # makes use of imported module function
        region_list = database.get_regionlist(database.create_connection())
        # create an option for all the regions possible
        for index in region_list:
            btn = Button(text=index,
                         color = (0,0,0,1),
                         size_hint_y=None, 
                         height=44,
                         background_normal = '',
                         background_color = (0.7,0.7,0.9,0.9)
                         )
            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)
        # create a big main button for the dropdown (i think dropdown is somehow binded to it)
        # i used self.mainbutton here so that set_region can update its text, if not mainbutton will be undefined
        self.mainbutton = Button(text="Pls select region",
                                 color = (0,0,0,1),
                            font_size=18,
                            halign='left', 
                            valign='middle',
                            #change the button appearance
                            background_normal = 'images/button_normal.png',
                            background_down = 'images/button_down.png'
                            )
        self.mainbutton.bind(on_release=dropdown.open)
        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        dropdown.bind(on_select=self.set_region)

        top_layout.add_widget(self.mainbutton)
        
        # add confirm button next to dropdown
        cfm_btn = Button(text="Confirm",
                         color = (0,0,0,1),
                         font_size = 18, 
                         size_hint_x = 0.2,
                         background_normal = 'images/button_normal.png',
                         background_down = 'images/button_down.png')
        cfm_btn.bind(on_release = self.query) # makes use of imported module function
        top_layout.add_widget(cfm_btn)
コード例 #50
0
class GroupScreen(Screen):

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

        # Hold the widgets in a container
        screen_container = BoxLayout(orientation='vertical',
                                     padding=[1])

        # *Empowered Logo------------------------------------------------------
        self.logo = HomeButton()
        screen_container.add_widget(self.logo)

        # *Group Selection Title-----------------------------------------------
        screen_container.add_widget(Label(text='Group Selection',
                                          size_hint=(1, .1),
                                          color=(0, .1, .25, .75)))

        # *Dropdown Menu-------------------------------------------------------
        self.dropdown = DropDown()
        self.dropdown.bind(on_select=self.set_active_group)

        # On load, no group is active.
        global_data.active_group = ''
        # Store the drop down buttons for easy manipulation
        self.current_groups = {}

        #       Populate when top button hit
        self.mainbutton = CustomButton(text='Select a group',
                                       size_hint=(1, .2))

        # Populate drop down on select
        self.mainbutton.bind(on_release=self.load_groups)
        self.dropdown.bind(on_select=lambda instance, x:
                           setattr(self.mainbutton, 'text', x))
        # Place on screen
        screen_container.add_widget(self.mainbutton)

        # *Group Actions Title-------------------------------------------------
        # Declarations
        self.button_container = BoxLayout(orientation='horizontal')

        #       Edit Button
        self.edit_btn = CustomButton(text="Edit",
                                     size_hint=(.3, .3))
        self.edit_btn.bind(on_press=self.switch_screen)

        #       New Button
        self.new_btn = CustomButton(text="New",
                                    size_hint=(.3, .3))
        self.new_btn.bind(on_press=self.switch_screen)

        #       Delete Button
        self.delete_btn = CustomButton(text="Delete",
                                       size_hint=(.3, .3))
        self.delete_btn.bind(on_press=self.delete)

        # Put buttons in container
        self.button_container.add_widget(self.edit_btn)
        self.button_container.add_widget(self.new_btn)
        self.button_container.add_widget(self.delete_btn)

        # Add container to screen container
        screen_container.add_widget(self.button_container)
        # Package screen container
        self.add_widget(screen_container)
        # Make sure drop down menu gets reset
        self.bind(on_enter=self.reset_menu)

    def set_active_group(self, *args):
        # args = (<DropDown obj>, 'Methylation Pathway')
        # Storing which group is selected for use in gene screen and deletion
        global_data.active_group = args[1]

    def switch_screen(self, *args):
        # Switch screens
        if args[0].text == "Edit" and global_data.active_group != '':
            sm.current = 'gene'
        elif args[0].text == "New":
            sm.current = 'newgroup'

    def delete(self, *args):

        def delete_group(*args):

            # Get the selected group
            active_group = global_data.active_group

            # Delete it from the group dictionary
            del global_data.groups[active_group]

            log(f"Group {active_group} deleted.")

            # Overwrite the existing groups with the modified group dictionary
            group_mngr.save_groups(global_data.groups)

            # Clear the selected group
            global_data.active_group = ''
            # Remove it from the drop down menu
            self.dropdown.remove_widget(self.current_groups[active_group])
            # Set drop down menu to default
            self.dropdown.select('Select a group')

            popup.dismiss()

        # If a group is selected and delete button hit, confirm deletion
        if global_data.active_group != '':

            # *Confirmation Popup----------------------------------------------
            content = BoxLayout(orientation='vertical')
            content.add_widget(Label(text=
                                     f"Delete {global_data.active_group}?"))

            # *Popup buttons---------------------------------------------------
            options = BoxLayout(orientation='horizontal', spacing=2)

            confirm_btn = CustomButton(text="Delete",  # Confirm delete button
                                       size_hint=(.3, .3))

            cancel_btn = CustomButton(text="Cancel",  # Cancel delete button
                                      size_hint=(.3, .3))
            options.add_widget(confirm_btn)
            options.add_widget(cancel_btn)
            content.add_widget(options)

            # *Popup Attributes------------------------------------------------
            popup = Popup(title="Delete?", content=content,
                          size_hint=(None, None), size=(400, 400),
                          separator_color=[1., 1., 1., 1.])

            confirm_btn.bind(on_press=delete_group)
            cancel_btn.bind(on_press=popup.dismiss)

            popup.open()

    def load_groups(self, *args):

        self.dropdown.clear_widgets()  # Clear any packaged buttons
        self.current_groups = {}  # Clear drop down button list

        groups = global_data.groups

        for group in groups:  # Iterating through groups and adding a button
            btn = CustomButton(text=group,  # Create button
                               size_hint_y=None,
                               height=44)
            btn.bind(on_release=lambda button:
            self.dropdown.select(button.text))  # Bind drop down functionality
            self.current_groups[group] = btn
            self.dropdown.add_widget(btn)  # Put in drop down menu

        self.dropdown.open(args[0])  # Called on clicking the default button

    def reset_menu(self, *args):
        # Need to make sure the menu text is defaulted when screen is entered
        self.dropdown.select('Select a group')
        global_data.active_group = ''
        global_data.active_gene = ''
コード例 #51
0
class GeneratorScreen(BoxLayout):
    def __init__(self, **kwargs):
        def send(instance):
            self.die_result.text = str(
                random.randint(1, int(self.mainbutton.text.split('D')[1])))
            self.mid.text = ' '

        # initial set up of vertical screen setup
        super(GeneratorScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'

        # create title label at top of screen
        self.main_label = Label(text='\n[b]Easy Peasy Die Roller[/b]\n',
                                markup=True)
        self.main_label.font_size = 30
        self.main_label.size_hint_y = None
        self.main_label.bind(texture_size=self.main_label.setter('size'))
        self.add_widget(self.main_label)

        # create main display for generated backstories
        self.die_result = ColoredRectangle()
        self.die_result.text = 'Let\'s Roll!'
        self.die_result.color = (0, 0, 0, 1)
        self.die_result.font_size = 60
        self.add_widget(self.die_result)

        # create buffer area using label
        self.mid = Label(text=' ', size_hint_y=None)
        self.add_widget(self.mid)
        self.mid.bind(texture_size=self.mid.setter('size'))

        # create horizontal box for two side by side buttons
        self.horizontalBox = BoxLayout(orientation='horizontal',
                                       size_hint_y=None)
        self.add_widget(self.horizontalBox)

        # add button to copy existing text from die_result field
        # self.copy = Button(text='\nCopy die_result\n', disabled=True)
        # self.horizontalBox.add_widget(self.copy)
        # self.copy.bind(on_press=copy_text)
        # self.copy.bind(texture_size=self.horizontalBox.setter('size'))

        # create a dropdown with 10 buttons
        self.dropdown = DropDown()
        for index in [2, 4, 6, 8, 10, 12, 20, 100]:
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn = Button(text='D%d' % index, size_hint_y=None, height=44)

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

            # then add the button inside the dropdown
            self.dropdown.add_widget(btn)

        # create a big main button
        self.mainbutton = Button(text='Die Options', size_hint=(None, None))
        self.horizontalBox.add_widget(self.mainbutton)
        self.mainbutton.bind(on_release=self.dropdown.open)

        # 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.).

        # one last thing, listen for the selection in the dropdown list and
        # assign the data to the button text.
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self.mainbutton, 'text', x))
        self.dropdown.bind(on_select=lambda instance, x: setattr(
            self.generate, 'disabled', False))
        self.dropdown.bind(on_select=lambda instance, x: setattr(
            self.generate, 'text', 'Roll!'))

        # add buttom to generate new die_result in field
        self.generate = Button(text='\nPick a die to begin.\n',
                               disabled=True,
                               font_size=30)
        self.horizontalBox.add_widget(self.generate)
        self.generate.bind(on_press=send)

        # add bottom black buffer zone
        self.bottom = Label(text=' ', size_hint_y=None)
        self.add_widget(self.bottom)
        self.bottom.bind(texture_size=self.bottom.setter('size'))
コード例 #52
0
class SecondaryWindow(Screen):
    def __init__(self, **kwargs):
        # GUI from top to bottom, left to right
        super(SecondaryWindow, self).__init__(**kwargs)

        self.scroll = ScrollView(size_hint=(1, None),
                                 size=(Window.width, Window.height))
        self.scroll_btn = None

        self.scroll_grid = GridLayout(cols=2, spacing=1, size_hint_y=None)
        self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height'))

        with self.canvas:
            Color(0.2, 0.2, 0.28)
            Rectangle(size=(Window.width**2, Window.height**2))

        self.btn_live_orders = Button(size_hint_y=None,
                                      height=40,
                                      text="< Current Orders",
                                      background_color=[0.45, 0.45, 0.45, 3],
                                      on_release=self.changeWindow)
        self.scroll_grid.add_widget(self.btn_live_orders)

        self.btn_menu = Button(size_hint_y=None,
                               height=40,
                               text="Menu >",
                               background_color=[0.45, 0.45, 0.45, 3],
                               on_release=self.changeWindow)
        self.scroll_grid.add_widget(self.btn_menu)

        self.drp_date = DropDown()
        self.drp_date_check = str(datetime.date.today())
        self.drp_date_btn = Button(size_hint_y=None,
                                   height=40,
                                   text=f"{self.drp_date_check}",
                                   background_color=[0.45, 0.45, 0.45, 3],
                                   on_release=self.drp_date.open)
        self.drp_date_btn_dates = None

        self.scroll_grid.add_widget(self.drp_date_btn)

        self.popup = Popup(title='Title',
                           title_align='center',
                           content=Label(text='Text',
                                         size=(400, 400),
                                         text_size=[380, 380],
                                         halign='center',
                                         valign='center'),
                           size_hint=(None, None),
                           size=(400, 400))
        self.popup_db_list = []
        self.dropDown()

    def dropDown(self):  # Always called with __init__
        for i in range(len(screen_main.order_database_dates)):
            self.drp_date_btn_dates = Button(
                text=f"{screen_main.order_database_dates[i]}",
                size_hint_y=None,
                height=44,
                background_color=[0.45, 0.45, 0.45, 3],
                on_release=self.checkDate)
            self.drp_date.add_widget(self.drp_date_btn_dates)

    def checkDate(self, instance):
        self.drp_date_check = instance.text
        self.generateOrders()
        self.drp_date.dismiss()

    def changeWindow(self, instance):
        if 'Menu' in instance.text:
            sm.current = 'main'
            sm.transition.direction = 'left'
            self.reset()
        elif 'Orders' in instance.text:
            sm.current = 'tertiary'
            sm.transition.direction = 'right'
            self.reset()

    def reset(self):
        self.scroll_grid.clear_widgets()
        self.scroll_grid.add_widget(self.btn_live_orders)
        self.scroll_grid.add_widget(self.btn_menu)
        self.scroll_grid.add_widget(self.drp_date_btn)
        self.popup_db_list.clear()

    def popupItem(self, instance):
        num = int(instance.text.split('Order #')[-1])

        self.popup.content.text = f"{self.popup_db_list[num - 1]}"
        self.popup.title = f"Order #{num}"

        self.popup.open()

    def generateOrders(self, instance=None, text=None):
        self.reset()
        self.drp_date_btn.text = f"{self.drp_date_check}"
        count = 0

        for i in range(len(screen_main.order_database)):
            if self.drp_date_check == screen_main.order_database[i][:10]:
                self.scroll_btn = Button(text=f"Order #{(i + 1) - count}",
                                         size_hint_y=None,
                                         height=40,
                                         background_color=[1.8, 0.8, 0, 3],
                                         on_release=self.popupItem)
                self.scroll_grid.add_widget(self.scroll_btn)
                self.popup_db_list.append(screen_main.order_database[i])
            else:
                count += 1

        if len(self.scroll.children) == 0:
            self.scroll.add_widget(self.scroll_grid)
            self.add_widget(self.scroll)
コード例 #53
0
ファイル: menu.py プロジェクト: makselivanov/RTV_redactor
class Menu(BoxLayout):
    """
         Class Menu has main buttons for working with application

         Static method 'bindings' is destined for setting actions with canvas to buttons of menu

    """
    def __init__(self, canvas_, **kwargs):
        super(Menu, self).__init__(**kwargs)
        self._dropdown_color = DropDown()
        self._dropdown_width = DropDown()
        self.canvas_ = canvas_

        self._dropdown_color.add_widget(
            Button(text='%s' % _colors[0],
                   color=(0, 0, 0, 1),
                   size_hint_y=None,
                   height=44,
                   background_normal='',
                   background_color=(0, 0, 0, 1),
                   on_release=self.change_color))
        self._dropdown_color.add_widget(
            Button(text='%s' % _colors[1],
                   color=(1, 0, 0, 1),
                   size_hint_y=None,
                   height=44,
                   background_normal='',
                   background_color=(1, 0, 0, 1),
                   on_release=self.change_color))
        self._dropdown_color.add_widget(
            Button(text='%s' % _colors[2],
                   color=(0, 1, 0, 1),
                   size_hint_y=None,
                   height=44,
                   background_normal='',
                   background_color=(0, 1, 0, 1),
                   on_release=self.change_color))
        self._dropdown_color.add_widget(
            Button(text='%s' % _colors[3],
                   color=(0, 0, 1, 1),
                   size_hint_y=None,
                   height=44,
                   background_normal='',
                   background_color=(0, 0, 1, 1),
                   on_release=self.change_color))

        self._dropdown_color.bind(
            on_select=lambda instance, x: setattr(self._btn_color, 'text', x))

        for i in _widths:
            self._dropdown_width.add_widget(
                Button(text=i,
                       size_hint_y=None,
                       height=44,
                       on_release=self.change_width))

        self._dropdown_width.bind(
            on_select=lambda instance, x: setattr(self._btn_width, 'text', x))

        self._btn_save = Button(text='Save', font_size=24)
        self._btn_load = Button(text='Load', font_size=24)
        self._btn_edit = Button(text='Edit', font_size=24)
        self._btn_back = Button(text='Back', font_size=24)
        self._btn_color = Button(text='Color',
                                 font_size=24,
                                 on_release=self._dropdown_color.open)
        self._btn_width = Button(text='Width',
                                 font_size=24,
                                 on_release=self._dropdown_width.open)
        self._btn_clear = Button(text='Clear', font_size=24)

        self.add_widget(self._btn_save)
        self.add_widget(self._btn_load)
        self.add_widget(self._btn_edit)
        self.add_widget(self._btn_back)
        self.add_widget(self._btn_color)
        self.add_widget(self._btn_width)
        self.add_widget(self._btn_clear)

    def bindings(self, save=None, load=None, back=None, clear=None):
        self._btn_save.bind(on_release=save)
        self._btn_load.bind(on_release=load)
        self._btn_back.bind(on_release=back)
        self._btn_clear.bind(on_release=clear)

    def change_color(self, instance):
        self._dropdown_color.select(instance.text)
        self.canvas_.change_color(instance)

    def change_width(self, instance):
        self._dropdown_width.select(instance.text)
        self.canvas_.change_width(instance)

    def choose_eraser(self, instance):
        instance.text = 'Eraser'
        self.canvas_.pen_color = (1, 1, 1, 1)

    def empty(self, instance):
        pass
コード例 #54
0
class ImageApp(App):
    def __init__(self):
        super().__init__()
        self.outer_layout = BoxLayout(padding=10, orientation='vertical')
        self.first_in_layout = BoxLayout(padding=10,
                                         orientation='horizontal',
                                         size_hint=(1, 0.5))
        self.second_in_layout = BoxLayout(padding=10,
                                          orientation='horizontal',
                                          size_hint=(1, 0.5))
        self.third_in_layout = BoxLayout(padding=10,
                                         orientation='horizontal',
                                         size_hint=(1, 2))
        self.svd_rank_layout = AnchorLayout(anchor_x="right", anchor_y="top")
        self.svd_number_layout = AnchorLayout(anchor_x="left", anchor_y="top")
        self.hw_ratio_layout = AnchorLayout(anchor_x="right", anchor_y="top")
        self.hw_number_layout = AnchorLayout(anchor_x="left", anchor_y="top")
        self.hw_normalization_layout = AnchorLayout(anchor_x="center",
                                                    anchor_y="top")
        self.rgb_layout_1 = AnchorLayout(anchor_x="center", anchor_y="top")
        self.rgb_layout_2 = AnchorLayout(anchor_x="center", anchor_y="top")
        self.conv_choice_layout = BoxLayout(padding=0, orientation='vertical')
        self.conv_dd_layout = AnchorLayout(anchor_x="center", anchor_y="top")
        self.image_layout = AnchorLayout(anchor_x="center", anchor_y="center")
        self.reset_layout = AnchorLayout(anchor_x="right",
                                         anchor_y="center",
                                         size_hint=(0.1, 1))

        self.normalization_dropdown = DropDown()
        self.rgb_dropdown_1 = DropDown()
        self.rgb_dropdown_2 = DropDown()
        self.blur_dropdown = DropDown()
        self.e_det_dropdown = DropDown()

        self.svd_button = Button(text="SVD", on_press=self.on_svd)
        self.haar_wavelet_button = Button(text="Haar Wavelet",
                                          on_press=self.on_hw)
        self.convolution_button = Button(text="Image Convolution",
                                         on_press=self.on_conv)
        self.reset_button = Button(text="Reset",
                                   on_press=self.reset,
                                   size_hint_y=None,
                                   height=40)
        self.normalization_button = Button(text="Normalization",
                                           size_hint=(0.6, 0.6))
        self.rgb_button_1 = Button(text="RGB", size_hint=(0.6, 0.6))
        self.rgb_button_2 = Button(text="RGB", size_hint=(0.6, 0.6))
        self.blur_button = Button(text="Blur", on_press=self.on_blur)
        self.sharpen_button = Button(text="Sharpen", on_press=self.on_sharpen)
        self.e_det_button = Button(text="Edge Detection",
                                   on_press=self.on_e_det)
        self.type_button_1 = Button(text="Type", size_hint=(0.6, 0.6))
        self.type_button_2 = Button(text="Type", size_hint=(0.6, 0.6))

        self.yes_button_1 = Button(text="Yes",
                                   size_hint_y=None,
                                   height=25,
                                   on_press=self.normalization_true)
        self.yes_button_1.bind(on_release=lambda btn: self.
                               normalization_dropdown.select(btn.text))
        self.normalization_dropdown.add_widget(self.yes_button_1)
        self.no_button_1 = Button(text="No",
                                  size_hint_y=None,
                                  height=25,
                                  on_press=self.normalization_false)
        self.no_button_1.bind(on_release=lambda btn: self.
                              normalization_dropdown.select(btn.text))
        self.normalization_dropdown.add_widget(self.no_button_1)

        self.yes_button_2 = Button(text="Yes",
                                   size_hint_y=None,
                                   height=25,
                                   on_press=self.svd_rgb_true)
        self.yes_button_2.bind(
            on_release=lambda btn: self.rgb_dropdown_1.select(btn.text))
        self.rgb_dropdown_1.add_widget(self.yes_button_2)
        self.no_button_2 = Button(text="No",
                                  size_hint_y=None,
                                  height=25,
                                  on_press=self.svd_rgb_false)
        self.no_button_2.bind(
            on_release=lambda btn: self.rgb_dropdown_1.select(btn.text))
        self.rgb_dropdown_1.add_widget(self.no_button_2)

        self.yes_button_3 = Button(text="Yes",
                                   size_hint_y=None,
                                   height=25,
                                   on_press=self.hw_rgb_true)
        self.yes_button_3.bind(
            on_release=lambda btn: self.rgb_dropdown_2.select(btn.text))
        self.rgb_dropdown_2.add_widget(self.yes_button_3)
        self.no_button_3 = Button(text="No",
                                  size_hint_y=None,
                                  height=25,
                                  on_press=self.hw_rgb_false)
        self.no_button_3.bind(
            on_release=lambda btn: self.rgb_dropdown_2.select(btn.text))
        self.rgb_dropdown_2.add_widget(self.no_button_3)

        self.regular_button = Button(text="Regular Blur",
                                     size_hint_y=None,
                                     height=25,
                                     on_press=self.blur_true)
        self.regular_button.bind(
            on_release=lambda btn: self.blur_dropdown.select(btn.text))
        self.blur_dropdown.add_widget(self.regular_button)
        self.gaussian_button = Button(text="Gaussian Blur",
                                      size_hint_y=None,
                                      height=25,
                                      on_press=self.blur_false)
        self.gaussian_button.bind(
            on_release=lambda btn: self.blur_dropdown.select(btn.text))
        self.blur_dropdown.add_widget(self.gaussian_button)

        self.normalization_button.bind(
            on_release=self.normalization_dropdown.open)
        self.normalization_dropdown.bind(on_select=lambda ins, x: setattr(
            self.normalization_button, 'text', x))
        self.rgb_button_1.bind(on_release=self.rgb_dropdown_1.open)
        self.rgb_dropdown_1.bind(
            on_select=lambda ins, x: setattr(self.rgb_button_1, 'text', x))
        self.rgb_button_2.bind(on_release=self.rgb_dropdown_2.open)
        self.rgb_dropdown_2.bind(
            on_select=lambda ins, x: setattr(self.rgb_button_2, 'text', x))

        self.vertical_e_button = Button(text="Vertical Edges",
                                        size_hint_y=None,
                                        height=25,
                                        on_press=self.e_det_true)
        self.vertical_e_button.bind(
            on_release=lambda btn: self.e_det_dropdown.select(btn.text))
        self.e_det_dropdown.add_widget(self.vertical_e_button)
        self.horizontal_e_button = Button(text="Horizontal Edges",
                                          size_hint_y=None,
                                          height=25,
                                          on_press=self.e_det_false)
        self.horizontal_e_button.bind(
            on_release=lambda btn: self.e_det_dropdown.select(btn.text))
        self.e_det_dropdown.add_widget(self.horizontal_e_button)

        self.type_button_1.bind(on_release=self.blur_dropdown.open)
        self.blur_dropdown.bind(
            on_select=lambda ins, x: setattr(self.type_button_1, 'text', x))
        self.type_button_2.bind(on_release=self.e_det_dropdown.open)
        self.e_det_dropdown.bind(
            on_select=lambda ins, x: setattr(self.type_button_2, 'text', x))

        self.rank_label = Label(text="Enter rank:", size_hint=(0.5, 0.5))
        self.ratio_label = Label(text="Enter ratio:", size_hint=(0.5, 0.5))

        self.rank_input = TextInput(multiline=False, size_hint=(0.4, 0.4))
        self.rank_input.bind(text=self.rank_input_f)
        self.ratio_input = TextInput(multiline=False, size_hint=(0.4, 0.4))
        self.ratio_input.bind(text=self.ratio_input_f)

        self.file_chooser = FileChooserIconView(on_submit=self.submit_file)

        self.mode = None
        self.svd_rank = None
        self.svd_rgb = None
        self.hw_rgb = None
        self.hw_normalization = None
        self.hw_ratio = None
        self.conv_mode = None
        self.blur_mode = None
        self.e_det_mode = None
        self.num = 0

    def on_svd(self, ins):
        self.second_in_layout.clear_widgets()
        self.second_in_layout.add_widget(self.svd_rank_layout)
        self.second_in_layout.add_widget(self.svd_number_layout)
        self.second_in_layout.add_widget(self.rgb_layout_1)
        self.mode = 0

    def on_hw(self, ins):
        self.second_in_layout.clear_widgets()
        self.second_in_layout.add_widget(self.hw_ratio_layout)
        self.second_in_layout.add_widget(self.hw_number_layout)
        self.second_in_layout.add_widget(self.hw_normalization_layout)
        self.second_in_layout.add_widget(self.rgb_layout_2)
        self.mode = 1

    def on_conv(self, ins):
        self.second_in_layout.clear_widgets()
        self.second_in_layout.add_widget(self.conv_choice_layout)
        self.second_in_layout.add_widget(self.conv_dd_layout)
        self.mode = 2

    def on_blur(self, ins):
        self.conv_dd_layout.clear_widgets()
        self.conv_dd_layout.add_widget(self.type_button_1)
        self.conv_mode = 0

    def on_sharpen(self, ins):
        self.conv_dd_layout.clear_widgets()
        self.conv_mode = 1

    def on_e_det(self, ins):
        self.conv_dd_layout.clear_widgets()
        self.conv_dd_layout.add_widget(self.type_button_2)
        self.conv_mode = 2

    def reset(self, ins):
        self.third_in_layout.clear_widgets()
        self.third_in_layout.add_widget(self.file_chooser)

    def normalization_true(self, ins):
        self.hw_normalization = True

    def normalization_false(self, ins):
        self.hw_normalization = False

    def hw_rgb_true(self, ins):
        self.hw_rgb = True

    def hw_rgb_false(self, ins):
        self.hw_rgb = False

    def svd_rgb_true(self, ins):
        self.svd_rgb = True

    def svd_rgb_false(self, ins):
        self.svd_rgb = False

    def blur_true(self, ins):
        self.blur_mode = True

    def blur_false(self, ins):
        self.blur_mode = False

    def e_det_true(self, ins):
        self.e_det_mode = True

    def e_det_false(self, ins):
        self.e_det_mode = False

    def rank_input_f(self, ins, text):
        try:
            self.svd_rank = int(text)
        except ValueError:
            self.svd_rank = None

    def ratio_input_f(self, ins, text):
        try:
            self.hw_ratio = float(text)
        except ValueError:
            self.hw_ratio = None

    def submit_file(self, ins, filepath, touch):
        try:
            filepath = filepath[0]
        except IndexError():
            return None

        if filepath.endswith(".png") or filepath.endswith(".jpg"):
            if self.mode == 0:
                if None in (self.svd_rank, self.svd_rgb):
                    return None
            elif self.mode == 1:
                if None in (self.hw_ratio, self.hw_rgb, self.hw_normalization):
                    return None
            elif self.mode == 2:
                if self.conv_mode is None:
                    return None
                elif self.conv_mode == 0:
                    if self.blur_mode is None:
                        return None
                elif self.conv_mode == 2:
                    if self.e_det_mode is None:
                        return None
            else:
                return None

            if self.mode == 0:
                try:
                    self.num += 1
                    rank_approx.approx(filepath,
                                       f"output{self.num}.png",
                                       self.svd_rank,
                                       rgb=self.svd_rgb)
                    image = Image(source=f"output{self.num}.png")
                    self.image_layout.clear_widgets()
                    self.third_in_layout.clear_widgets()
                    self.image_layout.add_widget(image)
                    self.third_in_layout.add_widget(self.image_layout)
                    self.third_in_layout.add_widget(self.reset_layout)
                except Exception():
                    self.third_in_layout.clear_widgets()
                    self.third_in_layout.add_widget(self.file_chooser)
            elif self.mode == 1:
                try:
                    self.num += 1
                    haar_wavelet.compress(filepath,
                                          f"output{self.num}.png",
                                          ratio=self.hw_ratio,
                                          rgb=self.hw_rgb,
                                          normalization=self.hw_normalization)
                    image = Image(source=f"output{self.num}.png")
                    self.image_layout.clear_widgets()
                    self.third_in_layout.clear_widgets()
                    self.image_layout.add_widget(image)
                    self.third_in_layout.add_widget(self.image_layout)
                    self.third_in_layout.add_widget(self.reset_layout)
                except Exception():
                    self.third_in_layout.clear_widgets()
                    self.third_in_layout.add_widget(self.file_chooser)
            elif self.mode == 2:
                try:
                    self.num += 1
                    if self.conv_mode == 0:
                        image_convolution.blur(filepath, self.blur_mode,
                                               f"output{self.num}.png")
                    elif self.conv_mode == 1:
                        image_convolution.sharpen(filepath,
                                                  f"output{self.num}.png")
                    elif self.conv_mode == 2:
                        image_convolution.edge_detection(
                            filepath, self.e_det_mode, f"output{self.num}.png")
                    image = Image(source=f"output{self.num}.png")
                    self.image_layout.clear_widgets()
                    self.third_in_layout.clear_widgets()
                    self.image_layout.add_widget(image)
                    self.third_in_layout.add_widget(self.image_layout)
                    self.third_in_layout.add_widget(self.reset_layout)
                except Exception():
                    self.third_in_layout.clear_widgets()
                    self.third_in_layout.add_widget(self.file_chooser)

    def build(self):
        self.first_in_layout.add_widget(self.svd_button)
        self.first_in_layout.add_widget(self.haar_wavelet_button)
        self.first_in_layout.add_widget(self.convolution_button)
        self.third_in_layout.add_widget(self.file_chooser)

        self.outer_layout.add_widget(self.first_in_layout)
        self.outer_layout.add_widget(self.second_in_layout)
        self.outer_layout.add_widget(self.third_in_layout)

        self.svd_rank_layout.add_widget(self.rank_label)
        self.svd_number_layout.add_widget(self.rank_input)

        self.hw_ratio_layout.add_widget(self.ratio_label)
        self.hw_number_layout.add_widget(self.ratio_input)
        self.hw_normalization_layout.add_widget(self.normalization_button)
        self.rgb_layout_1.add_widget(self.rgb_button_1)
        self.rgb_layout_2.add_widget(self.rgb_button_2)

        self.conv_choice_layout.add_widget(self.blur_button)
        self.conv_choice_layout.add_widget(self.sharpen_button)
        self.conv_choice_layout.add_widget(self.e_det_button)

        self.reset_layout.add_widget(self.reset_button)

        return self.outer_layout
コード例 #55
0
ファイル: main.py プロジェクト: stdgn/kivy-tr
class tableField(Popup):
    def __init__(self,**kwargs):
        self.myparent=kwargs['myparent']
        super(tableField,self).__init__(**kwargs)
        self.fi=-1
        if kwargs.has_key('fi'):
            self.fi=kwargs['fi']
        
        self.ids.field_pk.disabled=False
        self.ids.field_ai.disabled=False
        self.dropdown = DropDown()
        for typ in TYPES:
            btn = Button(text=typ, size_hint_y=None, height=20)
            self.dropdown.add_widget(btn)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            
 
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.ids.field_type, 'text', x))
        
        for f in self.myparent.fields:
            
            if f[4]:

                self.ids.field_pk.disabled=True
                self.ids.field_ai.disabled=True
                break

        if self.fi > -1:
            
            self.ids.field_name.text=self.myparent.fields[self.fi][0]
            self.ids.field_type.text=self.myparent.fields[self.fi][1]
            
            self.ids.field_not.active=self.myparent.fields[self.fi][2]
            self.ids.field_pk.active=self.myparent.fields[self.fi][3]
            self.ids.field_ai.active=self.myparent.fields[self.fi][4]
            
            if self.ids.field_ai.active:
                self.ids.field_pk.disabled=False
                self.ids.field_ai.disabled=False
            


    
       
    def add_field(self):
        field_name=self.ids.field_name.text
        field_type=self.ids.field_type.text
        
        field_not=self.ids.field_not.active
        field_pk=self.ids.field_pk.active
        field_ai=self.ids.field_ai.active


        #if this is auto increment field, then make pk is false for others.
        if field_ai: 
            field_pk=True
            for f in self.myparent.fields:
                f[3]=False
        
        
        #check if field name exists
        f_exist=False
        
        if self.fi == -1:
            for f in self.myparent.fields:
                if f[0]==field_name:
                    f_exist=True
                    break
                
        
        if field_type==_('Select Type') or not field_name:
            popup = Popup(title=_('Warning !'), content=Label(text=_("You should write field name and select type")), size_hint = (0.5,0.4) )
            popup.open()
        
        elif f_exist:
            popup = Popup(title=_('Warning !'), content=Label(text=_("This field name already exists")), size_hint = (0.5,0.4) )
            popup.open()
            
        else:
            ft=[field_name, field_type, field_not, field_pk, field_ai]
            if self.fi == -1:
                self.myparent.fields.append(ft)
            else:
                self.myparent.fields[self.fi]=ft
            self.dismiss()
            
            self.myparent.update_list()
コード例 #56
0
    def __init__(self, **kwargs):
        super(Screen2, self).__init__(**kwargs)
        file_name = 'C:/Users/1995h/PycharmProjects/hackthon/egg.jpg'

        # Loads the image into memory
        with io.open(file_name, 'rb') as image_file:
            content = image_file.read()

        image = types.Image(content=content)

        # Performs label detection on the image file
        response = client.label_detection(image=image)
        labels = response.label_annotations

        mainlayout = BoxLayout(orientation='vertical', padding=15, spacing=15)
        wimg = Image(source=file_name)
        mainlayout.add_widget(wimg)

        layout = BoxLayout()

        dropdown1 = DropDown()
        for inglabel in labels:

            btn = Button(text='%s' % inglabel.description, size_hint_y=None, height=44)

            btn.bind(on_release=lambda btn: dropdown1.select(btn.text))

            dropdown1.add_widget(btn)

        # create a big main button
        labelinput = TextInput(size_hint_y=None, height=44)
        labelinput.bind(on_double_tap=lambda labelinput: dropdown1.select(labelinput.text))
        dropdown1.add_widget(labelinput)
        mainbutton1.bind(on_release=dropdown1.open)
        dropdown1.bind(on_select=lambda instance, x: setattr(mainbutton1, 'text', x))
        layout.add_widget(mainbutton1)

        layout.add_widget(textinput)

        dropdown2 = DropDown()

        btn2 = Button(text='oz', size_hint_y=None, height=44)
        btn2.bind(on_release=lambda btn2: dropdown2.select(btn2.text))
        dropdown2.add_widget(btn2)
        btn3 = Button(text='g', size_hint_y=None, height=44)
        btn3.bind(on_release=lambda btn3: dropdown2.select(btn3.text))
        dropdown2.add_widget(btn3)
        btn4 = Button(text='fl oz', size_hint_y=None, height=44)
        btn4.bind(on_release=lambda btn4: dropdown2.select(btn4.text))
        dropdown2.add_widget(btn4)
        btn5 = Button(text='# of items', size_hint_y=None, height=44)
        btn5.bind(on_release=lambda btn5: dropdown2.select(btn5.text))
        dropdown2.add_widget(btn5)

        # create a big main button
        mainbutton2 = Button(text='Units')
        mainbutton2.bind(on_release=dropdown2.open)
        dropdown2.bind(on_select=lambda instance, x: setattr(mainbutton2, 'text', x))
        layout.add_widget(mainbutton2)

        mainlayout.add_widget(layout)

        sendbtn = Button(text="Add Ingredient")
        sendbtn.bind(on_press=self.changer)
        mainlayout.add_widget(sendbtn)

        self.add_widget(mainlayout)
コード例 #57
0
    def display_matching_tiles(self):
        # Check if Wang Tiles Map in Place
        if self.wang_tiles_map:
            self.wang_tiles_map.disable_user_interaction()
        else:
            print('Wang Tiles Map does not exist!')
            return
        popup_content = FloatLayout(size_hint=(1, 1),
                                    pos_hint={
                                        'center_x': 0.5,
                                        'center_y': 0.5
                                    })

        if len(self.wang_tiles_map.tiles.keys()) < 1:
            print('No tiles found in Wang Tiles Map!')
            print('Tiles:', self.wang_tiles_map.tiles)
            return
        # Add Widgets
        popup = MatchingTiles(content=popup_content)
        main_tile = Label(pos_hint={
            'x': 0,
            'top': 1.0
        },
                          size_hint=(None, None),
                          size=(200, 33),
                          text='_',
                          markup=True,
                          valign='middle',
                          halign='left')
        main_tile.text_size = main_tile.size
        with main_tile.canvas:
            main_tile_rect = Rectangle(pos=(main_tile.pos[0] + 25,
                                            main_tile.pos[1]),
                                       size=(self.displayed_size,
                                             self.displayed_size))
        self.bind(pos=partial(self.update_lbl_rect, main_tile, main_tile_rect),
                  size=partial(self.update_lbl_rect, main_tile,
                               main_tile_rect))

        grid = GridLayout(rows=4,
                          spacing=0,
                          size_hint=(None, 1.0),
                          pos_hint={
                              'x': 0.0,
                              'y': 0.0
                          })
        north_lbl = Label(text='North\nMatches:',
                          pos_hint={
                              'x': 0,
                              'top': 0.8
                          },
                          size_hint=(0.25, 0.2))
        east_lbl = Label(text='East\nMatches:',
                         pos_hint={
                             'x': 0,
                             'top': 0.6
                         },
                         size_hint=(0.25, 0.2))
        south_lbl = Label(text='South\natches:',
                          pos_hint={
                              'x': 0,
                              'top': 0.4
                          },
                          size_hint=(0.25, 0.2))
        west_lbl = Label(text='West\nMatches:',
                         pos_hint={
                             'x': 0,
                             'top': 0.2
                         },
                         size_hint=(0.25, 0.2))
        popup_content.add_widget(north_lbl)
        popup_content.add_widget(east_lbl)
        popup_content.add_widget(south_lbl)
        popup_content.add_widget(west_lbl)

        north_box = BoxLayout(size_hint=(1, 0.25), orientation='horizontal')
        east_box = BoxLayout(size_hint=(1, 0.25), orientation='horizontal')
        south_box = BoxLayout(size_hint=(1, 0.25), orientation='horizontal')
        west_box = BoxLayout(size_hint=(1, 0.25), orientation='horizontal')
        grid.bind(minimum_width=grid.setter('width'))

        scrollview = ScrollView(size_hint=(0.8, 0.8),
                                size=popup.size,
                                do_scroll_x=True,
                                do_scroll_y=False,
                                pos_hint={
                                    'x': 0.2,
                                    'y': 0
                                })
        scrollview.add_widget(grid)
        popup_content.add_widget(scrollview)

        # Modify Specific Tile Probability
        layout_change_prob = FloatLayout(size_hint=(1, None),
                                         size=(self.parent.width, 51),
                                         pos_hint={
                                             'x': 0.0,
                                             'top': 0.9
                                         })
        lbl_prob = Label(pos_hint={
            'x': 0,
            'top': 0.9
        },
                         size_hint=(None, None),
                         size=(200, 33),
                         text='_',
                         markup=True,
                         valign='middle',
                         halign='left')
        lbl_prob.text_size = lbl_prob.size
        with lbl_prob.canvas:
            lbl_prob_rect = Rectangle(pos=(lbl_prob.pos[0] + 25,
                                           lbl_prob.pos[1]),
                                      size=(self.displayed_size,
                                            self.displayed_size))
        self.bind(pos=partial(self.update_lbl_rect, lbl_prob, lbl_prob_rect),
                  size=partial(self.update_lbl_rect, lbl_prob, lbl_prob_rect))
        input_prob = DecimalNumericInput(size_hint=(0.25, 1.0),
                                         pos_hint={
                                             'center_y': 0.5,
                                             'right': 0.9
                                         })
        btn_change_prob = MyButton(pos_hint={
            'center_y': 0.5,
            'right': 1.0
        },
                                   size_hint=(0.1, 1),
                                   text='Modify')
        # btn_change_prob.bind(on_press=partial(self.change_tile_probability, lbl_prob, main_tile.text, input_prob.text))
        #  lbl, origin_tile, tile, index, new_value
        layout_change_prob.add_widget(input_prob)
        layout_change_prob.add_widget(lbl_prob)
        layout_change_prob.add_widget(btn_change_prob)
        popup_content.add_widget(layout_change_prob)

        # Spinner to Select Specific Tile
        # spinner = Spinner(
        #     pos_hint={'right': 1.0, 'top': 1.0},
        #     size_hint=(None, None),
        #     size=(100, 33),
        #     values=sorted(self.wang_tiles_map.tiles.keys())
        # )
        # spinner.bind(text=partial(self._update_match_spinner, main_tile, main_tile_rect, grid, north_box, east_box, south_box, west_box, btn_change_prob, input_prob, lbl_prob, lbl_prob_rect))

        dropdown = DropDown(
            # pos_hint={'right': 1.0, 'top': 1.0},
            size_hint=(None, None),
            size=(100, 33),
        )

        for val in sorted(self.wang_tiles_map.tiles.keys()):
            lbl_drop = Button(text=val, size_hint_y=None, height=44)

            with lbl_drop.canvas:
                lbl_drop_rect = Rectangle(pos=(lbl_drop.pos[0] + 10,
                                               lbl_drop.pos[1]),
                                          size=(self.displayed_size,
                                                self.displayed_size))
            grid.bind(pos=partial(self.update_lbl_rect, lbl_drop,
                                  lbl_drop_rect),
                      size=partial(self.update_lbl_rect, lbl_drop,
                                   lbl_drop_rect))
            lbl_drop_rect.texture = self.wang_tiles_map.tiles[val]
            lbl_drop.bind(
                on_release=lambda lbl_drop: dropdown.select(lbl_drop.text))
            dropdown.add_widget(lbl_drop)
            Clock.schedule_once(
                partial(self.update_lbl_rect, lbl_drop, lbl_drop_rect), .05)

        dropdown.bind(on_select=partial(
            self._update_match_spinner, main_tile, main_tile_rect, grid,
            north_box, east_box, south_box, west_box, btn_change_prob,
            input_prob, lbl_prob, lbl_prob_rect))
        dropdownbtn = Button(text='Tiles!',
                             pos_hint={
                                 'right': 1.0,
                                 'top': 1.0
                             },
                             size_hint=(None, None),
                             size=(100, 33))
        dropdownbtn.bind(on_release=dropdown.open)
        dropdown.bind(
            on_select=lambda instance, x: setattr(dropdownbtn, 'text', x))
        popup_content.add_widget(main_tile)
        # popup_content.add_widget(spinner)
        popup_content.add_widget(dropdown)
        popup_content.add_widget(dropdownbtn)
        popup.bind(on_dismiss=self.wang_tiles_map.enable_user_interaction)
        popup.open()
        Clock.schedule_once(
            partial(self.update_lbl_rect, main_tile, main_tile_rect), 0.05)
        Clock.schedule_once(
            partial(self.update_lbl_rect, lbl_prob, lbl_prob_rect), 0.05)
コード例 #58
0
    def build(self):
        layout = GridLayout(cols=4)

        self.label1 = Label(text="Age")
        layout.add_widget(self.label1)
        self.age_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.age_taste)

        self.label2 = Label(text="Gender")
        layout.add_widget(self.label2)
        dropdown_gender = DropDown()
        btn_male = Button(text='Male', size_hint_y=None, height=30)
        btn_male.bind(
            on_release=lambda btn: dropdown_gender.select(btn_male.text))
        dropdown_gender.add_widget(btn_male)
        btn_female = Button(text='Female', size_hint_y=None, height=30)
        btn_female.bind(
            on_release=lambda btn: dropdown_gender.select(btn_female.text))
        dropdown_gender.add_widget(btn_female)
        button_gender.bind(on_release=dropdown_gender.open)
        dropdown_gender.bind(
            on_select=lambda instance, x: setattr(button_gender, 'text', x))
        layout.add_widget(button_gender)

        self.label3 = Label(text="Income")
        layout.add_widget(self.label3)
        self.income_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.income_taste)

        self.label4 = Label(text="Budget")
        layout.add_widget(self.label4)
        self.budget_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.budget_taste)

        self.label5 = Label(text="Recent Visit")
        layout.add_widget(self.label5)
        dropdown_rv1 = DropDown()
        btn_plain_rv1 = Button(text='Plain', size_hint_y=None, height=30)
        btn_plain_rv1.bind(
            on_release=lambda btn: dropdown_rv1.select(btn_plain_rv1.text))
        dropdown_rv1.add_widget(btn_plain_rv1)
        btn_beach_rv1 = Button(text='Beach', size_hint_y=None, height=30)
        btn_beach_rv1.bind(
            on_release=lambda btn: dropdown_rv1.select(btn_beach_rv1.text))
        dropdown_rv1.add_widget(btn_beach_rv1)
        btn_desert_rv1 = Button(text='Desert', size_hint_y=None, height=30)
        btn_desert_rv1.bind(
            on_release=lambda btn: dropdown_rv1.select(btn_desert_rv1.text))
        dropdown_rv1.add_widget(btn_desert_rv1)
        btn_hill_rv1 = Button(text='Hill', size_hint_y=None, height=30)
        btn_hill_rv1.bind(
            on_release=lambda btn: dropdown_rv1.select(btn_hill_rv1.text))
        dropdown_rv1.add_widget(btn_hill_rv1)
        button_rv1.bind(on_release=dropdown_rv1.open)
        dropdown_rv1.bind(
            on_select=lambda instance, x: setattr(button_rv1, 'text', x))
        layout.add_widget(button_rv1)

        self.label6 = Label(text="Recent Visit")
        layout.add_widget(self.label6)
        dropdown_rv2 = DropDown()
        btn_plain_rv2 = Button(text='Plain', size_hint_y=None, height=30)
        btn_plain_rv2.bind(
            on_release=lambda btn: dropdown_rv2.select(btn_plain_rv2.text))
        dropdown_rv2.add_widget(btn_plain_rv2)
        btn_beach_rv2 = Button(text='Beach', size_hint_y=None, height=30)
        btn_beach_rv2.bind(
            on_release=lambda btn: dropdown_rv2.select(btn_beach_rv2.text))
        dropdown_rv2.add_widget(btn_beach_rv2)
        btn_desert_rv2 = Button(text='Desert', size_hint_y=None, height=30)
        btn_desert_rv2.bind(
            on_release=lambda btn: dropdown_rv2.select(btn_desert_rv2.text))
        dropdown_rv2.add_widget(btn_desert_rv2)
        btn_hill_rv2 = Button(text='Hill', size_hint_y=None, height=30)
        btn_hill_rv2.bind(
            on_release=lambda btn: dropdown_rv2.select(btn_hill_rv2.text))
        dropdown_rv2.add_widget(btn_hill_rv2)
        button_rv2.bind(on_release=dropdown_rv2.open)
        dropdown_rv2.bind(
            on_select=lambda instance, x: setattr(button_rv2, 'text', x))
        layout.add_widget(button_rv2)

        self.label7 = Label(text="Foreign")
        layout.add_widget(self.label7)
        dropdown_foreign = DropDown()
        btn_yes = Button(text='Yes', size_hint_y=None, height=30)
        btn_yes.bind(
            on_release=lambda btn: dropdown_foreign.select(btn_yes.text))
        dropdown_foreign.add_widget(btn_yes)
        btn_no = Button(text='No', size_hint_y=None, height=30)
        btn_no.bind(
            on_release=lambda btn: dropdown_foreign.select(btn_no.text))
        dropdown_foreign.add_widget(btn_no)
        button_foreign.bind(on_release=dropdown_foreign.open)
        dropdown_foreign.bind(
            on_select=lambda instance, x: setattr(button_foreign, 'text', x))
        layout.add_widget(button_foreign)

        self.label8 = Label(text="Purpose")
        layout.add_widget(self.label8)
        dropdown_purpose = DropDown()
        btn_edu = Button(text='Education', size_hint_y=None, height=30)
        btn_edu.bind(
            on_release=lambda btn: dropdown_purpose.select(btn_edu.text))
        dropdown_purpose.add_widget(btn_edu)
        btn_work = Button(text='Work', size_hint_y=None, height=30)
        btn_work.bind(
            on_release=lambda btn: dropdown_purpose.select(btn_work.text))
        dropdown_purpose.add_widget(btn_work)
        btn_recreation = Button(text='Recreation', size_hint_y=None, height=30)
        btn_recreation.bind(on_release=lambda btn: dropdown_purpose.select(
            btn_recreation.text))
        dropdown_purpose.add_widget(btn_recreation)
        button_purpose.bind(on_release=dropdown_purpose.open)
        dropdown_purpose.bind(
            on_select=lambda instance, x: setattr(button_purpose, 'text', x))
        layout.add_widget(button_purpose)

        self.label9 = Label(text="Eating Habit")
        layout.add_widget(self.label9)
        dropdown_eating = DropDown()
        btn_veg = Button(text='Vegetarian', size_hint_y=None, height=30)
        btn_veg.bind(
            on_release=lambda btn: dropdown_eating.select(btn_veg.text))
        dropdown_eating.add_widget(btn_veg)
        btn_nveg = Button(text='Non-Vegetarian', size_hint_y=None, height=30)
        btn_nveg.bind(
            on_release=lambda btn: dropdown_eating.select(btn_nveg.text))
        dropdown_eating.add_widget(btn_nveg)
        button_eating.bind(on_release=dropdown_eating.open)
        dropdown_eating.bind(
            on_select=lambda instance, x: setattr(button_eating, 'text', x))
        layout.add_widget(button_eating)

        self.label10 = Label(text="Stay")
        layout.add_widget(self.label10)
        dropdown_stay = DropDown()
        btn_dormitory = Button(text='Dormitory', size_hint_y=None, height=30)
        btn_dormitory.bind(
            on_release=lambda btn: dropdown_stay.select(btn_dormitory.text))
        dropdown_stay.add_widget(btn_dormitory)
        btn_hostel = Button(text='Hostel', size_hint_y=None, height=30)
        btn_hostel.bind(
            on_release=lambda btn: dropdown_stay.select(btn_hostel.text))
        dropdown_stay.add_widget(btn_hostel)
        btn_hotel3 = Button(text='Hotel 3*', size_hint_y=None, height=30)
        btn_hotel3.bind(
            on_release=lambda btn: dropdown_stay.select(btn_hotel3.text))
        dropdown_stay.add_widget(btn_hotel3)
        btn_hotel4 = Button(text='Hotel 4*', size_hint_y=None, height=30)
        btn_hotel4.bind(
            on_release=lambda btn: dropdown_stay.select(btn_hotel4.text))
        dropdown_stay.add_widget(btn_hotel4)
        btn_hotel5 = Button(text='Hotel 5*', size_hint_y=None, height=30)
        btn_hotel5.bind(
            on_release=lambda btn: dropdown_stay.select(btn_hotel5.text))
        dropdown_stay.add_widget(btn_hotel5)
        button_stay.bind(on_release=dropdown_stay.open)
        dropdown_stay.bind(
            on_select=lambda instance, x: setattr(button_stay, 'text', x))
        layout.add_widget(button_stay)

        # self.label = Label(text="")
        # layout.add_widget(self.label)
        # self.label = Label(text="")
        # layout.add_widget(self.label)

        btn_lr = Button(text="Logical Regression")
        btn_lr.bind(on_press=self.buttonClicked_LR)
        layout.add_widget(btn_lr)
        self.lr_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.lr_taste)

        btn_dt = Button(text="Decision Tree")
        btn_dt.bind(on_press=self.buttonClicked_DT)
        layout.add_widget(btn_dt)
        self.dt_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.dt_taste)

        btn_svm = Button(text="SVM")
        btn_svm.bind(on_press=self.buttonClicked_SVM)
        layout.add_widget(btn_svm)
        self.svm_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.svm_taste)

        btn_rf = Button(text="Random Forest")
        btn_rf.bind(on_press=self.buttonClicked_RF)
        layout.add_widget(btn_rf)
        self.rf_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.rf_taste)

        self.label12 = Label(text="Email")
        layout.add_widget(self.label12)
        self.email = TextInput(text='', multiline=False)
        layout.add_widget(self.email)

        btn_best_tt = Button(text="Partner")
        btn_best_tt.bind(on_press=self.buttonClicked_TT)
        layout.add_widget(btn_best_tt)
        self.tt_taste = TextInput(text='', multiline=False)
        layout.add_widget(self.tt_taste)

        return layout
コード例 #59
0
class DropDownButton(Button):
    """
    Base class for dropdown containing buttons.

    Assumes dropdown container doesn't contain *boxes* with buttons,
    and that all buttons result in dropdown being closed.
    """
    def __init__(self, container_buttons_height_ratio=2., **kwargs):
        super(DropDownButton, self).__init__(**kwargs)
        self.container_buttons_height_ratio = container_buttons_height_ratio
        self.dropdown = DropDown()
        self.add_dropdown_contents()
        self.add_widget(self.dropdown)
        self.bind(on_release=self.dropdown.open)
        self.set_initial_dropdown_selection()
        self.dropdown.dismiss()

    def container_child_height(self):
        return self.container_buttons_height_ratio * self.height

    @property
    def container_children(self):
        return self.dropdown.container.children

    @property
    def first_button(self):
        return self.container_children[-1]

    def on_release(self, *args):
        super(DropDownButton, self).on_release(*args)
        for btn in self.container_children:
            btn.height = self.container_child_height()

    @staticmethod
    def content_button():
        """
        Returns instance of Button after applying specific params.

        :return: (Button instance)
        """
        return Button(size_hint_y=None,)

    def bind_to_on_release_and_add_container(self, btn):
        btn.bind(on_release=self.apply_on_release_effects)
        btn.bind(on_release=self.dropdown.dismiss)
        self.dropdown.add_widget(btn)

    # Abstract
    def add_dropdown_contents(self, *args):
        raise NotImplementedError

    # Abstract
    def apply_on_release_effects(self, btn):
        """
        Applies all `on_release` effects of a dropdown child
        excluding `dismiss`.

        :param btn: button instance
        :return: (None)
        """
        raise NotImplementedError

    # Abstract
    def set_initial_dropdown_selection(self):
        raise NotImplementedError
コード例 #60
0
ファイル: Client.py プロジェクト: PranaySPatil/Pegasus
class AnnualTrendsClientGrid(GridLayout):
    def __init__(self, **kwargs):
        super(AnnualTrendsClientGrid, self).__init__(**kwargs)
        self.cols = 1

        self.inside = GridLayout(padding=[30, 2, 30, 2], spacing=2)
        self.inside.cols = 1

        self.inside.add_widget(
            Label(text="Domain: ", size_hint_y=None, height=32))
        self.dropdown = DropDown()
        result_set = []
        for domain in CassandraHelper.get_all_domains().current_rows:
            result_set.append(domain.domain)

        result_set.sort()
        domains = set(result_set)
        for domain in domains:
            btn = Button(text=domain, size_hint_y=None, height=32)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.mainbutton = Button(text='Select domain',
                                 size_hint_y=None,
                                 height=35)
        self.mainbutton.bind(on_release=self.dropdown.open)
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self.mainbutton, 'text', x))
        self.inside.add_widget(self.mainbutton)

        self.inside.add_widget(
            Label(text="Year to investigate trending topics: ",
                  size_hint_y=None,
                  height=32))
        self.year = TextInput(multiline=False, size_hint_y=None, height=32)
        self.inside.add_widget(self.year)

        self.inside.add_widget(
            Label(text="Top k topics: ", size_hint_y=None, height=32))
        self.k = TextInput(multiline=False, size_hint_y=None, height=32)
        self.k.text = "10"
        self.inside.add_widget(self.k)

        self.btnGetTopk = Button(text="Get top k topics",
                                 size_hint_y=None,
                                 height=35)
        self.btnGetTopk.bind(on_press=self.visualize_trending_topics)
        self.inside.add_widget(self.btnGetTopk)

        self.inside.add_widget(
            Label(text="Topic to visualize trend:",
                  size_hint_y=None,
                  height=32))
        self.topic = TextInput(multiline=False, size_hint_y=None, height=32)
        self.inside.add_widget(self.topic)

        self.btnVisualizeTrend = Button(
            text="Visualize topic trend from 2015 to 2019",
            size_hint_y=None,
            height=35)
        self.btnVisualizeTrend.bind(on_press=self.visualize_annual_tag_trend)
        self.inside.add_widget(self.btnVisualizeTrend)

        self.add_widget(self.inside)

    def visualize_trending_topics(self, instance):
        year = int(self.year.text)
        k = int(self.k.text)
        domain = self.mainbutton.text
        tags = CassandraHelper.get_annual_trend_tag_by_year(domain, year)
        if tags[0].tags:
            all_tags = tags[0].tags.items()
            all_tags = sorted(all_tags, key=lambda x: x[1])
            all_tags.reverse()
            all_tags = all_tags[0:k]

            x_pos = np.arange(len(all_tags))
            plt.bar(x_pos, [x[1] for x in all_tags], align='center', alpha=0.5)
            plt.xticks(x_pos, [x[0] for x in all_tags])
            plt.ylabel('Usage')
            plt.title('Top ' + str(k) + ' Topics')

            plt.show()
        else:
            print("No topics found for the given domain and year.")

    def visualize_annual_tag_trend(self, instance):
        domain = self.mainbutton.text
        tag = self.topic.text
        years = {2015: 0, 2016: 0, 2017: 0, 2018: 0, 2019: 0}
        for year in years:
            tags = CassandraHelper.get_annual_trend_tag_by_year(domain, year)
            if tags[0].tags.get(tag):
                years[year] = tags[0].tags.get(tag)

        years = sorted(years.items(), key=lambda x: x[0])
        x_pos = np.arange(len(years))
        years_x = [x[0] for x in years]
        years_x[-1] = "2019\ntill Aug"
        plt.plot(x_pos, [x[1] for x in years])
        plt.xticks(x_pos, years_x)
        plt.ylabel('Usage')
        plt.xlabel('Year')
        plt.title('Topic Trend - ' + tag)

        plt.show()