def displayNames(self, dt): nameLayout = GridLayout( cols=3, row_force_default=True, row_default_height=100, size_hint_x=0.6, size_hint_y=0.2, pos_hint={'x': 0.2, 'y': 0.2} ) gusButton = Button( text="Gus", color=[0,0,0,0], background_color=[0,0,0,0] ) chrisButton = Button( text="Chris", color=[0,0,0,0], background_color=[0,0,0,0] ) pattyButton = Button( text="Patty", color=[0,0,0,0], background_color=[0,0,0,0] ) gusButtonAnim = Animation( background_color=const.GUS_COLOR, color=[1,1,1,1], transition=AnimationTransition.in_out_quad ) chrisButtonAnim = Animation( background_color=const.CHRIS_COLOR, color=[1,1,1,1], transition=AnimationTransition.in_out_quad ) pattyButtonAnim = Animation( background_color=const.PATTY_COLOR, color=[1,1,1,1], transition=AnimationTransition.in_out_quad ) gusButtonAnim.start(gusButton) chrisButtonAnim.start(chrisButton) pattyButtonAnim.start(pattyButton) nameLayout.add_widget(gusButton) nameLayout.add_widget(chrisButton) nameLayout.add_widget(pattyButton) self.f.add_widget(nameLayout)
def __init__(self, parent, titleheader="Title", message="Message", options={"OK": ""}, size=(400, 400)): def popup_callback(instance): "callback for button press" self.retvalue = instance.text self.popup.dismiss() self.parent = parent self.retvalue = None self.titleheader = titleheader self.message = message self.options = options self.size = size box = GridLayout(orientation='vertical', cols=1) box.add_widget(Label(text=self.message, font_size=16)) b_list = [] buttonbox = BoxLayout(orientation='horizontal') for b in self.options: b_list.append(Button(text=b, size_hint=(1,.35), font_size=20)) b_list[-1].bind(on_press=popup_callback) buttonbox.add_widget(b_list[-1]) box.add_widget(buttonbox) self.popup = Popup(title=titleheader, content=box, size_hint=(None, None), size=self.size) self.popup.open() self.popup.bind(on_dismiss=self.OnClose)
def __init__(self, **kwargs): self._buttons = {} super(PlaygroundSizeView, self).__init__(**kwargs) for title, values in self.default_sizes: grid = GridLayout(rows=4) def sort_sizes(item): return item[1][1] * item[1][0] values = sorted(values, key=sort_sizes, reverse=True) for name, size in values: btn = ToggleButton(text='', markup=True) btntext = ('%s\n[color=777777][size=%d]%dx%d[/size][/color]' % (name, btn.font_size * 0.8, size[0], size[1])) btn.text = btntext btn.bind(on_press=partial(self.set_size, size)) grid.add_widget(btn) self._buttons[name] = btn item = AccordionItem(title=title) item.add_widget(grid) self.accordion.add_widget(item) self.accordion.select(self.accordion.children[-1]) self.update_buttons()
def subscroll(self): """ opens scroll list of substitute characters in a popup """ for btn in SMApp.teamlist: if btn.state == 'down': SMApp.nameOff = btn btn.state = 'normal' curs.execute('SELECT * FROM Subs') layout2 = GridLayout(cols=2, spacing=10, size_hint_y=None) layout2.bind(minimum_height=layout2.setter('height')) for row in curs: btn = ToggleButton(text=str(row[0]), size_hint_y=None, height=40) if row[1] == 1: btn.background_color = (0.5, 1, 0.9, 1) layout2.add_widget(btn) btn.bind(on_press=subChar) SMApp.sublist.append(btn) lbl = Label(text=str(row[2]), size_hinty=None, height=40) layout2.add_widget(lbl) root = ScrollView(size_hint=(None, None), size=(400, 400)) root.add_widget(layout2) SMApp.popup2 = Popup(content=root, size=(7, 10), size_hint=(0.55, 0.8), title="list of subs") SMApp.popup2.open()
class MyScroll(ScrollView): def __init__(self, **kwargs): super(MyScroll, self).__init__(**kwargs) self.grid1 = GridLayout(cols=10) self.add_widget(self.grid1) self.grid1.size_hint = None, None self.grid1.bind(minimum_height=self.grid1.setter("height")) self.grid1.bind(minimum_width=self.grid1.setter("width")) for i in range(20): for j in range(10): ti = TextInput(size_hint=(None, None)) ti.width = metrics.sp(160) ti.height = metrics.sp(40) if i > 2: ti.row = i ti.col = j self.grid1.add_widget(ti) ti.bind(text=self.textChanged) return def textChanged(self, instance, val): if getattr(instance, "row", None): print instance.row, instance.col, val else: print "Variable row is not implimented"
def build(self): # Set up the layout: layout = GridLayout(cols=5, spacing=30, padding=30, row_default_height=150) # Make the background gray: with layout.canvas.before: Color(.2,.2,.2,1) self.rect = Rectangle(size=(800,600), pos=layout.pos) # Instantiate the first UI object (the GPIO input indicator): inputDisplay = InputButton(text="Input") # Schedule the update of the state of the GPIO input button: Clock.schedule_interval(inputDisplay.update, 1.0/10.0) # Create the rest of the UI objects (and bind them to callbacks, if necessary): outputControl = ToggleButton(text="LED") outputControl.bind(on_press=press_callback) beepButton = Button(text="BEEP!") beepButton.bind(on_press=press_callback) wimg = Image(source='logo.png') speedSlider = Slider(orientation='vertical', min=1, max=30, value=speed) speedSlider.bind(on_touch_down=update_speed, on_touch_move=update_speed) # Add the UI elements to the layout: layout.add_widget(wimg) layout.add_widget(inputDisplay) layout.add_widget(outputControl) layout.add_widget(beepButton) layout.add_widget(speedSlider) # Start flashing the LED Clock.schedule_once(flash, 1.0/speed) return layout
def viewGames(self): sview = ScrollView(size_hint=(.9, .8), pos_hint={'center_x':.5, 'center_y':.5}) layout = GridLayout(cols=1, spacing=10, size_hint_y=None) # Make sure the height is such that there is something to scroll. layout.bind(minimum_height=layout.setter('height')) # Run sql query to get all available games availableGames = retrieve("SELECT * FROM Games") if availableGames == "": popup = Popup(title='No Games', content=Label(text='There are currently no available games'), size_hint=(None, None), size=(400, 100)) popup.open() elif availableGames == 0: popup = Popup(title='Connection', content=Label(text='Could not connect to the database'), size_hint=(None, None), size=(400, 100)) popup.open() else: for tpl in availableGames: uid, name, location, creator, status = tpl print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n" print name print "\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n" btn = Button(id=name, text=name, size_hint_y=None, height=200) btn.bind(on_press=self.seeInfo) layout.add_widget(btn) sview.add_widget(layout) self.add_widget(sview)
def _create_subpopup(self, instance): ''' shows the sub popup ''' # create the popup content = GridLayout(cols=1, spacing='5dp') scrollview = ScrollView( do_scroll_x=False) scrollcontent = GridLayout(cols=1, spacing='5dp', size_hint=(None, None)) scrollcontent.bind(minimum_height=scrollcontent.setter('height')) self.subpopup = popup = Popup(content=content, title=self.uOption, size_hint=(0.5, 0.9), auto_dismiss=False) #we need to open the popup first to get the metrics popup.open() #Add some space on top content.add_widget(Widget(size_hint_y=None, height=dp(2))) # add all the options uid = str(self.uid) for option in self.aSubOption: state = 'down' if option == self.value else 'normal' oTbtn = ToggleButton(text=option, state=state, group=uid, size=(popup.width, dp(55)), size_hint=(None, None)) oTbtn.bind(on_release=self._set_suboption) scrollcontent.add_widget(oTbtn) # finally, add a cancel button to return on the previous panel scrollview.add_widget(scrollcontent) content.add_widget(scrollview) content.add_widget(SettingSpacer()) oMbtn = cMultiLineButton(text=ReplaceVars('$lvar(5009)'), size=(popup.width, dp(50)),size_hint=(0.9, None), halign='center', valign='middle') oMbtn.bind(on_release=popup.dismiss) content.add_widget(oMbtn)
def askInfo(self,requiredInfo): #the button size is wrong on my laptop but right on the tablet so close=Button(text='Add') cancel=Button(text='Cancel') buttonGrid=GridLayout(cols=2,size_hint_y=.5) buttonGrid.add_widget(close) buttonGrid.add_widget(cancel) content=StackLayout(spacing=5) valueList=[]#empty list that gets filled with the inputs' getValue functions for x,y in requiredInfo: content.add_widget(Label(text=x,size_hint=(None,None),size=(50,32))) if y.split()[0]=='text': #v if it's length 1, then it isn't a list tmpWidget=_RetrievableText(len(y.split())-1,multiline=False,size_hint=(None,None), write_tab=False,size=(100,32)) #^ height 32 bc font size defaults to 10 and y padding defaults to 12 valueList.append(tmpWidget.getValue) content.add_widget(tmpWidget) elif y.split()[0]=='int': tmpWidget=_RetrievableText(len(y.split())-1,multiline=False,input_type='number', write_tab=False,size_hint=(None,None),size=(100,32)) #^ height 32 bc font size defaults to 10 and y padding defaults to 12 valueList.append(tmpWidget.getValue) content.add_widget(tmpWidget) #buttonGrid.height=.5*content.height #size_hint_y=.5 should do this but i guess not content.add_widget(buttonGrid) self.askPane=Popup(title='Get Info',content=content,size_hint=(.5,None), height=1.5*content.height, auto_dismiss=False,)#on_dismiss=lambda x: self._setInfo(valueList)) close.bind(on_release=lambda x: self._setInfo(valueList,False))#askPane.dismiss) cancel.bind(on_release=lambda x: self._setInfo(valueList,True)) self.askPane.open()
def load_custom_ker(self): Box = BoxLayout(orientation="vertical", spacing=10) panel = SettingsPanel(title="Custom HTC Kernels", settings=self) msg = GridLayout(cols=1, size_hint=(None, 0.8), width=700) btn_layout = GridLayout(cols=1) done = Button(text="Done") easy = Button(text='Show Stock Kernels',size_hint_y=(None), height=25) btn_layout.add_widget(done) msg.bind(minimum_height=msg.setter('height')) try: for name in kernels: item = SettingItem(panel = panel, title = "%s" % name, disabled=False, desc = "https://github.com/wes342/%s" % name) item_btn = CustomButton(text="Clone: %s" % name ,size_hint=(None, None),width=250, height=40) item.add_widget(item_btn) msg.add_widget(item) item_btn.bind(on_release=get_kernel) root = ScrollView(size_hint=(None, None), size=(675, 350), do_scroll_x=False) root.add_widget(msg) Box.add_widget(easy) Box.add_widget(root) Box.add_widget(btn_layout) easy.bind(on_release=load_ker) popup = Popup(background='atlas://images/eds/pop', title='Custom HTC Kernels',content=Box, auto_dismiss=True, size_hint=(None, None), size=(700, 500)) done.bind(on_release=popup.dismiss) easy.bind(on_release=popup.dismiss) popup.open() except: EdsNotify().run("'system/app Directory Not Found", 'Cant Find:\n' + SystemApp)
class CaterpillarList(ScrollView): def __init__(self,**kwargs): super(CaterpillarList, self).__init__(**kwargs) self.caterpillars=[] self.bind(size=self.draw) self.box=GridLayout(orientation="vertical",cols=2,size_hint_y=None,spacing=10) self.box.bind(minimum_height=self.box.setter('height')) self.add_widget(self.box) def reset(self): self.caterpillars=[] self.draw() def add(self,caterpillar): if caterpillar in self.caterpillars: self.caterpillars.remove(caterpillar) self.caterpillars=[caterpillar]+self.caterpillars self.draw() def draw(self,*args): self.box.clear_widgets() x,y=self.size if x>y: cols = 2 else: cols =1 self.box.cols=cols for guess in self.caterpillars: self.box.add_widget(Caterpillar(chain=guess,size_hint_y=None,size=(x,x/7/cols))) self.scroll_y=1
def __init__(self, **kwargs): Screen.__init__(self, **kwargs) main = BoxLayout(orientation="vertical") main.add_widget(ActionBar(size_hint=(1, .125))) carousel = Carousel(direction='right') layout = GridLayout(rows=2) i, c = 0, 0 for card in self.definition.cards(App.get_running_app().achievements, use_blocks=False): color = (1, 1, 1, 1) if str(card) in self.definition.blocked_cards: color = (.5, 0, 0, 1) layout.add_widget(CardSelect(card=card, color=color, callback=self._card_detail, args=(card,))) i += 1 c += 1 if i == 10: carousel.add_widget(layout) layout = GridLayout(rows=2) i = 0 if c < 50 + len(self.definition.specials): layout.add_widget(CardSelect(card=self.LOCKED_CARD)) carousel.add_widget(layout) main.add_widget(carousel) self.add_widget(main)
def mail_pop(self): """Popup with features to mail timesheet """ f=FloatLayout() global popup2 popup2 = Popup(title='Mail Timesheet',content=f, size_hint=(1.0, 0.6), size=(400, 400)) g=GridLayout(cols=1,row_force_default=True, row_default_height=40,pos_hint={'center_x':.5}) global msg msg=Label(text="ENTER AN EMAIL ID") global mail_id mail_id=TextInput(write_tab=False) g.add_widget(msg) g.add_widget(mail_id) btn1=Button(text='MAIL',size_hint=(0.2,0.1), pos=(popup2.width-350,popup2.height-250) ) btn1.bind(on_press=(MyApp.mail_timesheet)) btn2=Button(text='CLOSE',size_hint=(0.2,0.1), pos=(popup2.width-50,popup2.height-250)) f.add_widget(btn1) f.add_widget(btn2) f.add_widget(g) popup2.open() btn2.bind(on_press=popup2.dismiss)
class FileWidget(BoxLayout): """ """ def __init__(self, action_callback, cancel_callback, action_text): """ :return: """ BoxLayout.__init__(self, orientation="vertical") self.file_chooser = FileChooserIconView(size_hint=(1,0.7), on_submit=self.update_file_input) self.file_input = TextInput() self.action_button = Button(text=action_text, on_press=action_callback) self.cancel_button = Button(text="Cancel", on_press=cancel_callback) self.horizontal_layout = GridLayout(cols=3, row_force_default=True, row_default_height=40, size_hint=(1, 0.055)) self.horizontal_layout.add_widget(self.file_input) self.horizontal_layout.add_widget(self.action_button) self.horizontal_layout.add_widget(self.cancel_button) self.add_widget(self.file_chooser) self.add_widget(self.horizontal_layout) def update_file_input(self, instance, selection, touch): self.file_input.text = selection[0]
def OnIceFenwickStats(obj): # Clear widgets in order to hide previous table if user searched for other play stat categories first Layout.clear_widgets() Layout.add_widget(BackToPlayerSearch) Layout.add_widget(PlayerSearchLabel) Layout.add_widget(IndividualButton) Layout.add_widget(On_Ice_Goals_Button) Layout.add_widget(On_Ice_Fenwick_Button) Grid = GridLayout(rows = len(On_ice_Fenwick_stats) + 1, cols = len(On_ice_Fenwick_categories), size_hint = (None, None)) Grid.bind(minimum_height=Grid.setter('height'), minimum_width = Grid.setter('width')) for stat_category in On_ice_Fenwick_categories: Grid.add_widget(TextInput(text = str(stat_category), size_hint = (None, None), font_size = 18, readonly = True)) for i in range(len(On_ice_Fenwick_stats)): if i % 2 == 0: ColorBackGround = [200./255, 204./255, 255./255, 1] else: ColorBackGround = [1,1,1,1] season = On_ice_Fenwick_stats[i] for stat in season: Grid.add_widget(TextInput(text = str(stat), size_hint = (None, None), font_size = 18, background_color = ColorBackGround, readonly = True)) Scroll = ScrollView(size_hint = (1, .65)) Scroll.add_widget(Grid) Layout.add_widget(Scroll)
class ViewListScreen(MyScreen): def __init__(self, **kwargs): super(ViewListScreen, self).__init__(**kwargs) self.sv = ScrollView() self.content_box.add_widget(self.sv) self.list_grid = GridLayout(cols = 1, size_hint_y = None, orientation = 'vertical') self.sv.add_widget(self.list_grid) self.bind(on_pre_enter= self.prepare_yourself) def prepare_yourself(self,*args): self.list_grid.clear_widgets() c_list = App.get_running_app().root.current_list self.list_grid.height = len(c_list)*40 #HARDCODE for e,spell in enumerate(c_list): spell['button_card'].id = str(e) self.list_grid.add_widget(spell['button_card'])
def __init__(self, **kwargs): super(DemoBox, self).__init__(**kwargs) self.orientation = "vertical" self.buckets = 0 self.garbage = 0 self.funct = 0 self.tracker = TextInput(text=str(self.buckets)) self.tracker.size_hint = (1, .1) self.add_widget(self.tracker) buttons = GridLayout(cols=4) self.add_widget(buttons) butts = [] for i in range(10): butts.append(str(i)) butts.append("+") butts.append("-") butts.append("*") butts.append("/") butts.append("=") butts.append("clear") for butt in butts: b = Button(text=str(butt)) b.bind(on_press=self.press) buttons.add_widget(b) self.symbolFunctions = { "+":self.adder, "-":self.minuser, "=":self.equals, "*":self.multiplyer, "/":self.divider, "clear":self.numclear }
def library(self,instance): print "Show library" k = instance.parent.parent.parent.children[0] k.clear_widgets() s = GridLayout(cols = 1, spacing = 3, size_hint_y = None) s.bind(minimum_height = s.setter('height')) os.chdir(self.music_path) for i in os.listdir(u'.'): if '.mp3' in i: i = i.encode('utf-8') print type(i), i s.add_widget(Button( text = i[:-4], color = (1,1,1,1), size_hint_y = None, height = 70, on_press = self.playSong, background_color = self.song_color, background_normal = '' )) g = ScrollView(size_hint = (1,0.5), pos_hint = {'x': 0, 'y': 0}) g.add_widget(s) d = StackLayout(size_hint = (1,0.3),pos_hint = {'center_x': 0.5, 'y': 0.5}, orientation = 'lr-tb') d.add_widget(Button(text = self.current_song,color = (0,0,0,1),size_hint = (1,0.5),pos_hint = {'x': 0,'y':0.5}, background_normal = '', background_color = (1,1,1,1))) d.add_widget(Button(text = "STOP",size_hint = (0.5,0.5), on_press = self.playSong, background_normal = '', background_color = (0.9,0.1,0.1,1))) d.add_widget(Button(text = "PAUSE",size_hint = (0.5,0.5), on_press = self.playSong, background_normal = '', background_color = (0.9,0.7,0.1,1))) k.add_widget(g) k.add_widget(d)
def build(self): number_of_rows = 20 grid = GridLayout(rows = number_of_rows) for i in range(number_of_rows): for j in range(number_of_rows): grid.add_widget(ChangingBackgroundColor()) return grid
def __init__(self): ScrollView.__init__(self, size_hint=(None, None), size=(1000, 1000), pos=(0, 0)) layout = GridLayout(cols=1, spacing=0, size_hint_y=None) for i in range(30): btn = Button(text=str(i), size_hint_y=None, height=200) layout.add_widget(btn) self.add_widget(layout)
def setup(self): # Get the layout self.config = self.loadLayout() # We'll want to keep a list of all the letter objects self.letters = [] # Create a grid layout that's the right size grid = GridLayout(cols=self.config.COLS) # Loop over the letters for ltr in self.config.LAYOUT: # Create a letter object word = WordClockLetter(text=ltr, size=self.config.SIZE, font_size=self.config.FONTSIZE, colour=self.colour) # add it to our list... grid.add_widget(word) # ...and to the grid layout self.letters.append(word) # Clear the screen self.clear_widgets() # add the clock layout self.add_widget(grid)
def build(self): layout= GridLayout(cols=2) layout.add_widget(Label(text="Investment Ammount", halign='left')) pass btn = Button(text="Calculate", on_press=self.calculate) layout.add_widget(btn) return layout
def __init__(self, **kwargs): super(IntroPanelView, self).__init__(**kwargs) self.name='introscreen' # create a default grid layout with custom width/height layout = GridLayout(cols=1, padding=10, spacing=10, size_hint=(None, None),pos_hint={'center_x': .5, 'center_y': .5}, width=500) layout.bind(minimum_height=layout.setter('height')) # create a scroll view, with a size < size of the grid scrl = ScrollView(size_hint=(None, None), size=(500, 320), pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False) label = Label( text=self.introtext, size=(480, 900), text_size=(480,900), size_hint_y=None, markup=True) scrl.add_widget(label) layout.add_widget(scrl) btn = Button(text='Okay', size=(480, 40), size_hint=(None, None), on_press=self.close) layout.add_widget(btn) self.add_widget(layout)
def __init__(self, **kwargs): super(ScreenRecetas, self).__init__(**kwargs) box1 = GridLayout() box1.cols = 2 box2 = BoxLayout(orientation='horizontal') my_label1 = Label(text="Recetas", font_size='24dp') box1.add_widget(my_label1) box1.add_widget(Label(text=" ")) for x in range(0, len(recetas)): box1.add_widget(Label(text=recetas[x])) box1.add_widget(Button(text="Ver Receta", on_press=self.changerP)) box1.add_widget(Label(text=" ")) box1.add_widget(Label(text=" ")) my_button1 = Button(text="Home",size_hint_y=None, size_y=100) my_button1.bind(on_press=self.changer) my_button4 = Button(text="Informacion \nGeneral",size_hint_y=None, size_y=100) my_button2 = Button(text="Ingredientes",size_hint_y=None, size_y=100) my_button2.bind(on_press=self.changer2) my_button3 = Button(text="Enfermedades",size_hint_y=None, size_y=100) my_button3.bind(on_press=self.changer3) box2.add_widget(my_button1) box2.add_widget(my_button4) box2.add_widget(my_button2) box2.add_widget(my_button3) self.add_widget(box1) self.add_widget(box2)
def Start(self,uTitle,aOptions,fktCallBack): ''' starts selection ''' self.fktCallBack=fktCallBack # create the popup content = GridLayout(cols=1, spacing='5dp') scrollview = ScrollView( do_scroll_x=False, bar_width='10dp',scroll_type=['bars'] ) scrollcontent = GridLayout(cols=1, spacing='5dp', size_hint=(None, None)) scrollcontent.bind(minimum_height=scrollcontent.setter('height')) self.oPopup = popup = Popup(content=content, title=ReplaceVars(uTitle), size_hint=(0.5, 0.9), auto_dismiss=False) #we need to open the popup first to get the metrics popup.open() #Add some space on top content.add_widget(Widget(size_hint_y=None, height=dp(2))) # add all the options for option in aOptions: if hasattr(option,"Name"): name=option.Name else: name=option.Type btn = Button(text=name, size=(popup.width, dp(30)), size_hint=(None, None)) btn.bind(on_release=self.On_Value) btn.oDBRef=option scrollcontent.add_widget(btn) # finally, add a cancel button scrollview.add_widget(scrollcontent) content.add_widget(scrollview) content.add_widget(SettingSpacer()) btn = Button(text=ReplaceVars('$lvar(5009)'), size=(popup.width, dp(50)),size_hint=(0.9, None)) btn.bind(on_release=popup.dismiss) content.add_widget(btn)
def _create_popup(self, instance): # create the popup content = BoxLayout(orientation='vertical', spacing='5dp') box = GridLayout(cols=1, spacing="5dp") box.bind(minimum_height=box.setter('height')) self.popup = popup = Popup(content=content, title=self.title, size_hint=(None, 1), width='400dp') #popup.height = len(self.options) * dp(55) + dp(150) # add all the options content.add_widget(Widget(size_hint_y=None, height=1)) uid = str(self.uid) for option in self.options: state = 'down' if option == self.value else 'normal' btn = ToggleButton(text=option, state=state, group=uid) btn.bind(on_release=self._set_option) box.add_widget(btn) #box.height = metrics.dp(35) * len(self.options) scroll = ScrollView(pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False, size_hint=(1, 1)) scroll.add_widget(box) content.add_widget(scroll) # 2 buttons are created for accept or cancel the current value btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp') btn = Button(text='OK') btn.bind(on_release=self._validate) btnlayout.add_widget(btn) btn = Button(text='Cancel') btn.bind(on_release=self.popup.dismiss) btnlayout.add_widget(btn) content.add_widget(btnlayout) # and open the popup ! popup.open()
def build(self): #self.activePixels.bind(self.pixelValChange) boxLayout = BoxLayout(orientation='vertical') topLayer = BoxLayout( orientation="horizontal", size_hint=(1, .1), padding=4) self.maximumPixelsTXT = TextInput(hint_text="Maximum Pixels",text="5", size_hint=(0.2, 1)) self.nameTXT = TextInput(hint_text="Image Name" , size_hint=(0.2, 1)) self.currentActiveLBL = Label(text="0",size_hint=(0.2, 1)) self.saveBttn = Button(text="Save",size_hint=(0.2, 1), on_press=self.saveImage) self.clearBttn = Button(text="Clear",size_hint=(0.2, 1),on_press=self.clearBttnFn) topLayer.add_widget(self.maximumPixelsTXT) topLayer.add_widget(self.nameTXT) topLayer.add_widget(self.currentActiveLBL) topLayer.add_widget(self.saveBttn ) topLayer.add_widget(self.clearBttn) boxLayout.add_widget(topLayer) gridLayout = GridLayout(cols=self.cols, padding=10, size_hint=(1, 2) ) for i in range(80*4): nb = Button() self.bttns.append(nb) nb.bind(on_press=self.pressPixelButton) gridLayout.add_widget(nb) boxLayout.add_widget(gridLayout) return boxLayout
def build(self): tb_panel= TabbedPanel() tb_panel.background_image ="fundal2.jpg" tb_panel.default_tab_text = "tab-ul default" tb_panel.default_tab_content = Image(source='infoacademy3.gif',pos=(200, 100), size=(200, 200)) th_text_head = TabbedPanelHeader(text='Text tab') th_text_head.content= Label(text='Infoacademy', font_size = 40) th_img_head= TabbedPanelHeader(text='Image tab') th_img_head.content= Image(source='infoacademy4.gif',pos=(400, 100), size=(400, 400)) th_btn_head = TabbedPanelHeader(text='Button tab') layout= GridLayout(cols=1) eticheta=Label(text='tab-ul cu buton', font_size = 40) buton=Button(text='Acesta este un buton',font_size=20) layout.add_widget(eticheta) layout.add_widget(buton) th_btn_head.content= layout th_btn_head.content.padding = 200 tb_panel.add_widget(th_text_head) tb_panel.add_widget(th_img_head) tb_panel.add_widget(th_btn_head) return tb_panel
def taskMenu_inner(_=None): self.clear_widgets() taskMenuLayout = GridLayout(cols=1, spacing=10, size_hint_y=None) taskMenuLayout.bind(minimum_height=taskMenuLayout.setter('height')) self.scroll_y = 1 self.add_widget(taskMenuLayout) backButton = Button(text=getTaskName(tid), size_hint_y=None, height=100) statusLabel = Label(font_size='12sp', valign = 'top', halign='left') if isRunning(tid, True): backButton.background_color = (0.8,1,0.8,1) statusLabel.text = localisation.get(language, "end") + " " + getDateString(getLastDeadline(tid)) elif isComplete(tid): backButton.background_color = (1,0.8,0.8,1) statusLabel.text = localisation.get(language, "cooldown") + " " + getDateString(getCompletionExpirationDate(tid)) else: statusLabel.text = localisation.get(language, "limbo") + " " + getDateString(getCompletionExpirationDate(tid)) backButton.bind(on_press=self.buildMainScreen) taskMenuLayout.add_widget(backButton) taskMenuLayout.add_widget(statusLabel) for milestone in getMilestones(tid): taskMenuLayout.add_widget(self.makeMilestoneLayout(tid, milestone, oldScore if milestone == getNextMilestone(tid) else None)) newMilestoneButton = Button(text=localisation.get(language,"newdate"), bold=True, size_hint_y=None, height=100) taskMenuLayout.add_widget(newMilestoneButton) newMilestoneButton.bind(on_press=self.mileStonePopup(tid)) delConfirmSwitch = Switch() delConfirmPopup = Popup(title=localisation.get(language, "sure"), content=delConfirmSwitch, size_hint=(None, None), size=(200, 200)) delConfirmPopup.bind(on_dismiss=self.deleteTask(tid, delConfirmSwitch)) delButton = Button(text=localisation.get(language,"deltask"), bold=True, size_hint_y=None, height=100) delButton.bind(on_press=delConfirmPopup.open) taskMenuLayout.add_widget(delButton)
class AppList(StackLayout): def __init__(self, app): super(AppList, self).__init__(spacing=2, size_hint=(None, None)) self.app = app self.title = Label(text="No title yet", height=30) self.add_widget(self.title) self.add_buttons() scroll = ScrollView(size_hint_y=None, height=600 - self.height) self.add_widget(scroll) self.layout = GridLayout(cols=1, size_hint_y=None) self.layout.bind(minimum_height=self.layout.setter('height')) scroll.add_widget(self.layout) def add_buttons(self): pass def clear_list(self): self.layout.clear_widgets() def add_item(self, item): item.size_hint_y = None item.height = 40 self.layout.add_widget(item) return item
class MyGrid(GridLayout): def __init__(self, **kwargs): super(MyGrid, self).__init__(**kwargs) self.cols = 1 self.inside = GridLayout() self.inside.cols = 2 self.inside.add_widget(Label(text="First Name: ")) self.name = TextInput(multiline=False) self.inside.add_widget(self.name) self.inside.add_widget(Label(text="Last Name: ")) self.lastname = TextInput(multiline=False) self.inside.add_widget(self.lastname) self.inside.add_widget(Label(text="Email: ")) self.email = TextInput(multiline=False) self.inside.add_widget(self.email) self.question = Label(text=MyApp.random_question(MyApp)) self.inside.add_widget(self.question) self.add_widget(self.inside) self.submit = Button(text="submit", font_size=40) self.submit.bind(on_press=self.pressed) self.add_widget(self.submit) self.new_question = Button(text="mudar pergunta", font_size=40) self.add_widget(self.new_question) def pressed(self, instance): name = self.name.text last = self.lastname.text email = self.email.text print("name :", name, " last: ", last, " email: ", email) self.name.text = "" self.lastname.text = "" self.email.text = "" self.inside.remove_widget(self.question) self.nova_questao = Label(text=MyApp.random_question(MyApp)) self.inside.add_widget(self.nova_questao)
def cadastraCao(self, a): out_box = GridLayout(cols=1, rows=2) box = GridLayout(cols=2) box.add_widget(Label(text='Informe o nome do cão:')) self.nome_cao = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.nome_cao) box.add_widget(Label(text='Informe a raça do cão:')) self.raca_cao = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.raca_cao) box.add_widget(Label(text='Informe o sexo do cão:')) self.sexo_cao = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.sexo_cao) box.add_widget(Label(text='Informe o porte do cão:')) self.porte_cao = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.porte_cao) box.add_widget(Label(text='Informe a idade do cão:')) self.idade_cao = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.idade_cao) box.add_widget(Label(text='Informe o status do cão:')) self.stat_cao = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.stat_cao) box.add_widget(Label(text='Adicione as notas do veterinário:')) self.notas_cao = TextInput(multiline=True, size_hint_y=None, height=150) box.add_widget(self.notas_cao) out_box.add_widget(box) self.confirmaBotao = Button(text="Cadastrar", size_hint_y=0.1) self.confirmaBotao.bind(on_press=self.cadastroLogica) out_box.add_widget(self.confirmaBotao) self.popupCadastro = Popup(title='Cadastrar', content=out_box, size_hint=(None, None), size=(600, 620)) self.popupCadastro.open()
def adota(self, a): box = GridLayout(cols=2, rows=5, spacing=[0, 20]) box.add_widget( Label(text='ID do cão:', size_hint=(None, None), width=140, height=40)) self.idCao = TextInput(multiline=False, size_hint=(None, None), height=40, width=40, write_tab=False) box.add_widget(self.idCao) box.add_widget( Label(text='Nome:', size_hint=(None, None), width=140, height=40)) self.nome = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.nome) box.add_widget( Label(text='Endereço:', size_hint=(None, None), width=140, height=40)) self.end = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.end) box.add_widget( Label(text='CPF:', size_hint=(None, None), width=140, height=40)) self.cpf = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.cpf) box.add_widget( Label(text='Telefone:', size_hint=(None, None), width=140, height=40)) self.tel = TextInput(multiline=False, size_hint_y=None, height=40, write_tab=False) box.add_widget(self.tel) out_box = GridLayout(cols=1, rows=2) out_box.add_widget(box) self.confirmaBotao = Button(text="Adotar", size_hint_y=0.17) self.confirmaBotao.bind(on_press=self.adocaoLogica) out_box.add_widget(self.confirmaBotao) self.popupAdocao = Popup(title='Adoção', content=out_box, size_hint=(None, None), size=(600, 400)) self.popupAdocao.open()
def build(self): from kivy.core.window import Window Window.maximize() print "Importando dados..." self.dados = DAOMemoria.DAOMemoria() print "Dados importados com sucesso!" self.title = "Menu" layout = GridLayout(cols=1, rows=8, spacing=1) self.cadastrarCao = Button(text='Cadastrar Cão') self.cadastrarCao.bind(on_press=self.cadastraCao) self.alterarCao = Button(text='Alterar Cadastro') self.alterarCao.bind(on_press=self.alteraCao) self.excluirCao = Button(text='Excluir Cadastro') self.excluirCao.bind(on_press=self.excluiCao) self.adotar = Button(text='Adotar Cão') self.adotar.bind(on_press=self.adota) self.listarCaes = Button(text='Listar Cães') self.listarCaes.bind(on_press=self.listaCaes) self.listarTut = Button(text='Listar Tutores') self.listarTut.bind(on_press=self.listaTut) self.listarAdoc = Button(text='Listar Adoções') self.listarAdoc.bind(on_press=self.listaAdoc) self.fechar = Button(text='Fechar') self.fechar.bind(on_press=App.get_running_app().stop) layout.add_widget(self.cadastrarCao) layout.add_widget(self.alterarCao) layout.add_widget(self.excluirCao) layout.add_widget(self.adotar) layout.add_widget(self.listarCaes) layout.add_widget(self.listarTut) layout.add_widget(self.listarAdoc) layout.add_widget(self.fechar) return layout
class MainScreen(FloatLayout): def __init__(self, winroot, Config, **kwargs): super(MainScreen, self).__init__(**kwargs) self.winroot = winroot self.config = Config Window.maximize() # here is the main animation # here is the main animation self.base = Base() self.grdlayout1 = GridLayout( cols=1, rows=3, size_hint_x=.25, size_hint_y=.72, padding=15, spacing=50, pos_hint={ 'center_x': .25, 'y': .02 }, ) self.grdlayout2 = GridLayout( cols=1, rows=3, size_hint_x=.25, size_hint_y=.72, padding=15, spacing=50, pos_hint={ 'center_x': .75, 'y': .02 }, ) self.B1 = But(text='Base Calculator\n\n\n', on_press=self.basecalc) self.B2 = But(text='\n\n\n', ) self.B3 = But( text='Exit\n\n\n', on_press=self.base.stop, ) self.B4 = But(text='\n\n\n', ) self.B5 = But(text='\n\n\n', ) self.B6 = But(text='Settings\n\n\n', on_press=self.settings) self.mainlb = Label( text= '[size=17][b]Choose one of the below to proceed[/b][/size]\n\n\n\n', markup=True, size_hint=(1, .18), pos_hint={ 'x': 0, 'y': .72 }) self.grdlayout1.add_widget(self.B1) self.grdlayout1.add_widget(self.B2) self.grdlayout1.add_widget(self.B3) self.grdlayout2.add_widget(self.B4) self.grdlayout2.add_widget(self.B5) self.grdlayout2.add_widget(self.B6) self.add_widget(self.mainlb) self.add_widget(self.grdlayout1) self.add_widget(self.grdlayout2) self.canvas.before.add(Color(1, 1, 1, .7)) self.rects_schedule = Clock.schedule_interval(self.rects, .2) def basecalc(self, obj): self.winroot.clear_widgets() from basecalculator_vert import BaseCalculatorVert self.winroot.add_widget(BaseCalculatorVert(self.winroot, self.config)) def settings(self, obj): self.winroot.clear_widgets() from settings import Settings self.winroot.add_widget(Settings()) def rects(self, obj): print(Window.size) if Window.width != Window.height and Window.size != (800, 600): self.canvas.before.add(Color(1, 1, 0, .6)) self.canvas.before.add(Rectangle( pos=(0, 0), size=Window.size, )) self.canvas.after.add(Color(1, 1, 0, 1)) self.size_x = self.B1.width / 8 self.calc = self.canvas.after.add( Rectangle(pos=(self.B1.x + self.B1.width / 2 - self.size_x, self.B1.y + 10), size=(self.B1.width / 4, self.B1.height / 2), source='calculator128.png')) self.canvas.after.add( Rectangle(pos=(self.B6.x + self.B6.width / 2 - self.size_x, self.B6.y + 10), size=(self.B6.width / 4, self.B6.height / 2), source='Gear-128.png')) self.canvas.after.add( Rectangle(pos=(self.B3.x + self.B3.width / 2 - self.size_x, self.B3.y + 10), size=(self.B3.width / 4, self.B3.height / 2), source='power128.png')) self.rects_schedule.cancel() def on_resize( self, obj=1): # or we can just use the on_resume in the base class ! pass # put all the canvas instructions to redraw it on the resize . def on_exit(self, obj): # here we will add the instructions needed to be done before we close the program ! self.base.stop()
def createWidgets(self): list = ScrollView() layoutList = GridLayout(cols=1, size_hint_y=None, spacing=5) layoutList.bind(minimum_height=layoutList.setter('height')) self.nameInput = TextInput( size_hint=[.8, 1], pos_hint={ "center_x": .5, "y": 0 }, width=200, background_normal="images/backLayout.png", background_active="images/backLayout.png", multiline=False, foreground_color=COLOR["LIGHT"]["MAIN_COLOR"], hint_text="Название", hint_text_color=COLOR["LIGHT"]["MAIN_COLOR"]) self.description = TextInput( size_hint=[.8, 1], pos_hint={ "center_x": .5, "y": 0 }, width=200, background_normal="images/backLayout.png", background_active="images/backLayout.png", foreground_color=COLOR["LIGHT"]["MAIN_COLOR"], hint_text="Описание", hint_text_color=COLOR["LIGHT"]["MAIN_COLOR"]) nameLayout = FloatLayout(size_hint=[1, None], height=50, pos_hint={ "center_x": .5, "Y": 0 }) nameLayout.add_widget(self.nameInput) descriptionLayout = FloatLayout(size_hint=[1, None], height=100) descriptionLayout.add_widget(self.description) self.deadLine = check("Срочность", "dead") addImages = FloatLayout(size_hint=[1, None], height=50) addImages.add_widget(addImage()) checkCategoryF = FloatLayout(size_hint=[1, None], height=30) self.checkCategory = Button(text="Выберете категорию", background_normal="images/button.png", size_hint=[.9, 1], pos_hint={ "center_x": .5, "y": 0 }, on_press=self.openChooseType) checkCategoryF.add_widget(self.checkCategory) endButtons = FloatLayout(size_hint=[.7, None], height=75) okButton = Button(size_hint=[.5, None], height=30, background_normal="images/button.png", text="Пртвердиь", pos_hint={ "center_x": .5, "top": 1 }, on_press=self.addPost) noButton = Button(size_hint=[.3, None], height=35, background_normal="images/button.png", text="Отмена", pos_hint={ "center_x": .5, "y": 0 }, on_press=self.clearActivity) self.important = check("Важность", "imp") endButtons.add_widget(okButton) endButtons.add_widget(noButton) layoutList.add_widget(nameLayout) layoutList.add_widget(descriptionLayout) layoutList.add_widget(self.deadLine) layoutList.add_widget(self.important) layoutList.add_widget(addImages) layoutList.add_widget(Widget(size_hint=[1, None], height=5)) layoutList.add_widget(checkCategoryF) layoutList.add_widget(Widget(size_hint=[1, None], height=40)) layoutList.add_widget(endButtons) list.add_widget(layoutList) self.add_widget(list)
def __init__(self, text, group, **kwargs): super(check, self).__init__(**kwargs) self.important = "Средняя" self.size_hint = [.8, None] self.height = 50 os = FloatLayout(size_hint=[.95, 1], pos_hint={"center_x": .5, "y": 0}) os.add_widget( Button(background_normal="images/backLayout.png", size_hint=[1, 1], pos_hint={ "center_x": .5, "y": 0 })) os.add_widget( Label(text=text + ":", color=COLOR["LIGHT"]["MAIN_COLOR"], size_hint=[.28, 1], pos_hint={ "x": 0, "y": 0 }, font_size="12px")) states = GridLayout(rows=1, pos_hint={ "right": .95, "y": 0 }, size_hint=[.73, 1]) states.add_widget(CheckBox(group=group)) states.add_widget( Label(text="Низкая", font_size="12px", color=COLOR["LIGHT"]["MAIN_COLOR"])) states.add_widget(CheckBox(group=group, state="down")) states.add_widget( Label(text="Средняя", font_size="12px", color=COLOR["LIGHT"]["MAIN_COLOR"])) states.add_widget(CheckBox(group=group)) states.add_widget( Label(text="Высокая", font_size="12px", color=COLOR["LIGHT"]["MAIN_COLOR"])) os.add_widget(states) self.add_widget(os)
def type_sort(self, *_): self.tpopup = Popup(title="sorteren", width=Window.size[0] * 0.4, size_hint_x=None) layout = GridLayout(cols=1) select_layout = GridLayout(cols=2) select_layout.add_widget(Label(text="alles", font_size=30)) self._type_checkboxes = [ CheckBox(group="select_type", size_hint_x=0.4, active=True) ] select_layout.add_widget(self._type_checkboxes[-1]) for type in DATA.get_types(): select_layout.add_widget(Label(text=type, font_size=30)) self._type_checkboxes.append( CheckBox(group="select_type", size_hint_x=0.4)) select_layout.add_widget(self._type_checkboxes[-1]) layout.add_widget(select_layout) knop = Button(text="select", width=Window.size[0] * .75, font_size=30, size_hint_y=0.25) knop.bind(on_press=self.type_selected) layout.add_widget(knop) self.tpopup.add_widget(layout) self.tpopup.open()
class ProductScreen(GridLayout): ''' knoppen knop ('<', '>') en in het midden textinput voor aantal label met paginanr ''' def __init__(self, **kwargs): super().__init__(**kwargs) self.cols = 1 self.rows = 3 self.paginaNr = 0 self.prods = [] self.prods_knoppen = [] self.mode = 1 self.mode_type = -1 #{-1: alles, 0: is eerste type in DATA.get_types()} topgrid = GridLayout(size_hint_y=0.1, cols=2, rows=1) #paginaNr: self.paginaNr_label = Label(text=f"Pagina {self.paginaNr+1}", size_hint_y=0.1, font_size=FS - 2) topgrid.add_widget(self.paginaNr_label) knop = Button(text="SORT", size_hint_x=0.25, font_size=FS - 2) knop.bind(on_press=self.type_sort) topgrid.add_widget(knop) self.add_widget(topgrid) #knopjes self.knopLayout = GridLayout(cols=COLS, padding=[10, 5], spacing=[15, 10]) for _ in range(COLS * ROWS): self.prods_knoppen.append( Button(text="", halign="center", font_size=FS, markup=True, background_normal='')) self.prods_knoppen[-1].bind(on_press=self.klik, width=self._update_text_width) self.knopLayout.add_widget(self.prods_knoppen[-1]) self.min_knop = Button(text="[b]-[/b]", font_size=40, markup=True, background_color=(0.5, 0.5, 0.5, 1), background_normal='', size_hint_y=0.5) self.min_knop.bind(on_press=self.switch_mode) self.knopLayout.add_widget(self.min_knop) self.plus_knop = Button(text="[b]+[/b]", font_size=40, markup=True, background_color=(0.8, 0.8, 0, 1), background_normal='', size_hint_y=0.5) self.plus_knop.bind(on_press=self.switch_mode) self.knopLayout.add_widget(self.plus_knop) knop = Button(text="[b]<-[/b]", font_size=40, markup=True, size_hint_y=0.5) knop.bind(on_press=self.switch_page) self.knopLayout.add_widget(knop) knop = Button(text="[b]->[/b]", font_size=40, markup=True, size_hint_y=0.5) knop.bind(on_press=self.switch_page) self.knopLayout.add_widget(knop) self.add_widget(self.knopLayout) knop = Button( text="Huidige bestelling...", background_color=(0.1, 0.7, 0.3, 1), background_normal='', #om donkere tint te vermijden size_hint_y=0.15, font_size=FS - 2) knop.bind(on_press=self.zie_huidig) self.add_widget(knop) self.vul_in() def zie_huidig(self, _): m_app.screen_manager.current = "bestelling" def reset(self): self.paginaNr = 0 self.mode = 1 #{-1:-, 1:+} self.mode_type = -1 #all types self.paginaNr_label.text = "Pagina {}".format(self.paginaNr + 1) self.vul_in() self.update_list = DATA.bestelling_list() Clock.schedule_once(self.refill, 0.5) def klik(self, instance, load_backup=False): if instance.text != "": DATA.bestelling_add_prod(instance.text, instance.id, self.mode) #temp m_app.bestelling_pagina.bestelling.verklein_bestelling( ) #volledig weg self.update_list = DATA.bestelling_list() Clock.schedule_once(self.refill, 0.5) #message = "{:<28}1".format(instance.text.strip()) self.vul_in() #TODO: remove or change elif load_backup: m_app.bestelling_pagina.bestelling.verklein_bestelling( ) #volledig weg self.update_list = DATA.bestelling_list() Clock.schedule_once(self.refill, 0.5) #message = "{:<28}1".format(instance.text.strip()) self.vul_in() def switch_mode(self, instance): if instance.text == "[b]+[/b]": self.mode = 1 self.plus_knop.background_color = (0.8, 0.8, 0, 1) self.min_knop.background_color = (0.5, 0.5, 0.5, 1) else: self.mode = -1 self.plus_knop.background_color = (0.5, 0.5, 0.5, 1) self.min_knop.background_color = (0.8, 0.8, 0, 1) def switch_page(self, instance): vorig = self.paginaNr if instance.text == "[b]->[/b]": self.paginaNr += 1 if ( self.paginaNr + 1 < DATA.get_num_pages(self.mode_type)) else 0 else: self.paginaNr -= 1 if (self.paginaNr > 0) else 0 #controles nodig #kan beter met een return waarde gebeuren ! if vorig != self.paginaNr: #pas de producten aan self.vul_in() #pas paginaNrlabel aan self.paginaNr_label.text = f"Pagina {self.paginaNr+1}" def vul_in(self): if self.mode_type == -1: data = DATA.get_sort_prod_aantal() else: data = DATA.get_prod_by_type_aantal(self.mode_type) if len(data) < self.paginaNr * COLS * ROWS: end = len(data) else: end = COLS * ROWS * (self.paginaNr + 1) data = data[COLS * ROWS * self.paginaNr:end] for i, knop in enumerate(self.prods_knoppen): try: knop.text = "[b]{}[/b]".format(data[i][1]) knop.id = data[i][0] knop.background_color = COLOURS.get(data[i][0], (0.5, 0.5, 0.5, 1)) except: knop.text = "" knop.background_color = (0.5, 0.5, 0.5, 1) def refill(self, *_): if len(self.update_list): m_app.bestelling_pagina.bestelling.update_bestelling( self.update_list.pop(0)) Clock.schedule_once(self.refill, 0.01) #knoppen def _update_text_width(self, instance, _): instance.text_size = (instance.width * .9, None) #sorteren def type_sort(self, *_): self.tpopup = Popup(title="sorteren", width=Window.size[0] * 0.4, size_hint_x=None) layout = GridLayout(cols=1) select_layout = GridLayout(cols=2) select_layout.add_widget(Label(text="alles", font_size=30)) self._type_checkboxes = [ CheckBox(group="select_type", size_hint_x=0.4, active=True) ] select_layout.add_widget(self._type_checkboxes[-1]) for type in DATA.get_types(): select_layout.add_widget(Label(text=type, font_size=30)) self._type_checkboxes.append( CheckBox(group="select_type", size_hint_x=0.4)) select_layout.add_widget(self._type_checkboxes[-1]) layout.add_widget(select_layout) knop = Button(text="select", width=Window.size[0] * .75, font_size=30, size_hint_y=0.25) knop.bind(on_press=self.type_selected) layout.add_widget(knop) self.tpopup.add_widget(layout) self.tpopup.open() def type_selected(self, *_): #get type for num, box in enumerate(self._type_checkboxes): if box.active: #de index verwijst naar het type self.mode_type = num - 1 break #reset paginaNR self.paginaNr = 0 self.paginaNr_label.text = "Pagina {}".format(self.paginaNr + 1) self.vul_in() #close popup self.tpopup.dismiss() del self.tpopup
def __init__(self, **kwargs): super().__init__(**kwargs) self.cols = 1 self.add_widget( Label(text="Het ID klopt niet; deze rekening is reeds afgesloten.", font_size=FS - 4, size_hint_y=0.2)) lay_top = GridLayout(cols=2, rows=4, size_hint_y=0.85) info = DATA.get_info() lay_top.add_widget(Label(text="Naam:", size_hint_x=0.75, font_size=FS)) self.naam = TextInput(multiline=False, font_size=FS - 4, text=info["naam"]) lay_top.add_widget(self.naam) lay_top.add_widget(Label(text="ID:", size_hint_x=0.75, font_size=FS)) self.ID = TextInput(input_type='number', multiline=False, font_size=FS - 4) lay_top.add_widget(self.ID) lay_top.add_widget( Label(text="Tafelnummer:", size_hint_x=0.75, font_size=FS)) self.tafel = TextInput(input_type='number', multiline=False, font_size=FS - 4, text=str(info["tafel"])) lay_top.add_widget(self.tafel) lay_top.add_widget( Label(text="Verkoper:", size_hint_x=0.75, font_size=FS)) self.verkoper = TextInput(text=DATA.get_verkoper(), multiline=False, font_size=FS - 4) lay_top.add_widget(self.verkoper) self.add_widget(lay_top) knop = Button(text="Probeer opnieuw", font_size=FS, size_hint_y=0.3) knop.bind(on_press=self.resend) self.add_widget(knop) self.add_widget( Label(text="", size_hint_y=None, height=Window.size[1] * 0.45))
def send_bestelling(self, _): #TODO: popup indien de bestelling leeg is if DATA.is_empty() and not (DATA.has_opm()): popup = Popup(title="Info") layout = GridLayout(cols=1) info_label = Label( text= "[color=#ffff00]Je bestelling is leeg![/color]\nEr wordt niets gestuurd!", height=Window.size[1] * .8, size_hint_y=None, font_size=30, halign="center", markup=True) info_label.bind(width=self._update_text_width) layout.add_widget(info_label) knop = Button(text="sluit", width=Window.size[0] * .75) knop.bind(on_press=popup.dismiss) layout.add_widget(knop) popup.add_widget(layout) popup.open() return if not (DATA.get_status()[0]): H = "{}{}".format(DATA.get_info()['id'], randint(0, 99)) DATA.set_hash(H) m_app.info_pagina.change_info("Bestelling onderweg...") #bevat {"status":"ontvangen"} indien de bestelling goed is aangekomen ret = socket_client.requestData({ 'req': 'BST', 'bestelling': DATA.get_bestelling(), "hash": H }) if ret == -1: print("disconnect dump") m_app.dump_data() return #check of bestelling is toegekomen DATA.set_verzonden(True) else: H = DATA.get_hash() m_app.info_pagina.change_info( "Aankomst bestelling aan het controleren") m_app.screen_manager.current = "info" #send check TCP-msg ret = socket_client.requestData({'req': 'CHK', "hash": H}) if ret == -1: #TODO sla alles op, voeg een knopje toe laadt laatste bestelling terug in print("ERROR") return elif not ("status" in ret): print("ERROR, geen status") return #succes elif ret["status"] == 1: m_app.info_pagina.change_info( "Bestelling goed ontvangen en verwerkt.") Clock.schedule_once(self.goKlantinfo, 2) DATA.set_bevestigd(True) #verwijder de json file (moest die er zijn) if os.path.isfile(BACKUP): os.remove(BACKUP) #closed elif ret["status"] == 0: m_app.make_bestelling_closed() m_app.screen_manager.current = "closedbest" DATA.set_verzonden( False ) #terug op false want anders krijgen we een fake bestelling! #onbekend else: #geef foutmelding met hash en laat ze naar de keuken en kassa gaan popup = Popup(title="Onbekend") layout = GridLayout(cols=1) info_label = Label( text= "[b][color=#00ff00]Hash: {}[/color][/b]\nGa nu naar de kassa en/of naar de togen om te controleren of er een ticket met deze hash is toegekomen!" .format(DATA.get_hash()), height=Window.size[1] * .8, size_hint_y=None, font_size=30, halign="center", markup=True) info_label.bind(width=self._update_width) layout.add_widget(info_label) knop = Button(text="sluit", width=Window.size[0] * .75) knop.bind(on_press=popup.dismiss) layout.add_widget(knop) popup.add_widget(layout) popup.open() m_app.screen_manager.current = "klantinfo"
def __init__(self, **kwargs): super().__init__(**kwargs) self.cols = 1 self.rows = 3 self.paginaNr = 0 self.prods = [] self.prods_knoppen = [] self.mode = 1 self.mode_type = -1 #{-1: alles, 0: is eerste type in DATA.get_types()} topgrid = GridLayout(size_hint_y=0.1, cols=2, rows=1) #paginaNr: self.paginaNr_label = Label(text=f"Pagina {self.paginaNr+1}", size_hint_y=0.1, font_size=FS - 2) topgrid.add_widget(self.paginaNr_label) knop = Button(text="SORT", size_hint_x=0.25, font_size=FS - 2) knop.bind(on_press=self.type_sort) topgrid.add_widget(knop) self.add_widget(topgrid) #knopjes self.knopLayout = GridLayout(cols=COLS, padding=[10, 5], spacing=[15, 10]) for _ in range(COLS * ROWS): self.prods_knoppen.append( Button(text="", halign="center", font_size=FS, markup=True, background_normal='')) self.prods_knoppen[-1].bind(on_press=self.klik, width=self._update_text_width) self.knopLayout.add_widget(self.prods_knoppen[-1]) self.min_knop = Button(text="[b]-[/b]", font_size=40, markup=True, background_color=(0.5, 0.5, 0.5, 1), background_normal='', size_hint_y=0.5) self.min_knop.bind(on_press=self.switch_mode) self.knopLayout.add_widget(self.min_knop) self.plus_knop = Button(text="[b]+[/b]", font_size=40, markup=True, background_color=(0.8, 0.8, 0, 1), background_normal='', size_hint_y=0.5) self.plus_knop.bind(on_press=self.switch_mode) self.knopLayout.add_widget(self.plus_knop) knop = Button(text="[b]<-[/b]", font_size=40, markup=True, size_hint_y=0.5) knop.bind(on_press=self.switch_page) self.knopLayout.add_widget(knop) knop = Button(text="[b]->[/b]", font_size=40, markup=True, size_hint_y=0.5) knop.bind(on_press=self.switch_page) self.knopLayout.add_widget(knop) self.add_widget(self.knopLayout) knop = Button( text="Huidige bestelling...", background_color=(0.1, 0.7, 0.3, 1), background_normal='', #om donkere tint te vermijden size_hint_y=0.15, font_size=FS - 2) knop.bind(on_press=self.zie_huidig) self.add_widget(knop) self.vul_in()
def __init__(self, **kwargs): super().__init__(**kwargs) self.cols = 1 top_info = GridLayout(cols=2, rows=1, size_hint_y=0.15) top_info.add_widget(Label(text="Info over de klant:", font_size=FS - 2)) knop = Button(text="BACK UP", size_hint_x=0.5, background_color=(0, 0.2, 1, 1), background_normal='', font_size=FS - 2) knop.bind(on_press=self.check_backup) top_info.add_widget(knop) self.add_widget(top_info) lay_top = GridLayout(cols=2, rows=4, size_hint_y=0.85) lay_top.add_widget(Label(text="Naam:", size_hint_x=0.75, font_size=FS)) self.naam = TextInput(multiline=False, font_size=FS - 2) lay_top.add_widget(self.naam) lay_top.add_widget(Label(text="ID:", size_hint_x=0.75, font_size=FS)) self.ID = TextInput(input_type='number', multiline=False, font_size=FS - 2) lay_top.add_widget(self.ID) lay_top.add_widget( Label(text="Tafelnummer:", size_hint_x=0.75, font_size=FS)) self.tafel = TextInput(input_type='number', multiline=False, font_size=FS - 2) lay_top.add_widget(self.tafel) lay_top.add_widget( Label(text="Verkoper:", size_hint_x=0.75, font_size=FS)) self.verkoper = TextInput(text=DATA.get_verkoper(), multiline=False, font_size=FS - 2) lay_top.add_widget(self.verkoper) self.add_widget(lay_top) knop = Button(text="Ga verder", font_size=FS, size_hint_y=0.3) knop.bind(on_press=self.start_bestelling) self.add_widget(knop) self.add_widget( Label(text="", size_hint_y=None, height=Window.size[1] * 0.45))
def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) self.cols = 1 if os.path.isfile("credentials.txt"): with open("credentials.txt", "r") as f: ip, poort, naam = f.read().strip().split(',') else: ip = "" poort = "" naam = "" lay_top = GridLayout(cols=2, rows=4, size_hint_y=None, height=0.45 * Window.size[1]) lay_top.add_widget(Label(text="ip:", font_size=FS)) self.ip_veld = TextInput(text=ip, multiline=False, font_size=FS - 4) lay_top.add_widget(self.ip_veld) lay_top.add_widget(Label(text="Poort:", font_size=FS)) self.poort = TextInput(text=poort, multiline=False, font_size=FS - 4) lay_top.add_widget(self.poort) lay_top.add_widget(Label(text="Naam:", font_size=FS)) self.naam = TextInput(text=naam, multiline=False, font_size=FS - 4) lay_top.add_widget(self.naam) # lay_top.add_widget(Label( # text="Wachtwoord:", # font_size = 22)) # self.password = TextInput( # multiline=False, # password=True, # font_size = 22) # lay_top.add_widget(self.password) self.add_widget(lay_top) self.knop = Button(text="verbinden", font_size=FS, size_hint_y=None, height=0.1 * Window.size[1]) self.knop.bind(on_press=self.gedrukt) self.add_widget(self.knop) self.add_widget(Label(text=""))
class MyGrid(GridLayout): def __init__(self, **kwargs): super(MyGrid, self).__init__(**kwargs) self.cols = 1 self.inside = GridLayout() self.inside.cols = 2 self.inside.add_widget(Label(text="First Name: ")) self.name = TextInput(multiline=False) self.inside.add_widget(self.name) self.inside.add_widget(Label(text="Last Name: ")) self.lastName = TextInput(multiline=False) self.inside.add_widget(self.lastName) self.inside.add_widget(Label(text="Email: ")) self.email = TextInput(multiline=False) self.inside.add_widget(self.email) self.add_widget(self.inside) self.submit = Button(text="Submit", font_size=40) self.submit.bind(on_press=self.pressed) self.add_widget(self.submit) def pressed(self, instace): name = self.name.text last = self.lastName.text email = self.email.text print("Name:", name, "Last Name:", last, "Email:", email) self.name.text = "" self.lastName.text = "" self.email.text = ""
def check_backup(self, _): if not (os.path.isfile(BACKUP)): self.info_popup( "Er is geen backup gevonden.\nJe bestelling is verzonden en aangekomen." ) return #probeer de backup in te laden try: store = JsonStore(BACKUP) info = store.get("backup").get( "info") #gebruiken voor popup met info data = store.get("backup").get("data") DATA.load_data(data) except Exception as e: print("JSON load error", str(e)) self.info_popup("Er ging iets mis bij het inladen van de backup.") return #maak popup met info over de klant/status popup = Popup(title="Klantinfo") layout = GridLayout(cols=1) layout.add_widget( Label(text="ID: {}".format(info["id"]), font_size=30)) layout.add_widget( Label(text="Naam: {}".format(info["naam"]), font_size=28)) layout.add_widget( Label(text="Tafel: {}".format(info["tafel"]), font_size=30)) layout.add_widget( Label(text="Verzonden: {}".format("Ja" if ( info["verzonden"]) else "Nee"), font_size=30)) layout.add_widget( Label(text="Bevestigd: {}".format("Ja" if ( info["bevestigd"]) else "Nee"), font_size=30)) info_label = Label( text= "[color=#ffff00]Indien je bestelling reeds verzonden is zullen veranderingen niet worden toegelaten![/color]", font_size=30, markup=True) info_label.bind(width=self._update_text_width) layout.add_widget(info_label) knop = Button(text="sluit", width=Window.size[0] * .75) knop.bind(on_press=popup.dismiss) layout.add_widget(knop) popup.add_widget(layout) popup.open() #herlaad het bestellingscherm m_app.prod_pagina.klik(Label(text=""), True) m_app.prod_pagina.reset() m_app.screen_manager.current = "bestelling"
def __init__(self, **kwargs): super().__init__(**kwargs) self.orientation = "vertical" buscador = TextInput( text = "", multiline=False, readonly=False, halign="left", font_size=55, size_hint=(1, .2), #input_filter = "float", write_tab = "False", ) titulos = GridLayout( cols = 5, size_hint = (1, .2) ) tit1 = Label (text = "Articulos", size_hint =(.4, 1), ) tit2 = Label (text = "Precio", size_hint = (.2, 1), ) tit3 = Label (text = "Stock", size_hint = (.2, 1), ) tit4 = Label (text = "Cantidad", size_hint = (.1, 1), ) tit5 = Label(text = "Agregar", size_hint = (.1, 1), ) titulos.add_widget(tit1) titulos.add_widget(tit2) titulos.add_widget(tit3) titulos.add_widget(tit4) titulos.add_widget(tit5) buscador.bind(text = self.on_text) self.add_widget(buscador) self.add_widget(titulos) self.layout = GridLayout(cols = 5, spacing=5, size_hint_y=None ) # Make sure the height is such that there is something to scroll. self.layout.bind(minimum_height=self.layout.setter('height')) rotador = ScrollView( size_hint=(1, 1), #size=(Window.width, Window.height), ) rotador.add_widget(self.layout) self.add_widget(rotador)
def __init__(self, **kwargs): upper = GridLayout(cols=10) lower = BoxLayout(orientation='vertical', spacing=2) self.orientation = 'horizontal' Window.size = (1000, 500) self.alpha = 1 self.num_latents = 10 self.temp_sliders = np.ones(self.num_latents) self.make_audio = False self.all_data = np.zeros((BATCHES, CHUNK)) super(LoginScreen, self).__init__(**kwargs) with self.canvas.before: Color(0, 0.05, 0.15) Rectangle(pos=(0, 0), size=(2000, 2000)) self.sliders = [] for i in range(0, 10): self.sliders.append( Slider(min=0, max=100, value=50, orientation='vertical')) self.sliders[i].fbind('value', self.slide) upper.add_widget(self.sliders[i]) #Button to start music by calling useSliderVals(). This will be changed to a more relevant function soon self.padAnchor6 = AnchorLayout(size_hint_y=0.3) self.playButton = Button(text='Play', size_hint_y=None, height=50, size_hint_x=0.3, font_size=24, background_color=[0, 1, 0]) self.playButton.bind(on_press=self.load_tracks) self.padAnchor6.add_widget(self.playButton) lower.add_widget(self.padAnchor6) #Button to reset values by calling reset() when clicked self.padAnchor = AnchorLayout(size_hint_y=0.3) self.resetButton = Button(text='Reset', size_hint_y=None, height=50, size_hint_x=0.3, font_size=24) self.resetButton.bind(on_press=self.reset) self.padAnchor.add_widget(self.resetButton) lower.add_widget(self.padAnchor) #Button to start music by calling useSliderVals(). This will be changed to a more relevant function soon self.padAnchor6 = AnchorLayout(size_hint_y=0.3) self.textinput3 = TextInput(hint_text='Model', size_hint_y=None, height=45, font_size=24, size_hint_x=None, width=300, multiline='false') self.padAnchor6.add_widget(self.textinput3) lower.add_widget(self.padAnchor6) self.padAnchor3 = AnchorLayout(size_hint_y=0.3) self.textinput1 = TextInput(hint_text='Audio File 1', size_hint_y=None, height=45, size_hint_x=None, width=300, font_size=24, multiline='false') self.padAnchor3.add_widget(self.textinput1) lower.add_widget(self.padAnchor3) self.add_widget(upper) self.add_widget(lower) Clock.schedule_interval(self.loop, POLL_TIME)
class MyGrid(GridLayout): def __init__(self, **kwargs): super(MyGrid, self).__init__(**kwargs) self.cols = 1 self.inside = GridLayout() self.inside.cols = 2 self.add_widget(self.inside) self.inside.add_widget(Label(text="First Name:")) self.first_name = TextInput(multiline=False) self.inside.add_widget(self.first_name) self.inside.add_widget(Label(text="Last Name:")) self.last_name = TextInput(multiline=False) self.inside.add_widget(self.last_name) self.inside.add_widget(Label(text="Email:")) self.email = TextInput(multiline=False) self.inside.add_widget(self.email) self.submit = Button(text="Submit", font_size=40) self.submit.bind(on_press=self.pressed) self.add_widget(self.submit) def pressed(self, instance): first_name = self.first_name.text last_name = self.last_name.text email = self.email.text print("Name: " + first_name + " " + last_name) print("Email address: " + email) #clearing the input boxes self.first_name.text = "" self.last_name.text = "" self.email.text = ""
class RecogApp(App): def build(self): self.capture = cv2.VideoCapture(0) self.my_camera = KivyCamera(capture=self.capture, fps=30) self.total = GridLayout(rows=2) self.label = FormattedLabel() # self.divider = Divider() self.total.add_widget(self.my_camera) #self.total.add_widget(self.divider) self.total.add_widget(self.label) return self.total def on_stop(self): print("*** closing...") exit.set() cam.join() def on_start(self): QOS = 0 BROKER = 'test.mosquitto.org' PORT = 1883 def on_connect(client, userdata, rc, *extra_params): print('Connected with result code=' + str(rc)) client.subscribe("aiproj/facrecog/response", qos=QOS) def send_image(face, frame): (result, num) = client.publish('aiproj/facrecog/image', face, qos=QOS) print(result, num) if result != 0: print('PUBLISH returned error:', result) def on_message(client, data, msg): if msg.topic == "aiproj/facrecog/response": if msg: print("recieved message: ", str(msg.payload.decode())) self.label.update("Emotion: " + str(msg.payload.decode())) def detectAndDisplay(frame): frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_gray = cv2.equalizeHist(frame_gray) faces = face_cascade.detectMultiScale(frame_gray) face_list = [] i = 0 for (x, y, w, h) in faces: center = (x + w // 2, y + h // 2) face_list.append(frame[y:y + h, x:x + w]) return frame, face_list, faces def poll(): while True: flag, frame = self.capture.read() labels = [] if flag: frame_labelled, face_list, bounds = detectAndDisplay(frame) if len(face_list) == 0: self.label.update("Searching for face...") for i in range(len(face_list)): a_face = face_list[i] a_face = pickle.dumps(a_face) send_image(a_face, frame) if exit.is_set(): break #time.sleep(.5) #get the dimintions of the image pos_frame = self.capture.get(cv2.CAP_PROP_POS_FRAMES) face_cascade_name = 'haarcascade_frontalface_default.xml' face_cascade = cv2.CascadeClassifier() face_cascade.load(face_cascade_name) ''' server = Thread(target=start_server) start the thread server.daemon = True server.start() ''' global client global exit global cam exit = Event() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(BROKER, PORT, 60) cam = Thread(target=poll) client.loop_start() cam.start()
def __init__(self,**kwargs): #chama construtor do grid layout super(Cadastro,self).__init__(**kwargs) #layout grid_layout = GridLayout(rows = 10 ,cols = 2,spacing = 2,row_force_default = True, row_default_height = 70, padding =20) self.add_widget(CanvasWidget()) self.add_widget(grid_layout) #widgets # 1st row grid_layout.add_widget(Label(text = 'Cadastro de Dados ',color = [.56,.229,.229,1])) grid_layout.add_widget(Label(text = 'Nome:')) self.nome = TextInput(multiline = True,height = 30) grid_layout.add_widget(self.nome) # 2st row grid_layout.add_widget(Label(text = 'Idade:')) self.idade = TextInput(multiline = True,height = 30) grid_layout.add_widget(self.idade) # 3st row grid_layout.add_widget(Label(text = 'Dia de registro:')) self.data = TextInput(multiline = True,height = 30) grid_layout.add_widget(self.data) # 4st row button = Botao(text ='Cadastrar') button.bind(on_press=self.cadPessoa,on_release =self.clear_txt ) grid_layout.add_widget(button) buttonFile = Botao(text ='Arquivo Iris') buttonFile.bind(on_press=self.telaFile) grid_layout.add_widget(buttonFile)
from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.core.window import Window from kivy.app import runTouchApp layout = GridLayout(cols=1, spacing=10, size_hint_y=None) # Make sure the height is such that there is something to scroll. layout.bind(minimum_height=layout.setter('height')) for i in range(100): btn = Button(text=str(i), size_hint_y=None, height=40) layout.add_widget(btn) root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) root.add_widget(layout) runTouchApp(root)
def build(self): oscAPI.init() root = FloatLayout(size=(self.tray_width,300), pos = (0,0)) # Creates an image widget for the root root_image = Image(source='img/black.jpg', size_hint_x=None, width=self.tray_width, size_hint_y=None, height=300, allow_stretch = True, keep_ratio = False) root.add_widget(root_image) tray = GridLayout(rows = 1, cols = 4, spacing = 10, padding = 0) scatter = Scatter() leftLabel = Label(valign="middle", halign="left", text="Use an appropriate token\nor three fingers to\nexplore the object\nusing the knobs", italic=True, color=(255, 255, 255, 0.75), font_size='20sp') # Creates a MyKnob object widgetA = RelativeLayout(size_hint = (None, None), size = (300,300)) knobA = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter, # Passes the object to the knob knob_id = 001) labelA = Label(text = "Rotate object\nhorizontally", font_size = '20sp', italic = True, bold = True, color = (0, 0, 0, 0.75), halign = "center") widgetA.add_widget(knobA) widgetA.add_widget(labelA) # Creates a MyKnob object widgetB = RelativeLayout(size_hint = (None, None), size = (300,300)) knobB = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter, # Passes the object to the knob knob_id = 002) labelB = Label(text = "Rotate object\nvertically", font_size = '20sp', italic = True, bold = True, color = (0, 0, 0, 0.75), halign = "center") widgetB.add_widget(knobB) widgetB.add_widget(labelB) # Creates a MyKnob object widgetC = RelativeLayout(size_hint = (None, None), size = (300,300)) knobC = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter, # Passes the object to the knob knob_id = 003) labelC = Label(text = "Zoom", font_size = '20sp', italic = True, bold = True, color = (0, 0, 0, 0.75), halign = "center") widgetC.add_widget(knobC) widgetC.add_widget(labelC) # Adds objects to the root tray.add_widget(leftLabel) tray.add_widget(widgetA) tray.add_widget(widgetB) tray.add_widget(widgetC) root.add_widget(tray) return root
def add_table_screens(self, pf_data): c_data = [pf_data[i:i + 7] for i in range(0, len(pf_data), 7)] for count in range(len(c_data)): float = FloatLayout() float.pos_hint = {'center_x': 0.5, 'center_y': 0.8} grid = GridLayout(cols=4) lab1 = Label(text='Symbol') grid.add_widget(lab1) lab2 = Label(text='Quantity') grid.add_widget(lab2) lab3 = Label(text='Price') grid.add_widget(lab3) lab4 = Label(text='Nav') grid.add_widget(lab4) for index, fragment in enumerate(c_data): for item in fragment: sym = Label(text=item.symbol) qty = Label(text=str(item.quantity)) price = Label(text=str(item.price)) nav_str = '' if sym in tryout.nse_prev_price_data: prev_close = tryout.nse_prev_price_data.get(sym) prev_nav = prev_close * item.quantity if prev_nav > item.nav: nav_str = '[color=FF0000]' + str( item.nav) + '[/color]' else: nav_str = '[color=00FF00]' + str( item.nav) + '[/color]' nav = Label(text=nav_str, markup=True) grid.add_widget(sym) grid.add_widget(qty) grid.add_widget(price) grid.add_widget(nav) float.add_widget(grid) tableScreen = TableScreen(float, name='table' + str(count)) print(tableScreen) self.screens.append(tableScreen)
class RecorderWidget(ScrollView): def __init__(self, *args, **kwargs): super(RecorderWidget, self).__init__(*args, **kwargs) self.first_layout = BoxLayout(orientation='vertical') self.record_layout = GridLayout(cols=1, spacing=10, size_hint_y=None) self.record_layout.bind(minimum_height=self.record_layout.setter('height')) self.list_layout = ScrollView() self.recorder = MediaRecorder() if not os.path.isdir("/sdcard/operator/recordings"): os.makedirs("/sdcard/operator/recordings") self.is_recording = False self.set_background(self.record_layout) self.set_background(self.first_layout) self.layout_gen() def set_background(self, layout): """ Sets a solid color as a background. :param layout: The layout for whichever part of the screen should be set. """ layout.bind(size=self._update_rect, pos=self._update_rect) with layout.canvas.before: Color(0, 0, 0, 1) self.rect = Rectangle(size=layout.size, pos=layout.pos) def _update_rect(self, instance, value): """ Ensures that the canvas fits to the screen should the layout ever change. """ self.rect.pos = instance.pos self.rect.size = instance.size def layout_gen(self): """ Generate the initial layout with the dynamic recording button. """ if not self.is_recording: rcrd_btn = Button(text="Start Recording", size_hint_y=.8) rcrd_btn.bind(on_release=lambda x: self.start()) else: rcrd_btn = Button(text="Stop Recording", size_hint_y=.2) rcrd_btn.bind(on_release=lambda x: self.stop()) list_btn = Button(text="Previous recordings", on_release=lambda x: self.prev_recordings(), size_hint_y=None, height=160) self.first_layout.clear_widgets() self.first_layout.add_widget(rcrd_btn) self.first_layout.add_widget(list_btn) self.clear_widgets() self.add_widget(self.first_layout) def init_recorder(self): """Initialize the recorder.""" storage_path = '/sdcard/operator/recordings/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.wav' self.recorder.setAudioSource(AudioSource.MIC) self.recorder.setOutputFormat(OutputFormat.THREE_GPP) self.recorder.setAudioEncoder(AudioEncoder.AMR_NB) self.recorder.setOutputFile(storage_path) self.recorder.prepare() def start(self): """Start the recorder.""" if self.is_recording: self.recorder.stop() self.recorder.reset() self.is_recording = False return self.init_recorder() self.recorder.start() self.is_recording = True self.layout_gen() toast("Recording started", True) def stop(self): """Stop the recorder.""" if not self.is_recording: return self.recorder.stop() self.recorder.reset() self.is_recording = False self.layout_gen() toast("Recording saved", True) def prev_recordings(self): """ Show a list of previous recordings. """ self.clear_widgets() self.record_layout.clear_widgets() self.list_layout.clear_widgets() #sub_layout = BoxLayout(orientation='vertical') sub_layout = GridLayout(cols=1, spacing=10, size_hint_y=None) sub_layout.bind(minimum_height=sub_layout.setter('height')) sub_layout.clear_widgets() titles = [] paths = [] for filename in os.listdir("/sdcard/operator/recordings"): if filename.endswith(".wav"): paths.append(os.path.join("/sdcard/operator/recordings/", filename)) name = filename[:-4] info = name.split('-') formatted_name = info[3] + ":" + info[4] + ":" + info[5] + " on " + info[1] + "/"+info[2] + "/" + info[0] titles.append(formatted_name) for title, path in zip(titles, paths): play_button = Button(text=title, size_hint_y=None, height=160) play_button.bind(on_release=functools.partial(self.play_prev, path)) sub_layout.add_widget(play_button) return_btn = Button(text="Previous", on_release=lambda x: self.show_menu(), size_hint_y=None, height=100) #self.list_layout.add_widget(sub_layout) self.record_layout.add_widget(sub_layout) self.record_layout.add_widget(return_btn) self.add_widget(self.record_layout) def play_prev(self, path, event): """ Play the selected recording. :param str path: The path of the .wav recording. """ sl = SoundLoader() sound = sl.load(path) sound.play() def show_menu(self): """ Shows the list of possible sounds. """ self.clear_widgets() self.record_layout.clear_widgets() self.layout_gen()
class Teams(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) self.name = 'teams' self.client = client self.teams = None self.front = GridLayout() self.front.cols = 1 def show_teams(self): self.client.join_game() if not self.client.games: self.front.add_widget(Label(text="There is no game available")) else: i = 0 for game in self.client.games: self.front.add_widget((Label( text= "Number: {0} Game ID: {1} host: {2} number of teams: {3}" .format(i, game[0], game[1], game[2])))) i += 1 self.grid = GridLayout() self.grid.cols = 2 self.grid.add_widget(Label(text="Select game number:")) self.game = TextInput(multiline=False) self.grid.add_widget(self.game) self.grid.add_widget(Label(text="Select team number:")) self.team = TextInput(multiline=False) self.grid.add_widget(self.team) self.front.add_widget(self.grid) self.submit = Button(text="Submit") self.submit.bind(on_press=self.check_data) self.front.add_widget(self.submit) self.add_widget(self.front) def check_data(self, instance): if self.team.text.isnumeric() and self.game.text.isnumeric(): if int(self.game.text) < len(self.client.games) and 0 < int( self.team.text) <= int(self.client.games[int( self.game.text)][2]): self.client.send_team(self.game.text, self.team.text) client_app.wait = Wait() client_app.screen_manager.add_widget(client_app.wait) client_app.screen_manager.current = 'wait' return self.game.text = "" self.team.text = ""
class EditQuestionScreen(Screen): def __init__(self, **kwargs): super(EditQuestionScreen, self).__init__(**kwargs) self.name = 'edit' self.questoin_dictionary = {} self.qca_dict = None self.grid = GridLayout() self.grid.orientation = 'horizontal' self.grid.size_hint = (0.8, 0.8) self.grid.pos_hint = {'center_x': 0.5, 'center_y': 0.55} self.grid.cols = _NUM_CATS self.build_question_grid() self.home_button = Button(text='home', size_hint=(1 / 8, 1 / 12), pos_hint={ 'x': 0.02, 'y': 0.02 }, background_color=_COLOR_1) self.save_button = Button(text='save', size_hint=(1 / 8, 1 / 12), pos_hint={ 'right': 0.98, 'y': 0.02 }, background_color=_COLOR_1, on_press=self.save_to_db) self.build_edit_entry_popup() self.build_category_popup() self.add_widget(self.grid) self.add_widget(self.home_button) self.add_widget(self.save_button) def build_category_popup(self): self.edit_cat_popup = Popup(size_hint=(0.5, 0.5), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, title="Enter Category Name") self.edit_cat_float_layout = FloatLayout( size_hint=(1, 1), pos_hint={ 'center_x': 0.2, 'center_y': 0.2 }, ) self.cat_entry = TextInput(multiline=False, size_hint=(0.9, 0.50), pos_hint={ 'center_x': 0.5, 'center_y': 0.75 }, hint_text_color=(0, 0, 0, 0.5), hint_text="type category name here", on_text_validate=self.apply_cat) self.apply_cat_button = Button(text='apply', size_hint=(1, 0.1), pos_hint={ 'center_x': 0.5, 'top': 0.42 }) self.apply_cat_button.bind(on_press=self.apply_cat) self.edit_cat_float_layout.add_widget(self.cat_entry) self.edit_cat_float_layout.add_widget(self.apply_cat_button) self.edit_cat_popup.content = self.edit_cat_float_layout def build_edit_entry_popup(self): self.edit_entry_popup = Popup(size_hint=(0.5, 0.5), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, title="Enter Question & Answer") self.edit_float_layout = FloatLayout( size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, ) self.question_entry = TextInput(multiline=True, size_hint=(0.9, 0.30), pos_hint={ 'center_x': 0.5, 'center_y': 0.75 }, hint_text_color=(0, 0, 0, 0.5), hint_text="type question here") self.answer_entry = TextInput(multiline=True, size_hint=(0.9, 0.30), pos_hint={ 'center_x': 0.5, 'center_y': 0.35 }, hint_text_color=(0, 0, 0, 0.5), hint_text="type answer here") self.apply_button = Button(text='apply', size_hint=(1, 0.1), pos_hint={ 'center_x': 0.5, 'y': .02 }) self.apply_button.bind(on_press=self.apply_question) self.edit_float_layout.add_widget(self.question_entry) self.edit_float_layout.add_widget(self.answer_entry) self.edit_float_layout.add_widget(self.apply_button) self.edit_entry_popup.content = self.edit_float_layout def show_edit_entry_popup(self, instance): self.current_selection = instance if instance.question != "not assigned": self.question_entry.text = instance.question else: self.question_entry.text = '' if instance.answer != "not assigned": self.answer_entry.text = instance.answer else: self.answer_entry.text = '' self.edit_entry_popup.open() def show_cat_entry_popup(self, instance): self.current_selection = instance if instance.text != 'A category': self.cat_entry.text = self.current_selection.text else: self.cat_entry.text = '' self.edit_cat_popup.open() def apply_cat(self, instance): children = self.grid.children cur_index = children.index(self.current_selection) self.current_selection.text = self.cat_entry.text self.edit_cat_popup.dismiss() # update cat name for quesitons in cat for index, child in enumerate(children): if index < cur_index and index > cur_index - _NUM_CATS: child.category = self.current_selection.text def save_to_db(self, instance): children = self.grid.children self.qca_dict = {} for index, child in enumerate(children): keys = list(self.qca_dict.keys()) if (index + 1) % 6 != 0: if child.category in keys: self.qca_dict[child.category].append( QAL.QAL(child.question, child.answer, 1)) else: self.qca_dict[child.category] = [ QAL.QAL(child.question, child.answer, 1) ] self.parent.go_home(instance) def apply_question(self, instance): children = self.grid.children cur_index = children.index(self.current_selection) cat_index = int( (cur_index + 1) / _NUM_CATS) * _NUM_CATS + _NUM_CATS - 1 self.current_selection.question = self.question_entry.text self.current_selection.answer = self.answer_entry.text self.current_selection.category = children[cat_index].text self.current_selection.background_color = (216 / 255, 211 / 255, 211 / 255, .5) self.edit_entry_popup.dismiss() def build_question_grid(self): for cat_index in range(_NUM_CATS): cat = Button() cat.text = f'cat {cat_index + 1}' cat.bold = True cat.background_color = _COLOR_1 cat.bind(on_press=self.show_cat_entry_popup) self.grid.add_widget(cat) for question in range(_QUES_PER_CAT): qbtn = QuestionAnswerButton() qbtn.point_value = (question + 1) * 100 qbtn.text = str(qbtn.point_value) qbtn.category = cat.text qbtn.bind(on_press=self.show_edit_entry_popup) self.grid.add_widget(qbtn)
def cont(self): baglanti = sql.connect('sql/baglanti.db') cursor = baglanti.cursor() question = self.ids["question"] true = self.ids["true"] wrong1 = self.ids["wrong1"] wrong2 = self.ids["wrong2"] wrong3 = self.ids["wrong3"] if question.text == "Write Your Question": content = GridLayout(cols=1) content_cancel = Button(text="I'm Sorry", size_hint_y=None, height=40) content.add_widget(Label(text='Question can not be empty !')) content.add_widget(content_cancel) popup = Popup(title="Alert", size_hint=(None, None), size=(275, 275), content=content) content_cancel.bind(on_release=popup.dismiss) popup.open() question.focus = True elif true.text == "Right Answer": content = GridLayout(cols=1) content_cancel = Button(text="I'm Sorry", size_hint_y=None, height=40) content.add_widget(Label(text='Right Answer can not be empty !')) content.add_widget(content_cancel) popup = Popup(title="Alert", size_hint=(None, None), size=(275, 275), content=content) content_cancel.bind(on_release=popup.dismiss) popup.open() true.focus = True elif wrong1.text == "Wrong Answer 1": content = GridLayout(cols=1) content_cancel = Button(text="I'm Sorry", size_hint_y=None, height=40) content.add_widget(Label(text='Wrong Answer 1 can not be empty !')) content.add_widget(content_cancel) popup = Popup(title="Alert", size_hint=(None, None), size=(275, 275), content=content) content_cancel.bind(on_release=popup.dismiss) popup.open() wrong1.focus = True elif wrong2.text == "Wrong Answer 2": content = GridLayout(cols=1) content_cancel = Button(text="I'm Sorry", size_hint_y=None, height=40) content.add_widget(Label(text='Wrong Answer 2 can not be empty !')) content.add_widget(content_cancel) popup = Popup(title="Alert", size_hint=(None, None), size=(275, 275), content=content) content_cancel.bind(on_release=popup.dismiss) popup.open() wrong2.focus = True elif wrong3.text == "Wrong Answer 3": content = GridLayout(cols=1) content_cancel = Button(text="I'm Sorry", size_hint_y=None, height=40) content.add_widget(Label(text='Wrong Answer 3 can not be empty !')) content.add_widget(content_cancel) popup = Popup(title="Alert", size_hint=(None, None), size=(275, 275), content=content) content_cancel.bind(on_release=popup.dismiss) popup.open() wrong3.focus = True else: with baglanti: cursor.execute( "insert into sorular(soru, dogruCevap, yanlisBir, yanlisIki, yanlisUc, ekleyenID, soruDurum) values('{}', '{}', '{}', '{}', '{}', 1, 0)" .format(question, true, wrong1, wrong2, wrong3)) baglanti.commit() content = GridLayout(cols=1) content_cancel = Button(text="Great", size_hint_y=None, height=40) content.add_widget( Label( text= 'Your question will be add after administrator approval.\n Thank You' )) content.add_widget(content_cancel) popup = Popup(title="Notification", size_hint=(None, None), size=(400, 400), content=content) content_cancel.bind(on_release=popup.dismiss) popup.open() wrong3.focus = True self.parent.current = "main"
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)
class SelectionArea(GridLayout): def __init__(self, **kwargs): super(SelectionArea, self).__init__(**kwargs) self.datadir = './Data/' self.plotdir = './Plots/' self.delim = ',' self.data = {} # Layout configuration self.cols = 1 self.rows = 7 self.spacing = 20 self.CreateWidgets() self.CreateBindings() self.AddWidgets() # Helpers def CreateWidgets(self): # Layouts self.data_file_info_holder = GridLayout(cols=2, rows=1) self.x_value_holder = GridLayout(cols=2, rows=1) self.y_value_holder = GridLayout(cols=2, rows=1) self.title_holder = GridLayout(cols=2, rows=1) self.limit_holder = GridLayout(cols=4, rows=3) self.log_holder = GridLayout(cols=2, rows=1) self.plot_button_holder = GridLayout(cols=3, rows=1) # Labels self.data_fname_label = Label(text='Data file: ', halign='right', size_hint=(1, 0.5)) self.x_val_label = Label(text='X Value: ', halign='right', size_hint=(1, 0.5)) self.y_val_label = Label(text='Y Value: ', halign='right', size_hint=(1, 0.5)) self.x_min_label = Label(text='Min x value: ', halign='right', size_hint=(1, 1)) self.x_max_label = Label(text='Max x value: ', halign='right', size_hint=(1, 1)) self.y_min_label = Label(text='Min y value: ', halign='right', size_hint=(1, 1)) self.y_max_label = Label(text='Max y value: ', halign='right', size_hint=(1, 1)) self.x_label_label = Label(text='X-axis label: ', halign='right', size_hint=(1, 1)) self.y_label_label = Label(text='Y-axis label: ', halign='right', size_hint=(1, 1)) self.title_label = Label(text='Graph title: ', halign='right', size_hint=(1, 0.5)) # Text input self.x_min = TextInput(multiline=False, write_tab=False) self.x_max = TextInput(multiline=False, write_tab=False) self.y_min = TextInput(multiline=False, write_tab=False) self.y_max = TextInput(multiline=False, write_tab=False) self.x_label = TextInput(multiline=False, write_tab=False) self.y_label = TextInput(multiline=False, write_tab=False) self.title = TextInput(multiline=False, write_tab=False, size_hint=(1, 0.5)) # Dropdowns self.x_val_dropdown = DropDown() self.y_val_dropdown = DropDown() self.data_fname_dropdown = self.CreateDataFilenameDropdown( self.datadir) # Buttons self.data_fname_btn = Button(text='Please select data file.', size_hint_y=0.5, height=40) self.x_val_btn = Button(text='Please select x value.', size_hint_y=0.5, height=40) self.y_val_btn = Button(text='Please select y value.', size_hint_y=0.5, height=40) self.plot_btn = Button(text='Plot values!', size_hint_y=1, height=40, background_color=(0, 0, 255, 0.8)) self.clear_btn = Button(text='Clear plot', size_hint_y=1, height=40, background_color=(255, 0, 0, 0.8)) self.save_btn = Button(text='Save plot', size_hint_y=1, height=40, background_color=(0, 255, 0, 0.8)) # Toggle buttons self.x_log_btn = ToggleButton(text='Logrithmic x-axis?') self.y_log_btn = ToggleButton(text='Logrithmic y-axis?') def AddWidgets(self): self.data_file_info_holder.add_widget(self.data_fname_label) self.data_file_info_holder.add_widget(self.data_fname_btn) self.x_value_holder.add_widget(self.x_val_label) self.x_value_holder.add_widget(self.x_val_btn) self.y_value_holder.add_widget(self.y_val_label) self.y_value_holder.add_widget(self.y_val_btn) self.title_holder.add_widget(self.title_label) self.title_holder.add_widget(self.title) self.limit_holder.add_widget(self.x_min_label) self.limit_holder.add_widget(self.x_min) self.limit_holder.add_widget(self.y_min_label) self.limit_holder.add_widget(self.y_min) self.limit_holder.add_widget(self.x_max_label) self.limit_holder.add_widget(self.x_max) self.limit_holder.add_widget(self.y_max_label) self.limit_holder.add_widget(self.y_max) self.limit_holder.add_widget(self.x_label_label) self.limit_holder.add_widget(self.x_label) self.limit_holder.add_widget(self.y_label_label) self.limit_holder.add_widget(self.y_label) self.log_holder.add_widget(self.x_log_btn) self.log_holder.add_widget(self.y_log_btn) self.plot_button_holder.add_widget(self.clear_btn) self.plot_button_holder.add_widget(self.save_btn) self.plot_button_holder.add_widget(self.plot_btn) self.add_widget(self.data_file_info_holder) self.add_widget(self.x_value_holder) self.add_widget(self.y_value_holder) self.add_widget(self.title_holder) self.add_widget(self.limit_holder) self.add_widget(self.log_holder) self.add_widget(self.plot_button_holder) def CreateBindings(self): # Button Bindings self.data_fname_btn.bind(on_release=self.data_fname_dropdown.open) self.x_val_btn.bind(on_release=self.x_val_dropdown.open) self.y_val_btn.bind(on_release=self.y_val_dropdown.open) self.plot_btn.bind(on_release=self.PlotSelectedValues) self.clear_btn.bind(on_release=self.ClearPlot) self.save_btn.bind(on_release=self.SavePlot) # ToggleButton Bindings self.x_log_btn.bind(state=self.LogrithmicX) self.y_log_btn.bind(state=self.LogrithmicY) # Dropdown bindings self.data_fname_dropdown.bind(on_select=self.ProcessDataFile) self.x_val_dropdown.bind( on_select=lambda inst, x: setattr(self.x_val_btn, 'text', x)) self.y_val_dropdown.bind( on_select=lambda inst, x: setattr(self.y_val_btn, 'text', x)) # TextInput bindings self.x_min.bind(focus=self.UpdateAxisLimits) self.x_max.bind(focus=self.UpdateAxisLimits) self.y_min.bind(focus=self.UpdateAxisLimits) self.y_max.bind(focus=self.UpdateAxisLimits) self.x_label.bind(focus=self.UpdateXLabel) self.y_label.bind(focus=self.UpdateYLabel) self.title.bind(focus=self.UpdateTitle) def RebindDropdowns(self): self.x_val_btn.bind(on_release=self.x_val_dropdown.open) self.y_val_btn.bind(on_release=self.y_val_dropdown.open) self.x_val_dropdown.bind( on_select=lambda inst, x: setattr(self.x_val_btn, 'text', x)) self.y_val_dropdown.bind( on_select=lambda inst, x: setattr(self.y_val_btn, 'text', x)) # Callbacks def CreateDataFilenameDropdown(self, datadir): dropdown = DropDown() for (dirpath, dirnames, filenames) in os.walk(datadir): for filename in sorted(filenames): if filename.endswith('.csv'): btn = Button(text=filename, size_hint_y=None, height=44) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) return dropdown def CreateDataLabelDropdown(self, dropdown): for label in self.data.keys(): btn = Button(text=label, size_hint_y=None, height=44) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) return dropdown def ProcessDataFile(self, instance, x): self.x_val_dropdown.clear_widgets() self.y_val_dropdown.clear_widgets() setattr(self.data_fname_btn, 'text', x) self.data = {} with open(self.datadir + x) as csvf: reader = csv.reader(csvf, delimiter=self.delim) for label in reader.__next__(): self.data[label] = [] n_label = len(self.data.keys()) for row in reader: assert len( row ) == n_label, '\n\tCSV Error: Number of data != Number of labels' i = 0 for label in self.data.keys(): if row[i] != '': print(row[i]) self.data[label].append(float(row[i])) else: self.data[label].append(0) i += 1 self.CreateDataLabelDropdown(self.x_val_dropdown) self.CreateDataLabelDropdown(self.y_val_dropdown) self.RebindDropdowns() # Plotting methods def PlotSelectedValues(self, instance): x_label = self.x_val_btn.text y_label = self.y_val_btn.text x_data = self.data[x_label] y_data = self.data[y_label] plt.plot(x_data, y_data, label=y_label) #plt.scatter(x_data,y_data,s=5,label=y_label) #plt.legend() canvas = plt.gcf().canvas canvas.draw() x_min, x_max = plt.gca().get_xlim() y_min, y_max = plt.gca().get_ylim() self.x_min.text = str(x_min) self.x_max.text = str(x_max) self.y_min.text = str(y_min) self.y_max.text = str(y_max) def ClearPlot(self, instance): plt.clf() canvas = plt.gcf().canvas canvas.draw() def SavePlot(self, instance): if self.title != '': fname = self.plotdir + self.title.text + '.png' else: fname = self.plotdir + 'default' fig = plt.figure() x_label = self.x_val_btn.text y_label = self.y_val_btn.text x_data = self.data[x_label] y_data = self.data[y_label] plt.scatter(x_data, y_data, s=5) plt.title(self.title.text) plt.xlabel(self.x_label.text) plt.ylabel(self.y_label.text) try: a = [ float(self.x_min.text), float(self.x_max.text), float(self.y_min.text), float(self.y_max.text) ] except ValueError: a = None if a != None: plt.axis(a) fig.savefig(fname, bbox_inches='tight', format='png') plt.close(fig) def UpdateAxisLimits(self, inst, val): try: a = [ float(self.x_min.text), float(self.x_max.text), float(self.y_min.text), float(self.y_max.text) ] except ValueError: return if not val: plt.axis(a) canvas = plt.gcf().canvas canvas.draw() def UpdateXLabel(self, inst, val): if not val: plt.xlabel(self.x_label.text) canvas = plt.gcf().canvas canvas.draw() def UpdateYLabel(self, inst, val): if not val: plt.ylabel(self.y_label.text) canvas = plt.gcf().canvas canvas.draw() def UpdateTitle(self, inst, val): if not val: plt.title(self.title.text) canvas = plt.gcf().canvas canvas.draw() def LogrithmicX(self, inst, val): ax = plt.gca() if val == 'down': ax.set_xscale('log') else: ax.set_xscale('linear') canvas = plt.gcf().canvas canvas.draw() def LogrithmicY(self, inst, val): ax = plt.gca() if val == 'down': ax.set_yscale('log') else: ax.set_yscale('linear') canvas = plt.gcf().canvas canvas.draw()