def __init__(self, **kwargs): Widget.__init__(self, **kwargs) self.canvas = RenderContext(use_parent_projection=True) self.canvas.shader.source = 'tex_atlas.glsl' fmt = ( (b'vCenter', 2, 'float'), (b'vPosition', 2, 'float'), (b'vTexCoords0', 2, 'float'), ) texture, uvmap = load_atlas('icons.atlas') a = uvmap['icon_clock'] vertices = ( 128, 128, -a.su, -a.sv, a.u0, a.v1, 128, 128, a.su, -a.sv, a.u1, a.v1, 128, 128, a.su, a.sv, a.u1, a.v0, 128, 128, -a.su, a.sv, a.u0, a.v0, ) indices = (0, 1, 2, 2, 3, 0) b = uvmap['icon_paint'] vertices += ( 256, 256, -b.su, -b.sv, b.u0, b.v1, 256, 256, b.su, -b.sv, b.u1, b.v1, 256, 256, b.su, b.sv, b.u1, b.v0, 256, 256, -b.su, b.sv, b.u0, b.v0, ) indices += (4, 5, 6, 6, 7, 4) with self.canvas: Mesh(fmt=fmt, mode='triangles', vertices=vertices, indices=indices, texture=texture)
def build(self): wid = Widget() f = FloatLayout() wid.add_widget(f) label = Label(text='0') btn_add100 = Button( text='+ new node', on_press=partial(self.add_node, label, f, 1)) btn_reset = Button( text='Reset', on_press=partial(self.add_node, label, f)) layout = BoxLayout(size_hint=(1, None), height=50) layout.add_widget(btn_add100) layout.add_widget(btn_reset) layout.add_widget(label) root = BoxLayout(orientation='vertical') root.add_widget(wid) root.add_widget(layout) return root
def build(self): base = Widget() ss = ScreenSaver() Clock.schedule_interval(ss.start, 2) base.add_widget(ss) return base
def build(self): root = Widget() puzzle = Puzzle(resolution=(640, 480), play=True) root.add_widget(puzzle) return root
def __init__(self, color=Color(1., 1., 0.), size=(50, 50), pos=(100, 100), **kwargs): Widget.__init__(self, **kwargs) self.size = size self.pos = pos self.ball = Ellipse(pos = self.pos, size = self.size) self.canvas.add(color) self.canvas.add(self.ball)
def __init__(self, **kwargs): self.builded = False self.divW = 5 self.divH = 5 self.vertLines = [] self.horiLines = [] self.charaWidget = None wh = int(min(self.width // self.divW, (self.height - self.yBias) // self.divH)) self.blockSize = wh self.xMergin = (self.width - wh * self.divW) // 2 self.yMergin = ((self.height - self.yBias) - wh * self.divH) // 2 Widget.__init__(self, **kwargs) Map.__init__(self) with self.canvas: for x in range(self.divW): for y in range(self.divH): self.SetBlock([x, y], NullBlockWidget(pos=self.GetRectPos([x, y]), size=[wh, wh])) for i in range(self.divH+1): Color(0.3, 0.3, 0.3) self.vertLines += [Line(points=self.GetRectPos([0, i]) + self.GetRectPos([self.divW, i]), width=2)] for i in range(self.divW+1): Color(0.3, 0.3, 0.3) self.horiLines += [Line(points=self.GetRectPos([i, 0]) + self.GetRectPos([i, self.divH]), width=2)] self.builded = True
def build(self): self.widgets = dict() self.parseConfiguration() parent = Widget() layout = GridLayout(cols=self.numProj, size=(self.numProj * 100, 500), row_default_height=10) for id_ in xrange(self.numProj): self.widgets[id_] = dict() self.widgets[id_]['lbl'] = Label(text=self.proj[id_]['name'], size=(100,25), size_hint_y=None) layout.add_widget(self.widgets[id_]['lbl']) for id_ in xrange(self.numProj): self.widgets[id_]['pwr'] = ToggleButton(text='Off', size=(100, 25), size_hint_y=None) layout.add_widget(self.widgets[id_]['pwr']) for id_ in xrange(self.numProj): self.widgets[id_]['hdmi'] = ToggleButton(text='HDMI', state='down', size=(100, 25), size_hint_y=None, group='video%s' % id_) layout.add_widget(self.widgets[id_]['hdmi']) for id_ in xrange(self.numProj): self.widgets[id_]['vga'] = ToggleButton(text='VGA', state='normal', size=(100, 25), size_hint_y=None, group='video%s' % id_) layout.add_widget(self.widgets[id_]['vga']) parent.add_widget(layout) return parent
def build(self): Window.bind(on_key_down=self.on_key_down) root = Widget() self.container = Container(ws_count=7) # here we add an instance of container to the window, ws_count shows number of workspaces we need root.add_widget(self.container) return root
def on_touch_down(self, touch): self.cursorpos=touch.pos x, y = self.cursorpos self.cursor.pos=(x-40, y-40); self.cursor.visible=True; Widget.on_touch_down(self, touch) self.on_air(touch)
class ClientApp(App): def build(self): #this is where the root widget goes #should be a canvas self.parent = Widget() #this is an empty holder for buttons, etc self.app = GUI() self.sm = SmartStartMenu() self.sm.buildUp() def check_button(obj): #check to see which button was pressed if self.sm.buttonText == 'start': #remove menu self.parent.remove_widget(self.sm) #start the game print ' we should start the game now' Clock.unschedule(self.app.update) Clock.schedule_interval(self.app.update, 1.0/60.0) try: self.parent.remove_widget(self.aboutText) except: pass if self.sm.buttonText == 'about': self.aboutText = Label(text = 'Flappy Ship is made by Molecular Flow Games \n Check out: http://kivyspacegame.wordpress.com') self.aboutText.pos = (Window.width*0.45,Window.height*0.35) self.parent.add_widget(self.aboutText) #bind a callback function that repsonds to event 'on_button_release' by calling function check_button self.sm.bind(on_button_release = check_button) #setup listeners for smartstartmenu self.parent.add_widget(self.sm) self.parent.add_widget(self.app) #use this hierarchy to make it easy to deal w/buttons return self.parent
class ClientApp(App): def build(self): self.parent = Widget() self.app = GUI() self.sm = SmartStartMenu() self.sm.buildUp() def check_button(obj): # check to see which button was pressed if self.sm.buttonText == 'start': # remove menu self.parent.remove_widget(self.sm) # start game Clock.unschedule(self.app.update) Clock.schedule_interval(self.app.update, 1.0 / 60.0) try: self.parent.remove_widget(self.aboutText) except: pass if self.sm.buttonText == 'about': self.aboutText = Label(text=('Created by Ryan Choi, PCP Project ICS4U 2016')) self.aboutText.pos = (Window.width * 0.45, Window.height * 0.35) self.parent.add_widget(self.aboutText) self.sm.bind(on_button_release=check_button) # setup listeners for smartstartmenu self.parent.add_widget(self.sm) self.parent.add_widget(self.app) return self.parent
def build(self): win = Widget() fc1 = FileChooserListView(size=(160,150), pos=(670,260)) fc2 = FileChooserIconView(size=(160,150), pos=(670,120)) win.add_widget(fc1) win.add_widget(fc2) return win
def __init__(self, _min=0, _max=100, value=50): self.__min = _min self.__max = _max self.__value = value # used here only to save current pos and size self.widget_area = Rectangle() self.circle = AndroidSliderCenter(radius=5) self.bg_line = Rectangle() self.bg_line_color = Color(0.109,0.109,0.109,1.0) self.progress_line = Rectangle() self.bg_height = 3 Widget.__init__(self) self.canvas.add(self.bg_line_color) self.canvas.add(self.bg_line) self.canvas.add(Color(0.18,0.7,0.89,1.0)) self.canvas.add(self.progress_line) self.canvas.add(Color(0.18,0.7,0.89,1.0)) self.canvas.add(self.circle) self.canvas.add(Color(0.18,0.7,0.89,0.5)) self.canvas.add(self.circle.outer_circle) self.min = self.__min self.max = self.__max self.value = self.__value ButtonBehavior.__init__(self)
def __init__(self, *kargs, **kwargs): Widget.__init__(self, *kargs, **kwargs) # Bind the keyboard self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down = self._on_keyboard_down) self._keyboard.bind(on_key_up = self._on_keyboard_up) # Set up the controls self.controls = { 'thrust': 0, 'turning': 0, 'attack': 0, } self.old_controls = dict(self.controls) # Objects to display self.objects = {} self.player_id = None # Debug Object if DEBUG: data = { 'object_id': 0, 'type': 'player', 'pos_x': 100, 'pos_y': 100, 'angle': 50, 'vel_x': 10, 'vel_y': 10, 'vel_angle': 120, } self.add_object(data)
def __init__(self, **kwargs): """Function called when the game3 is created """ Widget.__init__(self, **kwargs) # Opening file reading mode loaded_file = open("./game3.txt", "r") #read the first line line = loaded_file.readline() #Loading all the file in 2 different lists while (line!="endfile"): if (line[0]!='#'): tab_res = line.split('&') tab_save = tab_res[1].split('/') tab_name = tab_save[4].split('.') nameImg = tab_name[0] if (tab_res[0]=="Object"): #Create Object with src and category obj = Object2(tab_res[1],nameImg,tab_res[2],tab_res[3],size=(self.windowSave[0]*1/4,self.windowSave[1]*1/3),text=tab_res[4]) #Updating object's list self.ObjectList.append(obj) if (tab_res[0]=="ObjectForm"): cat =tab_res[2] form = ObjectForm(tab_res[1],nameImg,cat,tab_res[3], size=(self.windowSave[0]*1/4,self.windowSave[1]*1/3)) #updating form's list self.ObjectFormList.append(form) #read the next line line = loaded_file.readline() self.new_round()
def build(self): cb = CefBrowser(url="http://mindmeister.com") w = Widget() w.add_widget(cb) #cb.pos = (100, 10) #cb.size = (1720, 480) return cb
def build(self): root = Widget() root.bind(on_touch_move=self.generate_one) aabb = b2AABB() aabb.lowerBound = b2Vec2(0, 0) aabb.upperBound = b2Vec2(10000, 10000) self.world = world = b2World( aabb, b2Vec2(0, -100), True) # plane for the ground, all other the window. # Define the ground body. groundBodyDef = b2BodyDef() groundBodyDef.position = [0, 0] # Call the body factory which allocates memory for the ground body # from a pool and creates the ground box shape (also from a pool). # The body is also added to the world. groundBody = world.CreateBody(groundBodyDef) # Define the ground box shape. groundShapeDef = b2PolygonDef() # The extents are the half-widths of the box. groundShapeDef.SetAsBox(10000, 1) # Add the ground shape to the ground body. groundBody.CreateShape(groundShapeDef) # generate circles self.circles = [] for x in xrange(5): c = Circle(y=500 + x * 5, x=500+x, world=world) self.circles.append(c) root.add_widget(c) Clock.schedule_interval(self._update_world, 1 / 60.) return root
def __init__(self): Widget.__init__(self) self.fbo = None self.fbo_pos = None self.fbo_size = None self.fbo_real_size = None self.fbo_scale = None
def __init__(self): Widget.__init__(self) self.ids['tInput'].bind(focus=self.on_input_focus) self.ids['tInput'].bind(text=self.on_input_text) self.buttons = [] for name in self.hero_names: for hero_name in name: # height=self.height*0.10157, bt = Button(text='', background_normal='images/%s.png'%hero_name, width=Window.width/3.25, size_hint_x=None, size_hint_y=None, opacity=0.8) bt.height=bt.width*0.5620 bt.bind(on_press=lambda x, n=hero_name: self.button_press(n)) bt.bind(width=self.on_button_width) self.buttons.append(bt) self.buttons.sort(key=lambda x: x.background_normal) for bt in self.buttons: self.ids.glayout.add_widget(bt) if platform == 'android': self.MediaPlayer=autoclass('android.media.MediaPlayer') self.player = self.MediaPlayer() self.ids.glayout.bind(minimum_height=self.ids.glayout.setter('height')) if platform == 'android': #Ad Network showAd # print("READY TO SHOW? ", AdBuddiz.isReadyToShowAd())#showAd(PythonActivity.mActivity)) pass self.presses = 0
def __init__(self, **kw): """**Constructor**: Create a new letter box :param keywords: dictionary of keyword arguments **Precondition**: See below. To use the constructor for this class, you should provide it with a list of keyword arguments that initialize various attributes. For example, to initialize the text and the foreground color, use the constructor call GObject(text='A',foreground=[1,0,0,1]) You do not need to provide the keywords as a dictionary. The ** in the parameter `keywords` does that automatically. Any attribute of this class may be used as a keyword. The argument must satisfy the invariants of that attribute. See the list of attributes of this class for more information.""" Widget.__init__(self,**kw) self._label = Label(**kw) self._state = False self._set_properties(kw) self._configure() self.bind(pos=self._reposition,size=self._resize)
def __init__(self, **kwargs): Widget.__init__(self, **kwargs) self.canvas = RenderContext(use_parent_projection=True) self.canvas.shader.source = 'starfield.glsl' self.vfmt = ( ('vCenter', 2, 'float'), ('vScale', 1, 'float'), ('vPosition', 2, 'float'), ('vTexCoords0', 2, 'float'), ) self.vsize = sum(attr[1] for attr in self.vfmt) self.indices = [] for i in xrange(0, 4 * NSTARS, 4): self.indices.extend(( i, i + 1, i + 2, i + 2, i + 3, i)) self.vertices = [] for i in xrange(NSTARS): self.vertices.extend(( 0, 0, 1, -24, -24, 0, 1, 0, 0, 1, 24, -24, 1, 1, 0, 0, 1, 24, 24, 1, 0, 0, 0, 1, -24, 24, 0, 0, )) self.texture = Image('star.png').texture self.stars = [Star(self, i) for i in xrange(NSTARS)]
def __init__(self, card_id, card_holder, number_in_hand): Widget.__init__(self) Button.__init__(self) self.card_id = card_id self.card_holder = card_holder self.number_in_hand = number_in_hand self.background_normal = 'assets/cards/' + str(card_holder) + '/1' + str(card_id)
def __init__(self, character, controller): Widget.__init__(self) self.character = character self.controller = controller summary = CharacterSummary(self.character, self.controller) self.summary.add_widget(summary)
def build(self): screen = Widget() play_button = Button() play_button.text = 'Play ►' play_button.on_press = self.play screen.add_widget(play_button) return screen
def __init__(self, direction, hp, **kwargs): """Initialize a Critter `direction`: direction in radians that the critter is facing initially `hp`: Health of the Critter """ Widget.__init__(self, **kwargs) # Max health self.hp = hp # Direction we're facing currently self.direction = direction # Speed in tiles per second self.speed = CRITTER_SPEED # Damage done (accessed through .damage) self._damage = 0 # Are we dead yet? self.dead = False # x-component of velocity self.xdir = int(numpy.sign(round(numpy.cos(direction)))) # y-component of velocity self.ydir = int(numpy.sign(round(numpy.sin(direction)))) # Initial velocity self.initial_dir = self.xdir, self.ydir self.draw() Clock.schedule_once(self.go) Clock.schedule_once(self.tick)
def __init__(self, angle_calculator, value=0, **kwargs): Widget.__init__(self, **kwargs) self._angle_calculator = angle_calculator self.value = value self.bind(pos=self.draw) self.bind(size=self.draw) self.bind(value=self.draw) self.draw()
def build(self): cb = CefBrowser(url="http://jegger.ch/datapool/app/test1.html", keyboard_above_classes=["select2-input", ]) w = Widget() w.add_widget(cb) #cb.pos = (100, 10) #cb.size = (1720, 480) return cb
def build(self): root = Widget() # trying workspace idea workspace = Workspace() root.add_widget(workspace) return root
def build(self): root = Widget() b1 = Button(pos=(0, 0), # background_color=(226, 13, 13, 1), size=(100, 50), text="Click Me") root.add_widget(b1) return root
def build(self): parent = Widget() self.painter = MyPaintWidget() clearbtn = Button(text='Clear') clearbtn.bind(on_release=self.clear_canvas) parent.add_widget(self.painter) parent.add_widget(clearbtn) return parent
def update_user_list_buttons(self): self.clear_user_list_display() for user in self.user_list.split("\n"): button = ModalPopupButton(text=user) self.ids.user_list.add_widget(button) self.ids.user_list.add_widget(Widget())
def build(self): parent = Widget() parent.add_widget( Button(text='Graph', on_press=show, size=(100, 35), pos=(299, 765))) parent.add_widget( Button(text='Load', on_press=self.load, size=(100, 35), pos=(199, 765))) parent.add_widget( Button(text='Save', on_press=self.save, size=(100, 35), pos=(99, 765))) parent.add_widget( Button(text='+', on_press=self.i_mut, size=(20, 20), pos=(340, 700))) parent.add_widget( Button(text='-', on_press=self.d_mut, size=(20, 20), pos=(365, 700))) parent.add_widget( Label(text='RED < 0', pos=(105, 70), color=(1, 0, 0, 1), font_size=18, font_family='tahoma')) parent.add_widget( Label(text='BLUE > 0', pos=(210, 70), color=(0, 0, 1, 1), font_size=18, font_family='tahoma')) parent.add_widget(self.gen_text) parent.add_widget(self.mutation_text) parent.add_widget(self.score_text) parent.add_widget(self.high_score_text) parent.add_widget(self.nodes_widget) parent.add_widget(self.weights_widget) parent.add_widget(self.snake_widget) parent.add_widget(self.food_widget) with parent.canvas: Color(1, 1, 1, 1) Line(points=(400, 0, 400, 800)) Line(points=(420, 20, 420, 780)) Line(points=(420, 20, 1180, 20)) Line(points=(1180, 20, 1180, 780)) Line(points=(420, 780, 1180, 780)) space = size / 5 n_size = (h - (space * (self.pop.best_snake.brain.i_nodes - 2)) ) / self.pop.best_snake.brain.i_nodes n_space = (w - (len(self.pop.best_snake.brain.weights) * n_size)) / len( self.pop.best_snake.brain.weights) o_buff = (h - (space * (self.pop.best_snake.brain.o_nodes - 1)) - (n_size * self.pop.best_snake.brain.o_nodes)) / 2 lc = 1 for a in range(self.pop.best_snake.brain.h_layers): lc += 1 x0 = x + (lc * (n_size + n_space)) + (n_size / 2) - 49 y0 = y + o_buff + (n_size / 2) - 51 parent.add_widget( Label(text='U', pos=(x0, y0 + 3 * (space + n_size)), color=(0, 0, 0, 1), font_size=18, font_family='tahoma', bold=True)) parent.add_widget( Label(text='D', pos=(x0, y0 + 2 * (space + n_size)), color=(0, 0, 0, 1), font_size=18, font_family='tahoma', bold=True)) parent.add_widget( Label(text='L', pos=(x0, y0 + 1 * (space + n_size)), color=(0, 0, 0, 1), font_size=18, font_family='tahoma', bold=True)) parent.add_widget( Label(text='R', pos=(x0, y0), color=(0, 0, 0, 1), font_size=18, font_family='tahoma', bold=True)) thread = Thread( target=self.pop.evolution, args=(self.weights_widget.canvas, self.nodes_widget.canvas, self.snake_widget.canvas, self.food_widget.canvas, self.gen_text, self.score_text, self.high_score_text)) thread.start() return parent
class Wall(Widget): colorList = ListProperty([1, 1, 0, 1]) blockWidth = NumericProperty(1) blockHeight = NumericProperty(1) blockArea = ReferenceListProperty(blockWidth, blockHeight) blockPos_x = NumericProperty(0) blockPos_y = NumericProperty(0) blockPos = ReferenceListProperty(blockPos_x, blockPos_y) def setup(self, size_x, size_y, pos_x, pos_y): self.blockWidth = size_x self.blockHeight = size_y self.blockPos_x = pos_x self.blockPos_y = pos_y def resize(self, blockSize): self.size = blockSize * Vector(self.blockArea) self.pos = blockSize * Vector(self.blockPos) def repos(self, blockSize): self.pos = blockSize * Vector(self.blockPos) def testCollide(self, testObject, blockSize, dy, dx): self.tempWid = Widget(size=(self.blockWidth, self.blockHeight), pos=(self.blockPos_x, self.blockPos_y)) if dy > 0: w1 = testObject.blockWidth - 2.0 / blockSize h1 = dy x1 = testObject.blockPos_x + 1.0 / blockSize y1 = testObject.blockPos_y + testObject.blockHeight if dy <= 0: w1 = testObject.blockWidth - 2.0 / blockSize h1 = abs(dy) x1 = testObject.blockPos_x + 1.0 / blockSize y1 = testObject.blockPos_y + dy self.tempWid1 = Widget(size=(w1, h1), pos=(x1, y1)) if self.tempWid.collide_widget(self.tempWid1): if dy > 0: testObject.velocity_y = 0 testObject.blockPos_y = self.blockPos_y - testObject.blockHeight elif dy <= 0: testObject.onGround = 1 testObject.groundHeight = self.blockPos_y + self.blockHeight testObject.blockPos_y = testObject.groundHeight if dx > 0: w2 = dx h2 = testObject.blockHeight - 2.0 / blockSize x2 = testObject.blockPos_x + testObject.blockWidth y2 = testObject.blockPos_y + 1.0 / blockSize if dx <= 0: w2 = abs(dx) h2 = testObject.blockHeight - 2.0 / blockSize x2 = testObject.blockPos_x + dx y2 = testObject.blockPos_y + 1.0 / blockSize self.tempWid2 = Widget(size=(w2, h2), pos=(x2, y2)) if self.tempWid.collide_widget(self.tempWid2): if dx > 0: testObject.velocity_x = 0 testObject.blockPos_x = self.blockPos_x - testObject.blockWidth elif dx <= 0: testObject.velocity_x = 0 testObject.blockPos_x = self.blockPos_x + self.blockWidth if self.text == "kill" and (self.tempWid.collide_widget( self.tempWid1) or self.tempWid.collide_widget(self.tempWid2)): try: testObject.kill() except Exception as e: print(e) self.remove_widget(self.tempWid1) self.remove_widget(self.tempWid2) self.remove_widget(self.tempWid) def remove(self): self.parent.remove_widget(self)
def info_ancestors(self, instance): """ Вывод подробной инфы о предке """ self.manager.get_screen('info').clear_widgets() sl = BoxLayout(orientation=horizontal, padding=padding_in_find) first_page_bl = BoxLayout(orientation=vertical) self.search_on_first_page(first_page_bl) sl.add_widget(first_page_bl) # print(instance.id) data, image = self.family_tree.find_full(instance.id) # if not self.page: # self.cursor += 1 if instance.text == 'Вперед': if self.cursor != len(self.page) - 1: self.cursor += 1 elif instance.text == 'Назад': if self.cursor != 0: self.cursor -= 1 else: if len(self.page) >= 1: self.cursor += 1 del self.page[self.cursor:] self.page.append(instance.id) st = StackLayout(size_hint_y=1) sl.add_widget(st) st.add_widget( Label( text='Личная карточка', **unpress_label(50), size_hint_y=.1, )) st.add_widget( Label( text='Родители' if len(data.get('parents')) > 0 else '', **unpress_label(font_in_pr_page), size_hint=(1, .05), )) # print(data) for parent in data.get('parents'): st.add_widget( Button(**button_for_parents( parent.get('fullname').replace(' ', '\n'), parent.get('id'), self.info_ancestors, (.5, .1), font_in_pr_page, ))) if data.get('second_half') and len(data.get('second_half')) > 0: if len(data.get('second_half')) > 1: st.add_widget( Button(text='Супруги', on_press=lambda x: self.output_on_first_page( first_page_bl, data.get('second_half')), **for_more_objects, **unpress_label(font_in_pr_page))) else: second_half = data.get('second_half')[0] mini_bl = BoxLayout( orientation=vertical, size_hint=(.33, .35), ) mini_bl.add_widget( Label(text=second_half.get('rel'), **unpress_label(font_in_pr_page))) mini_bl.add_widget( Button( **button_for_parents( second_half.get('fullname').replace(' ', '\n'), second_half.get('id'), self.info_ancestors, (1, 1), font_in_pr_page), )) mini_bl.add_widget(Widget()) st.add_widget(mini_bl) else: st.add_widget( Label( text='', **unpress_label(font_in_pr_page), size_hint=(.33, .35), )) if image: st.add_widget( Image(source='static\\' + image[0], size_hint=(.33, .35))) else: st.add_widget( Label(text='', **unpress_label(30), size_hint=(.33, .35))) if data.get('bro_and_sis'): if len(data.get('bro_and_sis')) > 1: st.add_widget( Button(text='Братья и сестры', on_press=lambda x: self.output_on_first_page( first_page_bl, data.get('bro_and_sis')), **for_more_objects, **unpress_label(font_in_pr_page))) else: mini_bl = BoxLayout(orientation=vertical, size_hint=(.33, .35)) mini_bl.add_widget( Label( text='Братья и сестры', **unpress_label(25), size_hint=(1, .3), )) mini_bl.add_widget( Button(**button_for_parents( data.get('bro_and_sis')[0].get('fullname').replace( ' ', '\n'), data.get('bro_and_sis')[0].get('fullname').get('id'), self.info_ancestors, (1, .3), 25))) st.add_widget(mini_bl) else: st.add_widget( Label(text='', **unpress_label(font_in_pr_page), size_hint=(.33, .35))) st.add_widget( Label(text=data.get('fullname') + ('\n' + data.get('bdate') if data.get('bdate') else ''), **unpress_label(font_in_pr_page), size_hint_y=.05, halign='center')) # print(data) temp_data = '' if data.get('comment'): news_str = data.get('comment').split() for part in range(6, len(news_str), 6): news_str[part] += '\n' data['comment'] = ' '.join(news_str) if len(data.get('comment')) > 400: temp_data = data.get('comment')[:400] temp_data = temp_data[:temp_data.rfind(' ')] + '...' else: temp_data = data.get('comment') st.add_widget( Button( text=temp_data if data.get('comment') else '', **unpress_label(font_in_pr_page), size_hint_y=.33, halign='center', background_color=invisible_background_color, on_press=lambda x: self.description_in_popup( data.get('comment')), )) navigation_bl = BoxLayout( orientation='horizontal', size_hint_y=.1, ) st.add_widget(navigation_bl) if self.cursor != 0 and len(self.page) >= 2: navigation_bl.add_widget( Button(**navigation_buttons( 'Назад', str(self.page[self.cursor - 1]), self.info_ancestors))) if self.cursor < len(self.page) - 1 and len(self.page) >= 2: navigation_bl.add_widget( Button(**navigation_buttons( 'Вперед', str(self.page[self.cursor + 1]), self.info_ancestors))) self.manager.get_screen('info').add_widget(sl) self.change_screen(info_screen)
def __init__(self, **kwargs): super(RPApp, self).__init__(**kwargs) self.widget = Widget() self.pattern_algorithm = PatternAlgorithm(loop_count=18)
first_button = Button(text='Popup\nbutton') first_button.bind(on_release=popup.open) side_panel.add_widget(first_button) side_panel.add_widget(Button(text='Another\nbutton')) navigationdrawer.add_widget(side_panel) label_head = ('[b]Example label filling main panel[/b]\n\n[color=ff0000](p' 'ull from left to right!)[/color]\n\nIn this example, the le' 'ft panel is a simple boxlayout menu, and this main panel is' ' a BoxLayout with a label and example image.\n\nSeveral pre' 'set layouts are available (see buttons below), but users ma' 'y edit every parameter for much more customisation.') main_panel = BoxLayout(orientation='vertical') label_bl = BoxLayout(orientation='horizontal') label = Label(text=label_head, font_size='15sp', markup=True, valign='top') label_bl.add_widget(Widget(size_hint_x=None, width=dp(10))) label_bl.add_widget(label) label_bl.add_widget(Widget(size_hint_x=None, width=dp(10))) main_panel.add_widget(Widget(size_hint_y=None, height=dp(10))) main_panel.add_widget(label_bl) main_panel.add_widget(Widget(size_hint_y=None, height=dp(10))) navigationdrawer.add_widget(main_panel) label.bind(size=label.setter('text_size')) def set_anim_type(name): navigationdrawer.anim_type = name def set_transition(name): navigationdrawer.opening_transition = name navigationdrawer.closing_transition = name
def _update_tabs(self, *l): self_content = self.content if not self_content: return # cache variables for faster access tab_pos = self.tab_pos tab_layout = self._tab_layout tab_layout.clear_widgets() scrl_v = ScrollView(size_hint=(None, 1)) tabs = self._tab_strip parent = tabs.parent if parent: parent.remove_widget(tabs) scrl_v.add_widget(tabs) scrl_v.pos = (0, 0) self_update_scrollview = self._update_scrollview # update scrlv width when tab width changes depends on tab_pos if self._partial_update_scrollview is not None: tabs.unbind(width=self._partial_update_scrollview) self._partial_update_scrollview = partial(self_update_scrollview, scrl_v) tabs.bind(width=self._partial_update_scrollview) # remove all widgets from the tab_strip self.clear_widgets(do_super=True) tab_height = self.tab_height widget_list = [] tab_list = [] pos_letter = tab_pos[0] if pos_letter == 'b' or pos_letter == 't': # bottom or top positions # one col containing the tab_strip and the content self.cols = 1 self.rows = 2 # tab_layout contains the scrollview containing tabs and two blank # dummy widgets for spacing tab_layout.rows = 1 tab_layout.cols = 3 tab_layout.size_hint = (1, None) tab_layout.height = tab_height self_update_scrollview(scrl_v) if pos_letter == 'b': # bottom if tab_pos == 'bottom_mid': tab_list = (Widget(), scrl_v, Widget()) widget_list = (self_content, tab_layout) else: if tab_pos == 'bottom_left': tab_list = (scrl_v, Widget(), Widget()) elif tab_pos == 'bottom_right': #add two dummy widgets tab_list = (Widget(), Widget(), scrl_v) widget_list = (self_content, tab_layout) else: # top if tab_pos == 'top_mid': tab_list = (Widget(), scrl_v, Widget()) elif tab_pos == 'top_left': tab_list = (scrl_v, Widget(), Widget()) elif tab_pos == 'top_right': tab_list = (Widget(), Widget(), scrl_v) widget_list = (tab_layout, self_content) elif pos_letter == 'l' or pos_letter == 'r': # left ot right positions # one row containing the tab_strip and the content self.cols = 2 self.rows = 1 # tab_layout contains two blank dummy widgets for spacing # "vertically" and the scatter containing scrollview containing tabs tab_layout.rows = 3 tab_layout.cols = 1 tab_layout.size_hint = (None, 1) tab_layout.width = tab_height scrl_v.height = tab_height self_update_scrollview(scrl_v) # rotate the scatter for vertical positions rotation = 90 if tab_pos[0] == 'l' else -90 sctr = Scatter(do_translation=False, rotation=rotation, do_rotation=False, do_scale=False, size_hint=(None, None), auto_bring_to_front=False, size=scrl_v.size) sctr.add_widget(scrl_v) lentab_pos = len(tab_pos) # Update scatter's top when it's pos changes. # Needed for repositioning scatter to the correct place after its # added to the parent. Use clock_schedule_once to ensure top is # calculated after the parent's pos on canvas has been calculated. # This is needed for when tab_pos changes to correctly position # scatter. Without clock.schedule_once the positions would look # fine but touch won't translate to the correct position if tab_pos[lentab_pos - 4:] == '_top': #on positions 'left_top' and 'right_top' sctr.bind(pos=partial(self._update_top, sctr, 'top', None)) tab_list = (sctr, ) elif tab_pos[lentab_pos - 4:] == '_mid': #calculate top of scatter sctr.bind( pos=partial(self._update_top, sctr, 'mid', scrl_v.width)) tab_list = (Widget(), sctr, Widget()) elif tab_pos[lentab_pos - 7:] == '_bottom': tab_list = (Widget(), Widget(), sctr) if pos_letter == 'l': widget_list = (tab_layout, self_content) else: widget_list = (self_content, tab_layout) # add widgets to tab_layout add = tab_layout.add_widget for widg in tab_list: add(widg) # add widgets to self add = self.add_widget for widg in widget_list: add(widg)
print("Hello World") def myFunction(checkButton, value): if value == True: print("the Check IS Active") else: print("The Check Is Not Selected!") def callback(instance): print('The button {} is being pressed'.format( instance.text)) #<-- method do define on_pressed Button command! hola = Widget() #***Button Widget** btn1 = Button(text='Hello world 1', pos=[400, 400]) btn1.bind(on_press=callback) btn2 = Button(text='Hello world 2', pos=[300, 300]) btn2.bind(on_press=callback) hola.add_widget(btn1) hola.add_widget(btn2) #***Label Widget*** label = Label(text="Hola Mundo", pos=[500, 500]) hola.add_widget(label) #****CheckBox Widget*** checkButton = CheckBox(color=[0, 1, 0, 1]) checkButton.bind(active=myFunction) hola.add_widget(checkButton) #***Slider***
def build(self): parent = Widget() painter = Painter() create_pointer = Button(text='Create pointer',pos=(0,0),size=(100,50)) create_node = Button(text='Create node',pos=(100,0),size=(100,50)) txtbox = TextInput(pos=(500,0),size=(100,50)) add_val = Button(text='Add value',pos=(600,0),size=(100,50)) reset = Button(text='Reset',pos=(700,0),size=(100,50)) parent.add_widget(painter) parent.add_widget(reset) parent.add_widget(create_pointer) parent.add_widget(create_node) parent.add_widget(txtbox) parent.add_widget(add_val) def clearCanvas(obj): painter.canvas.clear() reset.bind(on_release=clearCanvas) def createPointerTrigger(obj): painter.drawPtr=True painter.ptr_count+=1 painter.new_ptr = True create_pointer.bind(on_release=createPointerTrigger) def createNodeTrigger(obj): painter.drawNode=True create_node.bind(on_release=createNodeTrigger) def addValueTrigger(self,obj): painter.value[0]=(int(txtbox.text)) add_val.bind(on_release=partial(addValueTrigger,self)) return parent
def build(self): self.top_widget = Widget() self.content_widget = Widget() self.top_widget.add_widget(self.content_widget) self.top_widget.add_widget(SpeedAdjuster(self)) return self.top_widget
class Replay(App): """A widget that replays a game from a log file captured by Logger Replay monkeypatches kivy.clock.time to fire events read from the log file. Touching the replay will change the replay speed based on the y (up/down) -coordinate of the touch, from 50% to 200%. (NB. every clock tick is still processed, so speedups might not actually be that big). This is more of a dirty hack than other parts of the code. """ def __init__(self, log_filename): super(Replay, self).__init__() self.log_filename = log_filename kivy.clock.time = self.time self.stream = gzip.GzipFile(fileobj=open(self.log_filename, 'rb')) self.first_tick = time() self.last_tick = time() self.time_elapsed = 0 self.stream_time = 0 self.next_id = 0 self.clock_speed = 1 self.running = True def build(self): self.top_widget = Widget() self.content_widget = Widget() self.top_widget.add_widget(self.content_widget) self.top_widget.add_widget(SpeedAdjuster(self)) return self.top_widget def time(self): """Like time.time(), but handles events from the log file """ current = time() self.time_elapsed += (current - self.last_tick) * self.clock_speed self.last_tick = current if not self.running: return self.last_tick while self.stream and self.time_elapsed > self.stream_time: try: rec = pickle.load(self.stream) except EOFError: self.handle__end() self.running = False break else: getattr(self, 'handle_' + rec[0])(*rec[1:]) if rec[0] == 'dt': # Ensure every tick gets handled break return self.first_tick + self.stream_time def handle__end(self): parent = self.top_widget.get_parent_window() with self.top_widget.canvas: Color(0, 0, 0.2, 0.5) Rectangle(size=(parent.width, 40), pos=(0, parent.height / 2 - 20)) self.top_widget.add_widget(Label(text='Replay finished', width=self.top_widget.get_parent_window().width, pos=(0, parent.height / 2 - 5), height=10, color=(1, 1, 1, 1))) # Handlers for events from the log file: def handle_random(self, state): """Set the random state""" random.setstate(state) def handle_add_widget(self, cls): """Add a child widget""" self.content_widget.add_widget(cls()) def handle_dt(self, dt): """Tick the clock""" self.stream_time += dt def handle_down(self, attrs): """Generate a touch-down event""" self.handle__touch_event(attrs, 'on_touch_down') def handle_move(self, attrs): """Generate a touch-move event""" self.handle__touch_event(attrs, 'on_touch_move') def handle_up(self, attrs): """Generate a touch-up event""" self.handle__touch_event(attrs, 'on_touch_up') def handle__touch_event(self, attrs, event): """Generate any touch-down event""" touch = ReplayMotionEvent(None, attrs['id'], attrs) for name, value in attrs.items(): setattr(touch, name, value) self.content_widget.dispatch(event, touch) def handle_window_size(self, width, height): print width, height children_to_do = set([self.content_widget]) children_done = set() while children_to_do: child = children_to_do.pop() child.window_width = width child.window_height = height children_done.add(child) children_to_do.update(child.children) children_to_do.difference_update(children_done) self.content_widget.canvas.before.clear() with self.content_widget.canvas.before: PushMatrix() win = self.content_widget.get_parent_window() window_width = win.width window_height = win.height the_min = min(window_width / width, window_height / height) Scale(the_min) self.content_widget.canvas.after.clear() with self.content_widget.canvas.after: PopMatrix()
def __init__(self): self.ctx = RenderContext() self.root = root = Widget() for x in range(10000): root.add_widget(Widget()) self.ctx.add(self.root.canvas)
def run(self): o = Widget() for x in range(10000): o.add_widget(Widget())
class cWidgetScrollList(cWidgetPicture): """ WikiDoc:Doc WikiDoc:Context:Widgets WikiDoc:Page:Widgets-SCROLLLIST WikiDoc:TOCTitle:ScrollList = ScrollList = The scrolllist widget is a container widget to place lines of widget in a scrollable widget The scrolllist widget is based on the picture widget, please use the documentation for the common attributes To Identify the the source widget in actions triggered by widgets in the scroll list: The "SCROLLLISTVALUE" value is added to the action pars which refers to the widget text The "SCROLLLISTINDEX" index is added to the action pars which refers to the line order, eg: "0" is the first line in the list The "SCROLLLISTVARINDEX" index is added to the action pars which refers to the index number of the vararray The list of lines within the container is build from the vararry of minimum one widget within the line definition. So, one widget must have a caption with an array variable You can place all kind of widgets (with the exception of dropdowns in a row/line of the container All widgets got an index "[x]" added to the widget name, to manage them thought the actions The following attributes are additional attributes to common picture attributes <div style="overflow:auto; "> {| class="wikitable" ! align="left" | Attribute ! align="left" | Description |- |type |fixed: needs to be "SCROLLCONTAINER". Capital letters! |- |container |A string, which identifies the container AND all elements to place into the row of the container. If blank, a random value is used |- |rowheight |The rowheigth of a full line within the container: The line definition (all widgets in a line) must fir the this number |}</div> Below you see an example for a container definition <div style="overflow-x: auto;"><syntaxhighlight lang="xml"> <element name='Anchor1' type='ANCHOR' posx='%2' posy='%20' width='%30' height='%60' > <elements> <element name="ScrollBox Left" type="SCROLLLIST" picturenormal="background boxes" container="container_1" rowheight="%25" /> <element name='Anchor1 Inner' type='ANCHOR' height='%25' > <element name="First Button" type="BUTTON" posx="left" posy="top" height="%100" width="%40" picturenormal='button wide*' container="container_1" caption="First Button" action="Show Page" actionpars='{"pagename":"Page_Main"}' /> <element name="Second Button Top" type="BUTTON" posx="right" posy="top" height="%50" width="%60" picturenormal="button wide*" container="container_1" caption="$var(scrollcontent_button1_text[])" action="Show Page" actionpars='{"pagename":"Page_Main"}' /> <element name="Second Button Down" type="BUTTON" posx="right" posy="bottom" height="%50" width="%60" picturenormal="button wide*" container="container_1" caption="$var(scrollcontent_button2_text[])" action="Show Page" actionpars='{"pagename":"Page_Main"}' /> </element> </elements> </element> </syntaxhighlight></div> A second example with automated container assignment <div style="overflow-x: auto;"><syntaxhighlight lang="xml"> </syntaxhighlight></div> WikiDoc:End """ # noinspection PyUnusedLocal def __init__(self,**kwargs): super().__init__() self.oObjectContent:Union[FloatLayout,None] = None self.oObjectScroll:Union[ScrollView,None] = None self.uRowHeightInit:str = u'' self.iRowHeightScreen:int = 0 self.iRowHeight:int = 0 self.iNumRows:int = 0 self.aListChilds:List[cWidgetBase] = [] self.aChilds:List[cWidgetBase] = [] def InitWidgetFromXml(self,*,oXMLNode:Element,oParentScreenPage:cScreenPage, uAnchor:str) -> bool: """ Reads further Widget attributes from a xml node """ self.uRowHeightInit = GetXMLTextAttribute(oXMLNode=oXMLNode,uTag="rowheight",bMandatory=True,vDefault="%20") return super().InitWidgetFromXml(oXMLNode=oXMLNode,oParentScreenPage=oParentScreenPage ,uAnchor=uAnchor) def Create(self,oParent:Widget) -> bool: """ creates the Widget """ aChilds:List[cWidgetBase] aChilds:cWidgetBase aCaptions:List[str] self.iNumRows = 1 if super().Create(oParent): self.CreateScrollList() return True return False def GetChilds(self) -> List[cWidgetBase]: aRet:List[cWidgetBase] = [] # in case of recreation: Lets add the childs to the list of Screenpage widgets for oChild in self.aChilds: self.oParentScreenPage.RegisterWidget(oWidget=oChild) # and remove the from the local list del self.aChilds[:] # save a copy of the screenpage widgets locally and mark them for deletion for oWidget in self.oParentScreenPage.dWidgetsID.values(): if oWidget.uContainer==self.uContainer and oWidget!=self: aRet.append(oWidget) self.aChilds.append(copy(oWidget)) self.oParentScreenPage.aErrorWidgets.append(oWidget) return aRet def GetCaptions(self,aChilds:List[cWidgetBase]) -> List[List[Tuple[str,str]]]: aCaptions:List[List[Tuple[str,str]]] = [] aTmp:List[Tuple] tItem: Tuple aChildCaptions: List[Tuple[str, str]] for oChild in aChilds: aChildCaptions = [] if hasattr(oChild,'uOrgCaption'): if oChild.uOrgCaption.endswith("[])"): aTmp = Var_GetArrayEx(uVarName=oChild.uOrgCaption[5:-1], iLevel=1, bSort=False) for tItem in aTmp: aChildCaptions.append((u"$var(" + tItem[0] + ")",tItem[1])) self.iNumRows = max(self.iNumRows, len(aChildCaptions)) aCaptions.append(aChildCaptions) return aCaptions def CreateScrollList(self): aChilds:List[cWidgetBase] = self.GetChilds() aCaptions:List[List[Tuple[str,str]]] = self.GetCaptions(aChilds) self.iRowHeight = self.CalculateHeight(uHeight=self.uRowHeightInit, iAnchorHeight=self.iAnchorHeight) self.iRowHeightScreen = self.iRowHeight / self.oDef.fRationY self.oObjectScroll = ScrollView(size=self.oObject.size, pos=self.oObject.pos, do_scroll_x=False, scroll_type=['bars', 'content'], size_hint=(1, None), bar_width='10dp') self.oObjectContent = Widget(size=(self.oObject.width, self.iRowHeightScreen * self.iNumRows), size_hint=(1, None)) self.oObject.add_widget(self.oObjectScroll) self.oObjectScroll.add_widget(self.oObjectContent) self.CreateChilds(aChilds, aCaptions) def DeleteScrollList(self): self.DeleteChilds() self.oObjectScroll.remove_widget(self.oObjectContent) self.oObject.remove_widget(self.oObjectScroll) def CreateChilds(self,aChilds:List[cWidgetBase],aCaptions:List[List[Tuple[str,str]]]): iIndex:int iSubIndex: int yPos:int iAdd:int uVarIndex:str dTmpdActionPars:Dict = {} for u in range(self.iNumRows): iIndex = 0 uVarIndex = u'' # by purpose, we don't set it by child, we use the last known index, in case we have widgets without vars eg Buttons for oChild in aChilds: if hasattr(oChild,"dActionPars"): dTmpdActionPars = CopyDict(oChild.dActionPars) oTmpChild = copy(oChild) oTmpChild.uName = "%s[%s]" % (oTmpChild.uName, str(u)) oTmpChild.iHeightInit = self.iRowHeight * (oChild.iHeightInit/oChild.iAnchorHeight) oTmpChild.iPosXInit = oTmpChild.iPosXInit - self.iPosXInit oTmpChild.iGapY = (self.iPosY *-1) + (self.iRowHeightScreen * (u + 0)) if isinstance(oChild,cWidgetSwitch): if oTmpChild.uDestVar: oTmpChild.uDestVar=oTmpChild.uDestVar+"_"+str(u) if len(aCaptions[iIndex]) > u: if hasattr(oTmpChild,"uCaption"): oTmpChild.uOrgCaption = aCaptions[iIndex][u][0] oTmpChild.uCaption = ReplaceVars(aCaptions[iIndex][u][0]) uVarIndex = ReplaceVars(aCaptions[iIndex][u][1]) oTmpChild.Create(self.oObjectContent) if hasattr(oTmpChild,"dActionPars"): try: oTmpChild.dActionPars["SCROLLLISTVALUE"] = oTmpChild.oObject.text except: oTmpChild.dActionPars["SCROLLLISTVALUE"] = "" oTmpChild.dActionPars["SCROLLLISTINDEX"] = str(u) oTmpChild.dActionPars["SCROLLLISTVARINDEX"] = uVarIndex self.aListChilds.append(oTmpChild) self.oParentScreenPage.aAddWidgets.append(oTmpChild) oChild.dActionPars=dTmpdActionPars iIndex += 1 def DeleteChilds(self): for oChild in self.aListChilds: self.oObjectContent.remove_widget(oChild.oObject) oChild.oObject = None self.oParentScreenPage.RemoveWidget(oWidget=oChild) del self.aListChilds[:] self.iNumRows = 0 def UpdateWidget(self) -> None: super().UpdateWidget() if self.oObjectScroll is not None: self.DeleteScrollList() self.CreateScrollList() self.oParentScreenPage.PostHandleErrorWidgets() return def EnableWidget(self, *, bEnable:bool) -> bool: super(cWidgetScrollList, self).EnableWidget(bEnable=bEnable) if self.oObjectScroll: if bEnable: self.oObjectScroll.opacity=1 else: self.oObjectScroll.opacity=0 return self.bIsEnabled
def run(self): o = [] for x in range(10000): o.append(Widget())
def __init__(self, **kwargs): super().__init__() self.done = False self.modality_list = kwargs.get('modality_list') self.msg = kwargs.get('msg') self.cols = 1 self.return_vals = None self.fpop = None if not self.modality_list: pass else: self.changes = dict.fromkeys(set(self.modality_list), []) header = BoxLayout( cols=4, size_hint_y=0.1, ) header.add_widget( Label(text='Fuse', size_hint_x=None, width=10, bold=True, text_size=self.size, halign="right", valign="middle")) header.add_widget( Label(text='Modality', size_hint_x=None, width=290, bold=True, text_size=self.size, color=(0.05, 0.69, 0.29, 1.0), halign="left", valign="middle")) header.add_widget( Label(text='Similarity ', size_hint_x=None, width=100, bold=True, text_size=self.size, halign="right", valign="middle")) header.add_widget( Label(text='Dissimilarity ', size_hint_x=None, width=100, bold=True, text_size=self.size, halign="right", valign="middle")) self.add_widget(header) layout = GridLayout(cols=1, size_hint_y=0.8) if '_ORIGINAl' in self.modality_list: original = [ x for x in self.modality_list if "_ORIGINAL" in self.modality_list ] else: original = self.modality_list for mod in original: row = BoxLayout() fuse_chk = CheckBox(width=30, height=30, size_hint_x=None, size_hint_y=None, active=True) row.add_widget(fuse_chk) row.add_widget( Widget(width=15, height=30, size_hint_x=None, size_hint_y=None)) mod_name = TextInput(text=mod, width=250, height=30, size_hint_x=None, size_hint_y=None, multiline=False) row.add_widget(mod_name) row.add_widget( Widget(width=60, height=30, size_hint_x=None, size_hint_y=None)) similarity_chk = CheckBox(width=30, height=30, size_hint_x=None, size_hint_y=None, active=True, group=mod) row.add_widget(similarity_chk) row.add_widget( Widget(width=60, height=30, size_hint_x=None, size_hint_y=None)) dissimilarity_chk = CheckBox(width=50, height=30, size_hint_x=None, size_hint_y=None, group=mod) row.add_widget(dissimilarity_chk) layout.add_widget(row) self.changes[mod] = [ mod_name, similarity_chk, dissimilarity_chk, fuse_chk ] layout.add_widget(Label(text='')) self.add_widget(layout) update_btn = Button(text='Update', size_hint_y=0.1, bold=True, background_color=(0.05, 0.69, 0.29, 1.0)) update_btn.bind(on_press=self.update_dicts) self.add_widget(update_btn)
def __init__(self, **kwargs): self.player_velocity = [0.0, 0.0, 0.0] self.ops = [] self.frames_per_second = 60.0 self.gl_widget = Widget() self.hud_form = BoxLayout(orientation="vertical", size_hint=(1.0, 1.0)) self.hud_buttons_form = BoxLayout(orientation="horizontal", size_hint=(1.0, 0.1)) #fix incorrect keycodes if present (such as in kivy <= 1.8.0): if (Keyboard.keycodes["-"]==41): Keyboard.keycodes["-"]=45 if (Keyboard.keycodes["="]==43): Keyboard.keycodes["="]=61 try: self._keyboard = Window.request_keyboard( self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self._keyboard.bind(on_key_up=self._on_keyboard_up) except: print("[ TestingKivy3D ] Could not finish loading" + \ " keyboard (keyboard may not be present).") view_traceback() # self.bind(on_touch_down=self.canvasTouchDown) self.gl_widget.canvas = RenderContext(compute_normal_mat=True) self.gl_widget.canvas["_world_light_dir"] = (0.0, 0.5, 1.0) self.gl_widget.canvas["_world_light_dir_eye_space"] = (0.0, 0.5, 1.0) #rotated in update_glsl self.gl_widget.canvas["camera_light_multiplier"] = (1.0, 1.0, 1.0, 1.0) # self.gl_widget.canvas.shader.source = resource_find('simple1b.glsl') # self.gl_widget.canvas.shader.source = resource_find('shade-kivyops-standard.glsl') # NOT working # self.gl_widget.canvas.shader.source = resource_find('shade-normal-only.glsl') #partially working # self.gl_widget.canvas.shader.source = resource_find('shade-texture-only.glsl') # self.gl_widget.canvas.shader.source = resource_find('shade-kivyops-minimal.glsl') # NOT working # self.canvas.shader.source = resource_find('simple.glsl') # self.canvas.shader.source = resource_find('simple1b.glsl') # self.canvas.shader.source = resource_find('shade-kivyops-standard.glsl') # self.canvas.shader.source = resource_find('shade-normal-only.glsl') # self.canvas.shader.source = resource_find('shade-texture-only.glsl') # self.canvas.shader.source = resource_find('shade-kivyops-minimal.glsl') # self.canvas.shader.source = resource_find('fresnel.glsl') # self.gl_widget.canvas.shader.source = resource_find('simple1b.glsl') self.gl_widget.canvas.shader.source = resource_find('fresnel.glsl') #formerly, .obj was loaded here using load_obj (now calling program does that) #print(self.gl_widget.canvas.shader) #just prints type and memory address super(TestingKivy3D, self).__init__(**kwargs) self.cb = Callback(self.setup_gl_context) self.gl_widget.canvas.add(self.cb) self.gl_widget.canvas.add(PushMatrix()) self._contexts = InstructionGroup() #RenderContext(compute_normal_mat=True) self.gl_widget.canvas.add(self._contexts) self.finalize_canvas() self.add_widget(self.gl_widget) # self.hud_form.rows = 1 self.add_widget(self.hud_form) self.debug_label = Factory.Label(text="...") self.hud_form.add_widget(self.debug_label) self.hud_form.add_widget(self.hud_buttons_form) # self.inventory_prev_button = Factory.Button(text="<", id="inventory_prev_button", size_hint=(.2,1.0), on_press=self.inventory_prev_button_press) self.use_button = Factory.Button(text="0: Empty", id="use_button", size_hint=(.2,1.0), on_press=self.inventory_use_button_press) # self.inventory_next_button = Factory.Button(text=">", id="inventory_next_button", size_hint=(.2,1.0), on_press=self.inventory_next_button_press) # self.hud_buttons_form.add_widget(self.inventory_prev_button) self.hud_buttons_form.add_widget(self.use_button) # self.hud_buttons_form.add_widget(self.inventory_next_button) #Window.bind(on_motion=self.on_motion) # TODO ?: formerly didn't work, but maybe failed since used Window. instead of self--see <https://kivy.org/docs/api-kivy.input.motionevent.html> Clock.schedule_interval(self.update_glsl, 1.0 / self.frames_per_second) # self._touches = [] # self.scene = KivyGlops() # self.scene = ObjFile(resource_find("monkey.obj")) # self.scene.load_obj(resource_find("barrels triangulated (Costinus at turbosquid).obj")) # self.scene.load_obj(resource_find("barrel.obj")) # self.scene.load_obj(resource_find("KivyGlopsDemoScene.obj")) # self.scene.load_obj("testnurbs-all-textured.obj") self.this_op = Testing3DWidget() #with self.canvas: # self.cb = Callback(self.setup_gl_context) # PushMatrix() # self.setup_scene() # PopMatrix() # self.cb = Callback(self.reset_gl_context) self.add_op(self.this_op) self.camera_translate_instruction = Translate() self.camera_translate_instruction.x = -1.0 self.look_point = [0, 0, 0] self.rot = Rotate(1, 0, 1, 0) Clock.schedule_interval(self.update_glsl, 1 / 60.)
def FractionEq(self): def goBack(self): Fl.clear_widgets() GameSelector(self) # all these update_x are for window resizing def update_rect(*args): width = Fl.size[0] / 5 * 3 height = Fl.size[1] / 5 * 3 rec.pos = ((Fl.width / 5), (Fl.height * (3 / 11))) rec.size = (width, height) def update_line(*args): width = Fl.size[0] / 5 * 3 height = Fl.size[1] / 5 * 3 for x in range(1, denominator): line.points = [((width / denominator) * x) + Fl.size[0] / 5, (Fl.height * (13 / 15)), ((width / denominator) * x) + Fl.size[0] / 5, (Fl.height * (5 / 18))] line.dash_length = 60 line.dash_offset = 60 def update_numerator(*args): width = ((Fl.size[0] / 5 * 3) / denominator) * numerator height = Fl.size[1] / 5 * 3 line.dash_length = 60 line.dash_offset = 60 rec2.pos = ((Fl.width / 5), (Fl.height * (3 / 11))) rec2.size = (width, height) def update_sliderNum(*args): width = Fl.size[0] / 5 * 3 height = Fl.size[1] / 5 * 3 for x in range(1, slider.value): line2.points = [((width / slider.value) * x) + Fl.size[0] / 5, (Fl.height * (13 / 15)), ((width / slider.value) * x) + Fl.size[0] / 5, (Fl.height * (5 / 18))] # draws lines on canvas def sliderLines(): with wid3.canvas: wid3.canvas.clear() Color(.1, .1, .1) for x in range(1, slider.value): line2 = Line(points=[ (((width / slider.value) * x) + Fl.size[0] / 5), (Fl.height * (13 / 15)), (((width / slider.value) * x) + Fl.size[0] / 5), (Fl.height * (5 / 18)) ], width=4, color=(.23, .6, .2)) Fl.add_widget(wid3) def sliderValFunc(instance, val): sliderVal.text = "%d" % val Fl.remove_widget(wid3) sliderLines() return sliderVal.text def newQuestionFunc(self): randomQuestion = Fractions.level1() questionLabel.text = randomQuestion currFraction = questionLabel.text.split("/") denominator = int(currFraction[1]) Fl.clear_widgets() FractionEq(self) # checks students response def answerChecker(self): if int(slider.value) % denominator == 0: equivNumerator = int(slider.value) / denominator equiviFrac = int(equivNumerator) * numerator newFrac = "%i/%i" % (equiviFrac, slider.value) response = "%i/%i" % (equiviFrac, int(slider.value)) checkAnswerBtn.background_normal = '' checkAnswerBtn.background_color = (.1, .7, .2, .9) rightSound.play() rightResponse = TimedRightResponse() correctResp = Label(text='%s is equal to %s' % (str(questionLabel.text), str(newFrac)), color=(0, 0, 0, 1), font_size=62, pos_hint={ "x": .4, 'y': .06 }, size_hint=(.2, .1)) Fl.add_widget(correctResp) else: wrongSound.play() checkAnswerBtn.background_normal = ('') checkAnswerBtn.background_color = (1, .3, .3, .9) checkAnswerBtn.text = ("TRY AGAIN") try: sql = "UPDATE login SET incorrect = incorrect || ' " + str( slider.value) + str("/") + str( denominator) + ",' WHERE user = '******';" cursor.execute(sql) conn.commit() print(sql) except: sql = "UPDATE login SET incorrect = incorrect || '" + str( slider.value) + str("/") + str( denominator) + "' WHERE user = "******"; " print(sql) print("Failed to add inc. ans") wrongResponse = TimedWrongResponse() class TimedRightResponse(Widget): myCount = 0 boolRun = True def __init__(self, **kwargs): Clock.schedule_interval(self.update, 1) super(TimedRightResponse, self).__init__(**kwargs) def update(self, *args): if self.boolRun == True: if self.myCount < 1: print(self.myCount) self.myCount += 1 else: checkAnswerBtn.background_color = (.4, .4, .4, 1) checkAnswerBtn.text = 'Check Answer' self.myCount = 0 self.boolRun = False class TimedWrongResponse(Widget): myCount = 0 boolRun = True def __init__(self, **kwargs): Clock.schedule_interval(self.update, 1) super(TimedWrongResponse, self).__init__(**kwargs) def update(self, *args): if self.boolRun == True: if self.myCount < 1: print(self.myCount) self.myCount += 1 else: checkAnswerBtn.background_color = (.4, .4, .4, 1) checkAnswerBtn.text = 'Check Answer' self.myCount = 0 self.boolRun = False wid = Widget() wid1 = Widget() wid2 = Widget() # --------Fix me------------------- dropdown = DropDown() dropBtn1 = Button(text='level 1', size_hint_y=None, height=44) dropBtn1.bind(on_release=lambda btn: dropdown.select(dropBtn1.text)) dropdown.add_widget(dropBtn1) dropBtn2 = Button(text='level 2', size_hint_y=None, height=44) dropBtn2.bind(on_release=lambda btn: dropdown.select(dropBtn2.text)) dropdown.add_widget(dropBtn2) dropBtn3 = Button(text='level 3', size_hint_y=None, height=44) dropBtn3.bind(on_release=lambda btn: dropdown.select(dropBtn3.text)) dropdown.add_widget(dropBtn3) mainbutton = Button(text='Level Selector', size_hint=(.1, .08), pos_hint={ "x": .85, "y": .79 }) mainbutton.bind(on_release=dropdown.open) dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x)) # -------------------------- logo = Image(source='Images/SH_box2BSHSUName_021_horizontalstack_3_29.png', allow_stretch=True, pos_hint={ "x": .01, 'y': .9 }, size_hint=(.2, .1)) backBtnImage = Image(source='Images/eback-button-6-921315_2_15.png', pos_hint={ "x": .01, 'y': .83 }, size_hint=(.04, .07), keep_ratio=True) backBtn = Button(pos_hint={ "x": .01, 'y': .83 }, size_hint=(.141, .07), background_color=(1, 1, 1, .01)) backBtn.bind(on_release=goBack) questionLabel = Label(text=Fractions.level1(), font_size=68, color=(.1, .1, .1, 1), pos_hint={ 'x': .5, 'y': .93 }, size_hint=(.001, .001)) slider = Slider(min=1, max=28, step=1, pos_hint={ 'x': .2, 'y': .15 }, size_hint=(.6, .05)) slider.bind(value=sliderValFunc) sliderVal = Label(text='1', font_size=68, color=(.1, .1, .1, 1), pos_hint={ 'x': .5, 'y': .22 }, size_hint=(.001, .001)) newQuestionBtn = Button(text='New Question', size_hint=(.1, .08), pos_hint={ 'x': .25, 'y': .05 }) newQuestionBtn.bind(on_release=newQuestionFunc) checkAnswerBtn = Button( text='Check Answer', # background_color = (1,1,1,1), size_hint=(.1, .08), pos_hint={ 'x': .65, 'y': .05 }) checkAnswerBtn.bind(on_release=answerChecker) currFraction = questionLabel.text.split("/") numerator = int(currFraction[0]) denominator = int(currFraction[1]) width = Fl.size[0] / 5 * 3 height = Fl.size[1] / 5 * 3 # draws blank canvas with wid.canvas: Color(.9, .9, .9) rec = Rectangle(size=(width, height), pos=((Fl.width / 2) - (Fl.width / 4), (Fl.height / 2) - (Fl.height / 4))) wid.bind(pos=update_rect) wid.bind(size=update_rect) # draws smallest denominator lines with wid1.canvas: Color(.1, .1, .1) for x in range(1, denominator): line = Line(points=[(((width / denominator) * x) + Fl.size[0] / 5), (Fl.height * (13 / 15)), (((width / denominator) * x) + Fl.size[0] / 5), (Fl.height * (5 / 18))], dash_length=60, dash_offset=60, width=1, color=(.23, .6, .2)) wid1.bind(pos=update_line) wid1.bind(size=update_line) # draws numerator box with wid2.canvas: Color(.3, .3, .6) rec2 = Rectangle(size=((width / denominator) * numerator, height), pos=((Fl.width / 2) - (Fl.width / 3), (Fl.height / 2) - (Fl.height / 4))) wid2.bind(pos=update_numerator) wid2.bind(size=update_numerator) # draws slider lines # make this a function!! Fl.add_widget(logo) Fl.add_widget(backBtnImage) Fl.add_widget(backBtn) Fl.add_widget(slider) Fl.add_widget(questionLabel) Fl.add_widget(sliderVal) Fl.add_widget(newQuestionBtn) Fl.add_widget(checkAnswerBtn) Fl.add_widget(wid) Fl.add_widget(wid1) Fl.add_widget(wid2) Fl.add_widget(mainbutton)
def build(self): Game = Widget() Game.add_widget(HohenGame()) Window.size = int(metrics.dp(1366)), int(metrics.dp(768)) #Window.fullscreen = True return Game
def PieFraction(self): width = Fl.size[0] / 5 * 2 cwid = Widget() cirLabel = Label(text="each slice is 100% of the circle", color=(0, 0, 0, 1), font_size=62, pos_hint={ "x": .4, 'y': .06 }, size_hint=(.2, .1)) def draw(): def update_cir(*args): width = Fl.size[0] / 5 * 2 cir.pos = ((Fl.width / 2) - (Fl.width / 5), (Fl.width / 2) - (Fl.width / 3)) cir.size = (width, width) with cwid.canvas: for x in range(slider.value): Color(random.random(), random.random(), random.random()) cir = Ellipse( size=(width, width), pos=((Fl.width / 2) - (Fl.width / 5), (Fl.width / 2) - (Fl.width / 3)), angle_start=(360 / slider.value) * x, angle_end=((360 / slider.value) * x) + (360 / slider.value), ) cwid.bind(pos=update_cir) cwid.bind(size=update_cir) update_cir() Fl.add_widget(cwid) update_cir() return cirLabel def sliderValFunc(instance, val): sliderVal.text = "%d" % val Fl.remove_widget(cwid) cwid.canvas.clear() draw() cirLabel.text = "each slice is " + \ str(format(100/slider.value, '.2f'))+"% of the circle" return sliderVal.text def goBack(self): Fl.clear_widgets() GameSelector(self) logo = Image(source='Images/SH_box2BSHSUName_021_horizontalstack_3_29.png', allow_stretch=True, pos_hint={ 'x': .01, 'y': .9 }, size_hint=(.2, .1)) backBtnImage = Image(source='Images/eback-button-6-921315_2_15.png', pos_hint={ 'x': .01, 'y': .83 }, size_hint=(.04, .07), keep_ratio=True) backBtn = Button(pos_hint={ "x": .01, 'y': .83 }, size_hint=(.141, .07), background_color=(1, 1, 1, .01)) backBtn.bind(on_release=goBack) slider = Slider(min=1, max=24, step=1, pos_hint={ 'x': .2, 'y': .15 }, size_hint=(.6, .05)) slider.bind(value=sliderValFunc) sliderVal = Label(text='1', font_size=68, color=(.1, .1, .1, 1), pos_hint={ 'x': .5, 'y': .22 }, size_hint=(.001, .001)) draw() Fl.add_widget(logo) Fl.add_widget(backBtnImage) Fl.add_widget(backBtn) Fl.add_widget(slider) Fl.add_widget(sliderVal) Fl.add_widget(cirLabel)
def build(self): base = Widget() learn = Learning() base.add_widget(learn) learn.start() return base
import random import sqlite3 import hashlib Window.clearcolor = (1, 1, 1, 1) Window.size = (1200, 800) # sqlite connection conn = sqlite3.connect("UserInfo.db") cursor = conn.cursor() cursor.execute( "CREATE TABLE IF NOT EXISTS login(user TEXT NOT NULL, password TEXT, incorrect TEXT);" ) Fl = FloatLayout() wid3 = Widget() # load sounds rightSound = SoundLoader.load('Audio/success.ogg') wrongSound = SoundLoader.load('Audio/wrong.ogg') studentName = "" # applet 1 def FractionEq(self): def goBack(self): Fl.clear_widgets() GameSelector(self) # all these update_x are for window resizing
def setUp(self): self.a = Animation(x=100, d=1, t='out_bounce') self.a += Animation(x=0, d=1, t='out_bounce') self.w = Widget()
def build(self): top = Widget() top.add_widget(Label(center=top.center, text='Hello there\nnanners city!')) #Window.size = top.children[0].size return top
def build(self): if not self.root: return Widget()
def make_tasks(self): su = self.engine.screen_utils lu = LanguageUtils() field_task = Task(self.grid, lu.set_string('tutorial_field'), 'pass', su) self.tasks.append(field_task) rule_scroll_view_task = Task( self.rules_scroll_view.ids.rule_scroll_view, lu.set_string('tutorial_rule_list'), 'pass', su) self.tasks.append(rule_scroll_view_task) first_box_in_rule_task = Task( self.rules_scroll_view.ids.grid.children[-1].children[-1], lu.set_string('tutorial_rule_left_side'), 'pass', su) self.tasks.append(first_box_in_rule_task) first_in_right_side = self.rules_scroll_view.ids.grid.children[ -1].children[1] second_in_right_side = self.rules_scroll_view.ids.grid.children[ -1].children[0] right_side_of_the_rule_task = Task( first_in_right_side, lu.set_string('tutorial_rule_right_side'), 'pass', su, second_in_right_side) self.tasks.append(right_side_of_the_rule_task) arrow_task = Task( self.rules_scroll_view.ids.grid.children[-1].children[2], lu.set_string('tutorial_rule_arrow'), 'pass', su) self.tasks.append(arrow_task) box_task = Task(self.game_widgets[0], lu.set_string('tutorial_select_box'), 'act', su) self.tasks.append(box_task) rule_scroll_view_task = Task( self.rules_scroll_view.ids.rule_scroll_view, lu.set_string('tutorial_selected_box_rules'), 'pass', su) self.tasks.append(rule_scroll_view_task) '''...children[-1] -- пиздецкий костыль. Поскольку rule_widgets нумеруются снизу, получается, что таким образом я получаю координаты верхнего rule_widget-a, хотя когда эта task становится актуальна, там уже другой rule_widget, и он всего один.''' rule_widget_task = Task(self.rules_scroll_view.ids.grid.children[-1], lu.set_string('tutorial_apply_rule'), 'act', su) self.tasks.append(rule_widget_task) wow_task = Task(Widget(size=(0, 0)), lu.set_string('cool'), 'pass', su) self.tasks.append(wow_task) target_field_button_task = Task(self.parent.ids.field_switch, lu.set_string('tutorial_switch'), 'act', su) self.tasks.append(target_field_button_task) target_field_task = Task(self.grid, lu.set_string('target_field'), 'pass', su) self.tasks.append(target_field_task) game_field_button_task = Task(self.parent.ids.field_switch, lu.set_string('tutorial_switch_again'), 'act', su) self.tasks.append(game_field_button_task) final_task = Task(Widget(size=(0, 0)), lu.set_string('tutorial_your_turn'), 'pass', su) self.tasks.append(final_task) '''Tasks are stored stack-wise''' self.tasks.reverse() self.cur_task = self.tasks[-1] self.add_widget(self.cur_task)
def __init__(self, **kwargs): self.padding = (0, 0, 0, 0) self.tab_label = TooltipTabLabel(tab=self, tooltip_text=truncate( self.tooltip_text)) Widget.__init__(self, **kwargs)
def build(self): """Build the user interface.""" wid = Widget() self.myWid = MyWidget() wid.add_widget(self.myWid) self.counter = Label(text="0") labelA = Label(text=self.get_scores()[0]) labelB = Label(text=self.get_scores()[1]) labels = (labelA, labelB) self.labels = labels self.wid = wid self.agentA_spinner = Spinner( text='Agent A', text_size=(95, None), haligh="center", shorten=True, values=sorted([agent for agent in ALL_AGENTS.keys()]) + ["Agent A"], size=(100, 44)) agentB_spinner = Spinner( text='Agent B', text_size=(95, None), shorten=True, values=sorted([agent for agent in ALL_AGENTS.keys()]) + ["Agent B"], size=(100, 44)) self.maps_spinner = Spinner( text='Maps', text_size=(95, None), shorten=True, values=sorted([map for map in ALL_MAPS.keys()]) + ["Maps"], size=(100, 44)) self.agentA_spinner.bind(text=self.select_agent_A) agentB_spinner.bind(text=self.select_agent_B) self.maps_spinner.bind(text=self.select_map) btn_load = Button(text='Load', on_press=partial(self.load_env, labels, wid)) btn_step = Button(text='Step >', on_press=partial(self.btn_step, labels, wid)) self.btn_100step = ToggleButton(text='100 Step >', on_press=partial( self.btn_100step, self.running_step, labels, wid)) self.btn_run = ToggleButton(text='Run >>', on_press=partial(self.btn_run, self.running_step, labels, wid)) btn_stop = Button(text='Stop [ ]', on_press=partial(self.btn_stop, self.running_step)) self.partial_reset = partial( self.reset_all, labels, (self.agentA_spinner, agentB_spinner, self.maps_spinner), wid) btn_reset = Button(text='Reset', on_press=self.partial_reset) Window.bind(on_resize=self.on_resize) action_layout = BoxLayout(size_hint=(1, None), height=50) action_layout.add_widget(btn_load) action_layout.add_widget(btn_step) action_layout.add_widget(self.btn_100step) action_layout.add_widget(self.counter) action_layout.add_widget(self.btn_run) action_layout.add_widget(btn_stop) action_layout.add_widget(btn_reset) agents_layout = BoxLayout(size_hint=(1, None), height=50) agents_layout.add_widget(self.agentA_spinner) agents_layout.add_widget(labelA) agents_layout.add_widget(agentB_spinner) agents_layout.add_widget(labelB) agents_layout.add_widget(self.maps_spinner) root = BoxLayout(orientation='vertical') root.add_widget(wid) root.add_widget(action_layout) root.add_widget(agents_layout) return root
def __init__(self, fretboard, midi_config, tuning, **kwargs): super(NoteTrainerPanel, self).__init__(**kwargs) self.fretboard = fretboard self.midi_config = midi_config self.tuning = tuning self.orientation = 'vertical' self.padding = 10 self.spacing = 10 button_panel = BoxLayout(orientation='horizontal', size_hint=(1, 0.1)) button_panel.height = pt(20) button_panel.center_x = self.center_x self.play_button = Button(id='play', text='play', on_press=self.button_press, size_hint=(None, None)) # self.play_button.height = pt(20) self.play_label_text = 'play' self.curr_line_num = -1 self.bind(play_label_text=self.update_play_button_text) self.bind(current_note=self.update_current_note) button_panel.add_widget(Widget()) # button_panel.add_widget(rewind_button) button_panel.add_widget(self.play_button) # button_panel.add_widget(stop_button) button_panel.add_widget(Widget()) self.add_widget(button_panel) notes_container = BoxLayout(orientation='horizontal', size_hint=(1, 0.1)) notes_panel = GridLayout(cols=14, row_force_default=True, row_default_height=40) self.note_label_a = Label(halign='right', text='A:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_a = CheckBox(active=True) self.note_checkbox_a.bind(active=partial(self.note_checked, 'A')) notes_panel.add_widget(self.note_label_a) notes_panel.add_widget(self.note_checkbox_a) self.note_label_b = Label(halign='right', text='B:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_b = CheckBox(active=True) self.note_checkbox_b.bind(active=partial(self.note_checked, 'B')) notes_panel.add_widget(self.note_label_b) notes_panel.add_widget(self.note_checkbox_b) self.note_label_c = Label(halign='right', text='C:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_c = CheckBox(active=True) self.note_checkbox_c.bind(active=partial(self.note_checked, 'C')) notes_panel.add_widget(self.note_label_c) notes_panel.add_widget(self.note_checkbox_c) self.note_label_d = Label(halign='right', text='D:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_d = CheckBox(active=True) self.note_checkbox_d.bind(active=partial(self.note_checked, 'D')) notes_panel.add_widget(self.note_label_d) notes_panel.add_widget(self.note_checkbox_d) self.note_label_e = Label(halign='right', text='E:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_e = CheckBox(active=True) self.note_checkbox_e.bind(active=partial(self.note_checked, 'E')) notes_panel.add_widget(self.note_label_e) notes_panel.add_widget(self.note_checkbox_e) self.note_label_f = Label(halign='right', text='F:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_f = CheckBox(active=True) self.note_checkbox_f.bind(active=partial(self.note_checked, 'F')) notes_panel.add_widget(self.note_label_f) notes_panel.add_widget(self.note_checkbox_f) self.note_label_g = Label(halign='right', text='G:', font_size='16sp', color=(0, 0, 0, 1)) self.note_checkbox_g = CheckBox(active=True) self.note_checkbox_g.bind(active=partial(self.note_checked, 'G')) notes_panel.add_widget(self.note_label_g) notes_panel.add_widget(self.note_checkbox_g) notes_container.add_widget(Widget()) notes_container.add_widget(notes_panel) notes_container.add_widget(Widget()) self.add_widget(notes_container) options_container = BoxLayout(orientation='horizontal', size_hint=(1, 0.1)) options_panel = GridLayout(cols=14, row_force_default=True, row_default_height=40) self.accidental_label_none = Label(halign='right', text="none:", font_size='16sp', color=(0, 0, 0, 1)) self.accidental_checkbox_none = CheckBox(group='accidentals', active=False) options_panel.add_widget(self.accidental_label_none) options_panel.add_widget(self.accidental_checkbox_none) self.accidental_label_sharp = Label(halign='right', text="#'s:", font_size='16sp', color=(0, 0, 0, 1)) self.accidental_checkbox_sharp = CheckBox(group='accidentals') options_panel.add_widget(self.accidental_label_sharp) options_panel.add_widget(self.accidental_checkbox_sharp) self.accidental_label_flat = Label(halign='right', text="b's:", font_size='16sp', color=(0, 0, 0, 1)) self.accidental_checkbox_flat = CheckBox(group='accidentals', active=True) options_panel.add_widget(self.accidental_label_flat) options_panel.add_widget(self.accidental_checkbox_flat) self.show_notes_label = Label(halign='right', text="show notes:", font_size='16sp', color=(0, 0, 0, 1)) self.show_notes_checkbox = CheckBox(active=True) self.show_notes_checkbox.bind(active=self.show_notes) options_panel.add_widget(self.show_notes_label) options_panel.add_widget(self.show_notes_checkbox) self.require_all_label = Label(halign='right', text="require all:", font_size='16sp', color=(0, 0, 0, 1)) self.require_all_checkbox = CheckBox() options_panel.add_widget(self.require_all_label) options_panel.add_widget(self.require_all_checkbox) self.error_sound_label = Label(halign='right', text="beep on error:", font_size='16sp', color=(0, 0, 0, 1)) self.error_sound_checkbox = CheckBox() options_panel.add_widget(self.error_sound_label) options_panel.add_widget(self.error_sound_checkbox) options_container.add_widget(Widget()) options_container.add_widget(options_panel) options_container.add_widget(Widget()) self.add_widget(options_container) self.current_note_label = Label(halign='center', text="?", font_size='340sp', color=(0, 0.1, 0.8, 1), size_hint=(1, .7)) self.add_widget(self.current_note_label) fretboard.set_target_tone_callback(self)
def build(self): p.init() top = Widget() top.add_widget(Main()) return top