def build(self): self.operators = ["^", " / ", " * ", " + ", " - "] # operators /,*,+,- are added with leading and trailing space to make # identification possible between that and negative numbers self.last_was_operator = None self.last_button = None main_layout = MDBoxLayout(orientation="vertical") self.solution = MDTextFieldRect(multiline=False, readonly=True, size_hint=[1, None], halign="right", height="80sp", font_size='55sp') main_layout.add_widget(self.solution) buttons = [["", "C", "<-", "^"], ["", "", "", " / "], ["7", "8", "9", " * "], ["4", "5", "6", " - "], ["1", "2", "3", " + "], ["+/-", "0", ".", "="]] for row in buttons: h_layout = MDBoxLayout() for label in row: button = MDRectangleFlatButton(text=label, pos_hint={ "center_x": 0.5, "center_y": 0.5 }, size_hint=(1, 1), font_size='20sp') button.bind(on_press=self.on_button_press) h_layout.add_widget(button) main_layout.add_widget(h_layout) return main_layout
def potential_clients(self): # Checking if there are plot on result screen if self.graph is not None: self.root.ids.box.remove_widget(self.graph) # Reseting flag self.check_graph = False # Check if result screen already has clients list if self.check_clients == False: # Getting dataframe from .csv file df = pd.read_csv('csv.csv') # Formating data to object df['Дата'] = pd.to_datetime(df['Дата']) # Adding button, that leads to result screen btn = MDRectangleFlatButton(text='Go to result screen', pos_hint={'center_x': .5, 'center_y': .4}) # Binding button with method btn.bind(on_press=self.switch) # Adding button self.root.ids.choice_screen.add_widget(btn) # Getting dataframe, with clients that made purchases in 2018 and 2019 years sr = df[df['Дата'].dt.year == 2018] sr1 = df[df['Дата'].dt.year == 2019] srr = sr[['Наименование']] srr1 = sr1[['Наименование']] ch = srr.values.tolist() ch1 = srr1.values.tolist() for name in ch: df.drop(df[df['Наименование'] == name[0]].index, inplace=True) for name in ch1: df.drop(df[df['Наименование'] == name[0]].index, inplace=True) abc = df['Наименование'].tolist() s = set(abc) text = 'Список потенциальных заказчиков:' for name in s: text += '\n\n' + name + "," # self.root.ids.result_text.text = text self.clients = MDLabel(text=text, halign='center') self.root.ids.result_screen.add_widget(self.clients) self.check_clients = True
class pp(Screen): def __init__(self,**kwargs): super().__init__(**kwargs) self.btn1=MDRectangleFlatButton(text='Camera',pos_hint={'center_x': 0.5,'center_y' : 0.60}) self.btn2=MDRectangleFlatButton(text='Gallery',pos_hint={'center_x': 0.5,'center_y' : 0.45}) self.btn1.bind(on_press=button_to_camera) self.add_widget(self.btn1) self.add_widget(self.btn2)
def winners(self): # Checking if there are list of potential client on the result screent # and if there are, we are deleting this list from screen so that we can place plot on this screen if self.clients is not None: # Deleting list of potential clients self.root.ids.result_screen.remove_widget(self.clients) # Reseting flag self.check_clients = False # Checking if result screen already has a plot, and if not we are adding it if self.check_graph == False: # Dataframe that we get from .csv file df = pd.read_csv('csv.csv') # Counting winners from first column df1 = df['Победитель1'].value_counts()[df['Победитель1'].value_counts() >= 2] # Counting winners from second column df2 = df['Победитель2'].value_counts()[df['Победитель2'].value_counts() >= 2] # Adding dataframes into one dataframe frames = [df1, df2] df3 = pd.concat(frames) # Creating horizontal bar plot df3.plot.barh() plt.subplots_adjust(left=0.5) # Saving plot into image plt.savefig("image.png", bbox_inches='tight', dpi=150) # Creating image widget image = AsyncImage(source='image.png', ) #Adding image to class variable self.graph = image self.root.ids.box.add_widget(image) # Adding button "Go to result" btn = MDRectangleFlatButton(text='Go to result screen', pos_hint={'center_x': .5, 'center_y': .4}) # Binding button with method, which allows us go to result screen btn.bind(on_press=self.switch) # Adding button to screen self.root.ids.choice_screen.add_widget(btn) # Setting flag self.check_graph = True
def show_message(self, message): ok_btn = MDRectangleFlatButton(text="OK") ok_btn.bind(on_press=self.close) self.dialog = MDDialog ( title="INFO", text=message, size_hint=(.8, 1), buttons=[ok_btn] ) self.dialog.open()
def delete(self, instance): self.class_id = self.buttons_dict[instance] btn1 = MDRectangleFlatButton(text='Yes') btn1.bind(on_press=self.yes) btn2 = MDRectangleFlatButton(text='No') btn2.bind(on_press=self.no) self.dialog = MDDialog(title='Confirm', text='Are you sure?', size_hint_x=None, width=300, buttons=[btn1, btn2]) self.dialog.open()
def __init__(self, **kwargs): super().__init__(**kwargs) camera_widget=Camera(play=True) #camera_widget.resolution=(720,1080) #camera_widget.orientation='vertical' camera_widget.resolution=(Window.size) camera_widget.pos_hint={'center_x':0.5,'center_y':0.5} button_widget=MDRectangleFlatButton(text='Search',pos_hint={'center_x': 0.5,'center_y' : 0.1}) button_widget.bind(on_press=self.capture) self.add_widget(camera_widget) self.add_widget(button_widget) self.camera_reference=camera_widget #referencing camera_widget(camera object) to camera_refernce
def build(self): main_layout = MDBoxLayout(orientation="vertical") self.operators = ["/", "*", "+", "-"] self.last_was_operator = None self.last_button = None self.solution = TextInput(multiline=False, readonly=True, halign="right", height=200, font_size=130) main_layout.add_widget(self.solution) buttons = [ ["sin", "cos", "tan", "π"], ["log", "ln", "^", "fact."], ["7", "8", "9", "/"], ["4", "5", "6", "*"], ["1", "2", "3", "-"], [".", "0", "C", "+"], ["√", "(", ")", "="], ] for row in buttons: h_layout = MDBoxLayout() for label in row: button = MDRectangleFlatButton( text=label, pos_hint={ "center_x": 0.5, "center_y": 0.5 }, font_size=20, size_hint=(1, 1), ) button.bind(on_press=self.on_button_press) h_layout.add_widget(button) main_layout.add_widget(h_layout) return main_layout
class CamApp(MDApp): def build(self): self.parent = BoxLayout(orientation='vertical') self.capture = cv.VideoCapture(0) self.my_camera = KivyCamera(capture=self.capture, fps=30) self.parent.add_widget(self.my_camera) self.shot_btn = MDRectangleFlatButton(text='Screen Shot') self.shot_btn.bind(on_release=self.screen_shot) self.shot_btn.increment_width = Window.size[0] self.parent.add_widget(self.shot_btn) return self.parent def screen_shot(self, obj): # Finds the number to add after name. name = "face" datename = datetime.now().strftime('%H_%M_%S_%d_%m_%Y.log') # saves file self.my_camera.export_to_png(name + datename + ".png") def on_stop(self): self.capture.release()
class UI(Screen, MDBoxLayout): # Creates main screen along with the widgets def __init__(self, **kwargs): super(UI, self).__init__(**kwargs) self.label = MDLabel( text='Rap Lyrics Generator', halign='center', font_style='H5', pos_hint={'center_x': 0.5, 'center_y': 0.95} ) self.label_word = MDLabel( text='Type in one word for lyric generator', font_style='Overline', pos_hint={'center_x': 0.5, 'center_y': 0.9} ) self.word = MDTextField( hint_text='Type the word here', helper_text="This will disappear when you click off", helper_text_mode="on_focus", pos_hint={'center_x': 0.5, 'center_y': 0.85} ) self.label_temp = MDLabel( text='Type in a float between 0.1 and 2. This will determine how random the text will be. 0.1 = least random, 2 = most random.', font_style='Overline', pos_hint={'center_x': 0.5, 'center_y': 0.8} ) self.temp = MDTextField( hint_text='temp', helper_text="This will disappear when you click off", helper_text_mode="on_focus", pos_hint={'center_x': 0.5, 'center_y': 0.75} ) self.label_num = MDLabel( text='Type in a number of characters you want to generate. The limit is 1000.', font_style='Overline', pos_hint={'center_x': 0.5, 'center_y': 0.70} ) self.num = MDTextField( hint_text='num', helper_text="This will disappear when you click off", helper_text_mode="on_focus", pos_hint={'center_x': 0.5, 'center_y': 0.65} ) self.generate = MDRectangleFlatButton( text='Generate lyrics', pos_hint={'center_x': 0.5, 'center_y': 0.6} ) self.generate.bind(on_press=self.on_generate_press) self.res_label = MDLabel( text='Here you will see your lyrics', font_style="Overline", halign="center", pos_hint={'center_x': 0.5, 'center_y': 0.25}, size_hint=[1.0, None], ) self.add_widget(self.label) self.add_widget(self.label_word) self.add_widget(self.word) self.add_widget(self.label_temp) self.add_widget(self.temp) self.add_widget(self.label_num) self.add_widget(self.num) self.add_widget(self.generate) self.add_widget(self.res_label) def on_generate_press(self, instance): # Takes input from the user and calls generate_text() num_generate = self.num.text temperature = self.temp.text start_string = self.word.text ml_util = MLUtil() logging.info("ML Gen res:") gen_res = ml_util.generate_text( num_generate, temperature, start_string) self.res_label.text = gen_res
class Form(MDGridLayout): def __init__(self, form_attrs, **kwargs): super(Form, self).__init__(**kwargs) self.cols = 1 self.form = MDGridLayout() self.form.cols = 2 self.form_attrs = form_attrs self.text_inputs = {} self.search_btn = {} for key, value in form_attrs.items(): if key == 'form_name': self.form_name = form_attrs[key] elif key in ['product_id', 'provider_id']: self.form.add_widget(MDLabel(text=value[0] + ':')) self.text_inputs[key] = MDTextField( multiline=False, text='' if 'date' not in key else datetime.now().strftime('%Y-%m-%d %H:%M:%S')) self.search_btn[key] = MDRectangleFlatButton(text='Buscar ' + value[0], size_hint_x=None, font_size=10) self.search_btn[key].bind(on_release=self.search) search_lo = MDGridLayout() search_lo.cols = 2 search_lo.add_widget(self.text_inputs[key]) search_lo.add_widget(self.search_btn[key]) self.form.add_widget(search_lo) else: self.form.add_widget(MDLabel(text=value[0] + ':')) self.text_inputs[key] = MDTextField( multiline=False, text='' if 'date' not in key else datetime.now().strftime('%Y-%m-%d %H:%M:%S')) self.form.add_widget(self.text_inputs[key]) self.add_widget(self.form) self.submit = MDRectangleFlatButton(text='Crear', font_size=40, pos_hint={ 'center_x': 0.5, 'center_y': 0.1 }, size_hint_x=None) self.submit.bind(on_release=self.submit_form) self.add_widget(self.submit) def search(self, instance): key = instance.text url = None if key == 'Buscar ID Proveedor': ti_key = 'provider_id' id = '?id=' + self.text_inputs[ti_key].text url = Constants.HOST + '/provider' + id elif key == 'Buscar ID Producto': ti_key = 'product_id' id = '?id=' + self.text_inputs['product_id'].text url = Constants.HOST + '/product' + id if self.text_inputs[ti_key].text != '': UrlRequest(url, on_success=self.parse_object) def parse_object(self, req, result): if 'provider' in req.url: self.text_inputs['provider_name'].text = result["result"][0][ 'name'] elif 'product' in req.url: self.text_inputs['product_name'].text = result["result"][0]['name'] self.text_inputs['product_description'].text = result["result"][0][ 'description'] self.text_inputs['measure'].text = result["result"][0]['measure'] def convert(self, k, v): value = None try: if self.form_attrs[k][1] == 'int': value = int(v) elif self.form_attrs[k][1] == 'flt': value = float(v) elif self.form_attrs[k][1] == 'date': value = v datetime.strptime(value, '%Y-%m-%d %H:%M:%S') else: value = v except: raise return [k, value] def submit_form(self, instance): print("pressed") form_name = self.form_name text_inputs = self.text_inputs for key, value in self.text_inputs.items(): if self.text_inputs[key].text == '': return try: resp_dic = {} for k, v in text_inputs.items(): record = self.convert(k, v.text) resp_dic[record[0]] = record[1] texts = json.dumps(resp_dic) except: return if form_name == 'entry_form': url = Constants.HOST + '/entry' elif form_name == 'out_form': url = Constants.HOST + '/out' headers = {"Content-type": "application/json", "Accept": "text/plain"} req = UrlRequest(url, req_headers=headers, req_body=texts, on_failure=self.fail, on_success=self.success, on_error=self.error) for key, value in self.text_inputs.items(): self.text_inputs[ key].text = '' if 'date' not in key else datetime.now( ).strftime('%Y-%m-%d %H:%M:%S') def success(sefl, req, result): print('success') def fail(self, req, result): print('fail') def error(self, req, error): print("error") print(error)
class Space(Screen): in_play = BooleanProperty(False) timer = NumericProperty(0) shield_time = NumericProperty(0) time_label = StringProperty('00:00:00') rgba_label = ListProperty([1, 1, 1, 0]) # shield color score = NumericProperty(0) raider = ObjectProperty(None) pause_label = ObjectProperty(None) resume_label = ObjectProperty(None) pause_button = ObjectProperty(None) time_button = ObjectProperty(None) def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_key_down=self.on_key_down) Clock.schedule_interval(self.tick, 0.2) Clock.schedule_interval(self.spawn_enemies, 0.2) Clock.schedule_interval(self.garbage_collect, 1 / 60) # list of sprite objects self.bonus = [] self.cannons = [] self.enemies = [] # meteorites, saturn, ufos and missiles... self.time_dialog = MDTimePicker() # test def tick(self, interval): if self.in_play: self.timer += 1 self.shield_time += 1 self.time_label = self.format_time() self.rgba_label = self.format_rgba() if __debug__: # this will be called by running `python -O asteroids.py` on the command line # make sure that objects are garbage collected print(len(self.bonus)) print(len(self.cannons)) print(len(self.enemies)) def format_time(self): hour = self.timer // 3600 minute, second = map(int, divmod(self.timer, 60)) return f'{hour:02d}:{minute:02d}:{second:02d}' def format_rgba(self): if self.shield_time < 40 and self.shield_time % 2 == 0: return 1, 1, 1, 1 elif 20000 <= self.shield_time <= 20020 and self.shield_time % 2 == 0: return 1, 1, 0, 1 return 1, 1, 1, 0 def spawn_enemies(self, interval): if self.in_play: if self.timer % 5 == 0: # every second menu = ['meteorite1', 'meteorite2', 'saturn', 'ufo', 'missile'] model = random.choice(menu) if model == 'missile': size = (90, 120) elif model == 'saturn': size = (140, 70) elif model == 'ufo': size = (110, 110 / 1.77) else: size = (75, 100) pos = random.randint(int(size[0] / 2), int(self.size[0] - size[0] * 1.5)), self.size[1] enemy = Sprite(model=model, pos=pos, size=size) self.enemies.append(enemy) self.add_widget(enemy) def clear_sprite(self, *args, spr=None): self.remove_widget(spr) def garbage_collect(self, interval): """ Check boundaries and collisions, so as to remove dead widgets on a regular basis. Free resources periodically to prevent memory overload and make the game smooth. """ if not self.in_play: return for wid in self.cannons.copy(): if self.out_of_bound(wid): self.cannons.remove(wid) self.remove_widget(wid) for wid in self.enemies.copy(): if self.out_of_bound(wid): self.enemies.remove(wid) self.remove_widget(wid) elif wid.hp <= 0: self.enemies.remove(wid) if random.random() > 0.9: wid.revive() self.bonus.append(wid) else: wid.explode( ) # explosion effect (takes around 0.5 ~ 1 seconds) callback = partial(self.clear_sprite, spr=wid) # partial function Clock.schedule_once( callback, timeout=2) # remove widget after 2 seconds else: collided, enemy, cannon = collide_1_9(wid, self.cannons) if collided: self.remove_widget(cannon) self.cannons.remove(cannon) enemy.hp -= 1 self.score += 1 for wid in self.bonus.copy(): if wid.y < -150 or wid.y > self.size[ 1]: # bonus escapes the top or bottom self.bonus.remove(wid) self.remove_widget(wid) elif collide_1_1(wid, self.raider): self.bonus.remove(wid) wid.explode( ) # explosion effect (takes around 0.5 ~ 1 seconds) callback = partial(self.clear_sprite, spr=wid) # partial function Clock.schedule_once(callback, timeout=2) # remove widget after 2 seconds self.score += 1000 # bonus score self.shield_time = 20000 # add protection shield def out_of_bound(self, spr): """ Check if a sprite widget has *completely* moved out of bound. """ if spr.x < -spr.size[0] or spr.x > self.size[0]: return True if spr.y < -spr.size[1] or spr.y > self.size[1]: return True return False def on_touch_down(self, touch): """ Important Notice: ----------------- Unlike listeners such as on_press, on_release and on_key_down, which are triggered only on a specific widget, on_touch_down fires everything within a widget tree, be it a button click or a mouse drag event, literally any event happened on the screen. The same is true for on_touch_up and on_touch_move. The consequence of this is, when you override an on_touch method, for instance, to control a moving widget with your mouse and finger touches, if there are other buttons and text inputs on the same screen, they are not going to work properly since their bindings rely on the original on_touch implementations. In some other scenarios, the on_touch method can overshadow your defined callback, or unexpectedly fired on other objects from a different widget tree, or a widget can be fired twice by different callbacks, which leads to conflict. To get around this issue, there's only one solution: code up the overriding method partially with caution, override only where you are interested using if-else, do not override the whole function. Place a call to the superclass method wherever applicable, so as to inherit, keep, mutate or disable the original behavior depending on the type of conflict you have. """ if not self.in_play: return super().on_touch_down(touch) if self.raider.collide_point(touch.x, touch.y): self.raider.offset_x = self.raider.center_x - touch.x self.raider.offset_y = self.raider.center_y - touch.y def on_touch_up(self, touch): if not self.in_play: return super().on_touch_down(touch) self.raider.thrust = False self.raider.offset_x = None self.raider.offset_y = None def on_touch_move(self, touch): if not self.in_play: return super().on_touch_down(touch) if self.raider.offset_x and self.raider.offset_y: self.raider.thrust = True self.raider.center_x = min( max(touch.x + self.raider.offset_x, self.raider.size[0] / 2), self.width - self.raider.size[0] / 2) self.raider.center_y = min( max(touch.y + self.raider.offset_y, self.raider.size[1] / 2), self.width - self.raider.size[1] / 2) def switch_screen(self, *args): # clear the pause widgets before switch self.remove_widget(self.pause_label) self.remove_widget(self.resume_label) self.remove_widget(self.pause_button) self.remove_widget(self.time_button) self.manager.transition = WipeTransition() self.manager.current = 'login' def pause(self): # pause the game and all scheduled events self.in_play = False # create pause widgets (only the first time) if not self.pause_label: self.pause_label = Label(font_name='perpeta', font_size=40, text='GAME PAUSED', pos_hint={ "center_x": 0.5, "center_y": 0.6 }) if not self.resume_label: self.resume_label = Label(font_name='perpeta', font_size=18, color=(0.8, 0.8, 0.8, 0.5), text='PRESS ENTER AGAIN TO RESUME', pos_hint={ "center_x": 0.5, "center_y": 0.55 }) if not self.pause_button: self.pause_button = MDRectangleFlatButton(font_name='OpenSans', font_size=20, pos_hint={ "center_x": 0.5, "center_y": 0.48 }, text_color=(1, 1, 1, 1), text='BACK TO MENU') self.pause_button.md_bg_color = (0, 1, 0, 0.2) self.pause_button.bind(on_release=self.switch_screen) if not self.time_button: self.time_button = MDRectangleFlatButton(font_name='OpenSans', font_size=20, pos_hint={ "center_x": 0.5, "center_y": 0.4 }, text_color=(1, 1, 1, 1), text='TIME LEAP') self.time_button.md_bg_color = (0, 0, 1, 0.2) self.time_button.bind(on_release=self.time_dialog.open) # display pause widgets on the screen self.add_widget(self.pause_label) self.add_widget(self.resume_label) self.add_widget(self.pause_button) self.add_widget(self.time_button) def resume(self): # clear the pause widgets before resume self.remove_widget(self.pause_label) self.remove_widget(self.resume_label) self.remove_widget(self.pause_button) self.remove_widget(self.time_button) self.in_play = True # resume the game def on_key_down(self, window, key, *args): if key == Keyboard.keycodes['spacebar']: if self.in_play: missile = self.raider.shoot() self.cannons.append(missile) self.add_widget(missile) elif key == Keyboard.keycodes['enter']: if self.in_play: self.pause() else: self.resume()