def show_example_list_bottom_sheet(self): bs_menu = MDListBottomSheet() bs_menu.add_item( "Watch", lambda x: self.watch(), icon="youtube", ) bs_menu.add_item( "Code Link", lambda x: self.link(), icon="page-previous", ) bs_menu.add_item( "Made by kerry 407510062", lambda x: None, icon="dev-to", ) bs_menu.add_item( "using Python!", lambda x: self.version(), icon="language-python", ) bs_menu.add_item( "Exit", lambda x: self.Exit(), icon="exit-to-app", ) bs_menu.open()
def bottom_layer(self): bottom_sheet = MDListBottomSheet(radius=20, radius_from='top') for i in range(10): bottom_sheet.add_item( f"Item {i+1}", lambda x, y=i + 1: self.callback_(f"Item {y} clicked"), icon='android') bottom_sheet.open()
def show_example_list_bottom_sheet1(self): """ It shows the list of the currencies together with their flags. If an item from the list is selected the function callback_for_menu_items1(self, *args) is called. i = flag index""" bottom_sheet_menu = MDListBottomSheet() i = 0 for key in exchange_dict: bottom_sheet_menu.add_item( f"{key}", lambda x, y=key: self.callback_for_menu_items1(f"{y}"), icon=self.icons[i]) i += 1 bottom_sheet_menu.open()
def show_example_list_bottom_sheet(self): bottom_sheet_menu = MDListBottomSheet(radius=25, radius_from="top") data = {} all_wallets = list(get_saved_wallet()) current_wallet = the_settings()["wallet"] for wallet in all_wallets: number = all_wallets.index(wallet) address = Wallet_Import(all_wallets.index(wallet), 3) if not current_wallet == number: data[number] = address else: data[number] = address + " - CURRENTLY USED" for item in data.items(): bottom_sheet_menu.add_item( str(item[0]) + " : " + item[1], lambda x, y=item[0]: self.callback_for_menu_items(y), ) bottom_sheet_menu.open()
def transaction_history(self): transactions = GetMyTransaction() if not len(transactions) == 0: bottom_sheet_menu = MDListBottomSheet(radius=25, radius_from="top") data = {} for tx in transactions: data[tx] = tx.toUser + " | " + str(tx.amount) + " | " + str( tx.transaction_fee) for item in data.items(): bottom_sheet_menu.add_item( item[1], lambda x, y=item[0]: self. callback_for_transaction_history_items(y), ) bottom_sheet_menu.open() else: SweetAlert().fire( "You have not a transaction", type='failure', )
def open_song_menu(self, i): # adding right-side icons from kivymd.uix.bottomsheet import MDListBottomSheet song_menu = MDListBottomSheet(radius_from='top') # Spotify if i.id_spotify: from utils import spotify_installed msg = "Spotify isn't installed on your device." song_menu.add_item(text="Listen on Spotify", callback=lambda x, song=i: (self.open_spotify(i) if spotify_installed() else toast(msg)), icon="spotify") # Favorited favorited = i in app.favorites song_menu.add_item(text="Favorite" if not favorited else "Unfavorite", callback=lambda *args, song=i: app.main_page. favorite_playlist_item(self, song), icon='heart' if favorited else 'heart-outline') # Remove removable = (is_removable(i) or i != app.playlist.current_track) if removable: song_menu.add_item(text="Remove from playlist", callback=lambda *args, song=i: app.main_page. remove_playlist_item(self, song), icon='close') song_menu.open()
class FavoriteSongListItem(TwoLineAvatarIconListItem): def __init__(self, **kwargs): song = kwargs.pop('song') super().__init__(**kwargs) self.text = song.name self.secondary_text = song.artist self._txt_left_pad = '10dp' self.song = song def create_song_menu(self): from kivymd.uix.bottomsheet import MDListBottomSheet song = self.song app = MDApp.get_running_app() self.song_menu = MDListBottomSheet(radius_from='top') # Play song if song != app.song.song_object: self.song_menu.add_item(text="Play", callback=lambda *args, song=song: app. favorites_page.play_song(song), icon='play') # Add to playlist self.song_menu.add_item(text="Add to playlist", callback=lambda *args, song=song: app. favorites_page.playlist_add(song), icon='playlist-plus') # Spotify if song.id_spotify: from utils import spotify_installed msg = "Spotify isn't installed on your device." self.song_menu.add_item(text="Listen on Spotify", callback=lambda x, song=song: (app.main_page.open_spotify(song) if spotify_installed() else toast(msg)), icon="spotify") # Remove from favorites self.song_menu.add_item(text="Remove from favorites", callback=lambda *args, song=song: app. favorites_page.remove_song(song), icon='close')
def nick_details(self, nick_list_item): self.app.connection.signedOn() nick_item_data = self.nick_data[nick_list_item.text] bs = MDListBottomSheet() bs.add_item("WHOIS ({})".format(nick_list_item.text), lambda x: x) bs.add_item( "{} ({}@{})".format(nick_item_data[7].split(' ')[1], nick_item_data[3], nick_item_data[2]), lambda x: x) bs.add_item( "{} is connected via {}".format(nick_list_item.text, nick_item_data[4]), lambda x: x) bs.open()
def show_example_bottom_sheet(self): bs_menu = MDListBottomSheet() bs_menu.add_item( "[b][color=311B92]Change Theme[/color][/b]" if main_app.theme == "purple" else f"[b][color=263238]Change Theme[/b][/color]", lambda x: self.themer(), icon="theme-light-dark") bs_menu.add_item( "[b][color=311B92]BMI Calculator[/color][/b]" if main_app.theme == "purple" else f"[b][color=263238]BMI Calculator[/b][/color]", lambda x: None, icon="google-fit") bs_menu.add_item( "Made by Abhay Maurya", lambda x: None, icon="dev-to", ) bs_menu.add_item( "using Python!", lambda x: None, icon="language-python", ) bs_menu.open()
def bottom_sheet(self): bs_menu_period = MDListBottomSheet() bs_menu_period.add_item( "Сегодня", lambda x: self.set_today(), icon="clipboard-account", ) bs_menu_period.add_item( "Вчера", lambda x: self.set_yesterday(), icon="clipboard-account", ) bs_menu_period.add_item( "Число", lambda x: self.set_date(), icon="clipboard-account", ) bs_menu_period.add_item( "Период", lambda x: self.set_period(), icon="clipboard-account", ) bs_menu_period.open()
def show_example_bottom_sheet(self, product): """ method the show the bottom sheet after the click on the product """ #get of the product in the database dbase_product = self.database.get_product_by_id(product.id) bs_menu = MDListBottomSheet() bs_menu.add_item( f'{dbase_product[4]}- [b]{dbase_product[1]}[/b] {dbase_product[2]}$ {dbase_product[3]}$', lambda x: print(x), ) bs_menu.add_item( "view", lambda x:self.navigate(product_id=dbase_product[0]), icon="file-edit-outline", ) bs_menu.add_item( "delete", lambda x: self.remove_product(product), icon="delete", ) bs_menu.open()
def show_example_bottom_sheet(self): bs_menu_1 = MDListBottomSheet() bs_menu_1.add_item( "Here's an item with text only", lambda x: self.callback_for_menu_items( "Here's an item with text only"), ) bs_menu_1.add_item( "Here's an item with an icon", lambda x: self.callback_for_menu_items( "Here's an item with an icon"), icon="clipboard-account", ) bs_menu_1.add_item( "Here's another!", lambda x: self.callback_for_menu_items("Here's another!"), icon="nfc", ) bs_menu_1.open()
class KitchenSink(App, Screens): theme_cls = ThemeManager() theme_cls.primary_palette = "BlueGray" theme_cls.accent_palette = "Gray" previous_date = ObjectProperty() title = "Kitchen Sink" def __init__(self, **kwargs): super().__init__(**kwargs) self.menu_items = [{ "viewclass": "MDMenuItem", "text": "Example item %d" % i, "callback": self.callback_for_menu_items, } for i in range(15)] self.Window = Window # Default class instances. self.manager = None self.md_app_bar = None self.instance_menu_demo_apps = None self.instance_menu_source_code = None self.md_theme_picker = None self.long_dialog = None self.input_dialog = None self.alert_dialog = None self.ok_cancel_dialog = None self.long_dialog = None self.dialog = None self.user_card = None self.bs_menu_1 = None self.bs_menu_2 = None self.popup_screen = None self.my_snackbar = None self.dialog_load_kv_files = None self.create_stack_floating_buttons = False self.manager_open = False self.cards_created = False self._interval = 0 self.tick = 0 self.x = 0 self.y = 25 self.file_source_code = "" self.hex_primary_color = get_hex_from_color( self.theme_cls.primary_color) self.previous_text = ( f"Welcome to the application [b][color={self.hex_primary_color}]" f"Kitchen Sink[/color][/b].\nTo see [b]" f"[color={self.hex_primary_color}]KivyMD[/color][/b] " f"examples, open the menu and select from the list the desired " f"example or") self.previous_text_end = ( f"for show example apps\n\n" f"Author - [b][color={self.hex_primary_color}]" f"Andrés Rodríguez[/color][/b]\n" f"[u][b][color={self.hex_primary_color}]" f"[email protected][/color][/b][/u]\n\n\n" f"Authors this Fork:\n\n" f"[b][color={self.hex_primary_color}]" f"Ivanov Yuri[/color][/b]\n" f"[u][b][color={self.hex_primary_color}]" f"[email protected][/color][/b][/u]\n\n" f"[b][color={self.hex_primary_color}]Artem S. Bulgakov[/color][/b]\n" f"[u][b][color={self.hex_primary_color}]" f"[email protected][/color][/b][/u]\n\n" f"and contributors...") self.names_contacts = ( "Alexandr Taylor", "Yuri Ivanov", "Robert Patric", "Bob Marley", "Magnus Carlsen", "Jon Romero", "Anna Bell", "Maxim Kramerer", "Sasha Gray", "Vladimir Ivanenko", ) self.demo_apps_list = [ "Shop Window", "Coffee Menu", "Fitness Club", "Registration", "Account Page", ] self.list_name_icons = list(md_icons.keys())[0:15] Window.bind(on_keyboard=self.events) crop_image( (Window.width, int(dp(Window.height * 35 // 100))), f"{demos_assets_path}guitar-1139397_1280.png", f"{demos_assets_path}guitar-1139397_1280_crop.png", ) def set_list_for_refresh_layout(self): async def set_list_for_refresh_layout(): names_icons_list = list(md_icons.keys())[self.x:self.y] for name_icon in names_icons_list: await asynckivy.sleep(0) self.data["Refresh Layout"]["object"].ids.box.add_widget( ItemForListRefreshLayout(icon=name_icon, text=name_icon)) self.data["Refresh Layout"][ "object"].ids.refresh_layout.refresh_done() asynckivy.start(set_list_for_refresh_layout()) def refresh_callback(self, *args): """A method that updates the state of your application while the spinner remains on the screen.""" def refresh_callback(interval): self.data["Refresh Layout"]["object"].ids.box.clear_widgets() if self.x == 0: self.x, self.y = 25, 50 else: self.x, self.y = 0, 25 self.set_list_for_refresh_layout() self.tick = 0 Clock.schedule_once(refresh_callback, 1) def build_tabs(self): for name_tab in self.list_name_icons: tab = Factory.MyTab(text=name_tab) self.data["Tabs"]["object"].ids.android_tabs.add_widget(tab) def switch_tabs_to_icon(self, istance_android_tabs): for i, instance_tab in enumerate( istance_android_tabs.ids.scrollview.children[0].children): istance_android_tabs.ids.scrollview.children[0].remove_widget( instance_tab) istance_android_tabs.add_widget( Factory.MyTab(text=self.list_name_icons[i])) def switch_tabs_to_text(self, istance_android_tabs): for instance_tab in istance_android_tabs.ids.scrollview.children[ 0].children: for k, v in md_icons.items(): if v == instance_tab.text: istance_android_tabs.ids.scrollview.children[ 0].remove_widget(instance_tab) istance_android_tabs.add_widget( Factory.MyTab( text=" ".join(k.split("-")).capitalize())) break def crop_image_for_tile(self, instance, size, path_to_crop_image): """Crop images for Grid screen.""" if not os.path.exists(os.path.join(self.directory, path_to_crop_image)): size = (int(size[0]), int(size[1])) path_to_origin_image = path_to_crop_image.replace("_tile_crop", "") crop_image(size, path_to_origin_image, path_to_crop_image) instance.source = path_to_crop_image def theme_picker_open(self): if not self.md_theme_picker: from kivymd.uix.picker import MDThemePicker self.md_theme_picker = MDThemePicker() self.md_theme_picker.open() def example_add_stack_floating_buttons(self): from kivymd.uix.stackfloatingbutton import MDStackFloatingButtons def set_my_language(instance_button): toast(instance_button.icon) if not self.create_stack_floating_buttons: screen = self.main_widget.ids.scr_mngr.get_screen("stack buttons") screen.add_widget( MDStackFloatingButtons( icon="lead-pencil", floating_data={ "Python": "language-python", "Php": "language-php", "C++": "language-cpp", }, callback=set_my_language, )) self.create_stack_floating_buttons = True def set_expansion_panel(self): from kivymd.uix.expansionpanel import MDExpansionPanel def callback(text): toast(f"{text} to {content.name_item}") content = ContentForAnimCard(callback=callback) for name_contact in self.names_contacts: self.data["Expansion Panel"]["object"].ids.anim_list.add_widget( MDExpansionPanel( content=content, icon="assets/kivy-logo-white-512.png", title=name_contact, )) def set_chevron_back_screen(self): """Sets the return chevron to the previous screen in ToolBar.""" self.main_widget.ids.toolbar.right_action_items = [[ "dots-vertical", lambda x: self.root.toggle_nav_drawer() ]] def download_progress_hide(self, instance_progress, value): """Hides progress progress.""" self.main_widget.ids.toolbar.right_action_items = [[ "download", lambda x: self.download_progress_show(instance_progress), ]] def download_progress_show(self, instance_progress): self.set_chevron_back_screen() instance_progress.open() instance_progress.animation_progress_from_fade() def show_example_download_file(self, interval): from kivymd.uix.progressloader import MDProgressLoader def get_connect(host="8.8.8.8", port=53, timeout=3): import socket try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect( (host, port)) return True except (TimeoutError, ConnectionError, OSError): return False if get_connect(): link = ("https://www.python.org/ftp/python/3.5.1/" "python-3.5.1-embed-win32.zip") progress = MDProgressLoader( url_on_image=link, path_to_file=os.path.join(self.directory, "python-3.5.1.zip"), download_complete=self.download_complete, download_hide=self.download_progress_hide, ) progress.start(self.data["Download File"]["object"].ids.box_flt) else: toast("Connect error!") def download_complete(self): self.set_chevron_back_screen() toast("Done") def file_manager_open(self): from kivymd.uix.filemanager import MDFileManager from kivymd.uix.dialog import MDDialog def open_file_manager(text_item, dialog): previous = False if text_item == "List" else True self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False) self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, previous=previous, ) self.manager.add_widget(self.file_manager) self.file_manager.show(self.user_data_dir) self.manager_open = True self.manager.open() MDDialog( title="Title", size_hint=(0.8, 0.4), text_button_ok="List", text="Open manager with 'list' or 'previous' mode?", text_button_cancel="Previous", events_callback=open_file_manager, ).open() def select_path(self, path): """It will be called when you click on the file name or the catalog selection button. :type path: str; :param path: path to the selected directory or file; """ self.exit_manager() toast(path) def exit_manager(self, *args): """Called when the user reaches the root of the directory tree.""" self.manager.dismiss() self.manager_open = False self.set_chevron_menu() def set_chevron_menu(self): self.main_widget.ids.toolbar.left_action_items = [[ "menu", lambda x: self.root.toggle_nav_drawer() ]] def events(self, instance, keyboard, keycode, text, modifiers): """Called when buttons are pressed on the mobile device.""" if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True def callback_for_menu_items(self, *args): toast(args[0]) def add_cards(self, instance_grid_card): """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.uix.card import MDCardPost def callback(instance, value): if value is None: toast("Delete post %s" % str(instance)) elif isinstance(value, int): toast("Set like in %d stars" % value) elif isinstance(value, str): toast("Repost with %s " % value) elif isinstance(value, list): toast(value[1]) if not self.cards_created: self.cards_created = True menu_items = [{ "viewclass": "MDMenuItem", "text": "Example item %d" % i, "callback": self.callback_for_menu_items, } for i in range(2)] buttons = ["facebook", "vk", "twitter"] instance_grid_card.add_widget( MDCardPost(text_post="Card with text", swipe=True, callback=callback)) instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, text_post="Card with a button to open the menu MDDropDown", callback=callback, )) instance_grid_card.add_widget( MDCardPost( likes_stars=True, callback=callback, swipe=True, text_post="Card with asterisks for voting.", )) image_for_card = ( f"{demos_assets_path}kitten-for_card-1049129_1280-crop.png") if not os.path.exists(image_for_card): crop_image( (int(Window.width), int(dp(200))), f"{demos_assets_path}kitten-1049129_1280.png", image_for_card, ) instance_grid_card.add_widget( MDCardPost( source=image_for_card, tile_text="Little Baby", tile_font_style="H5", text_post="This is my favorite cat. He's only six months " "old. He loves milk and steals sausages :) " "And he likes to play in the garden.", with_image=True, swipe=True, callback=callback, buttons=buttons, )) def update_screen(self, instance): """Set new label on the screen UpdateSpinner.""" def update_screen(interval): self.tick += 1 if self.tick > 2: instance.update = True self.tick = 0 self.data["Update Screen Widget"][ "object"].ids.upd_lbl.text = "New string" Clock.unschedule(update_screen) Clock.schedule_interval(update_screen, 1) main_widget = None def build(self): self.main_widget = Builder.load_string(main_widget_kv) return self.main_widget def show_popup_screen(self): if not self.popup_screen: self.popup_screen = self.data["Popup Screen"]["object"].ids.popup content_screen = ContentForPopupScreen() self.popup_screen.screen = content_screen self.popup_screen.padding = dp(10) self.popup_screen.background_color = self.theme_cls.primary_color self.popup_screen.show() def show_user_example_animation_card(self): """Create and open instance MDUserAnimationCard for the screen UserCard.""" from kivymd.uix.useranimationcard import MDUserAnimationCard def main_back_callback(): toast("Close card") if not self.user_card: image_for_user_card = ( f"{demos_assets_path}guitar-for-user-card1139397_1280-crop.png" ) if not os.path.exists(image_for_user_card): crop_image( (int(Window.width), int(dp(Window.height * 40 // 100))), f"{demos_assets_path}guitar-1139397_1280.png", image_for_user_card, ) self.user_card = MDUserAnimationCard( user_name="Lion Lion", path_to_avatar=image_for_user_card, callback=main_back_callback, ) self.user_card.box_content.add_widget(ContentForAnimCard()) self.user_card.open() def show_example_snackbar(self, snack_type): """Create and show instance Snackbar for the screen MySnackBar.""" def callback(instance): toast(instance.text) def wait_interval(interval): self._interval += interval if self._interval > self.my_snackbar.duration: anim = Animation(y=dp(10), d=0.2) anim.start(self.data["Snackbars"]["object"].ids.button) Clock.unschedule(wait_interval) self._interval = 0 self.my_snackbar = None from kivymd.uix.snackbar import Snackbar if snack_type == "simple": Snackbar(text="This is a snackbar!").show() elif snack_type == "button": Snackbar( text="This is a snackbar", button_text="WITH A BUTTON", button_callback=callback, ).show() elif snack_type == "verylong": Snackbar(text="This is a very very very very very very very " "long snackbar!").show() elif snack_type == "float": if not self.my_snackbar: self.my_snackbar = Snackbar( text="This is a snackbar!", button_text="Button", duration=3, button_callback=callback, ) self.my_snackbar.show() anim = Animation(y=dp(72), d=0.2) anim.bind(on_complete=lambda *args: Clock.schedule_interval( wait_interval, 0)) anim.start(self.data["Snackbars"]["object"].ids.button) def show_example_input_dialog(self): """Creates an instance of the dialog box and displays it on the screen for the screen Dialogs.""" def result(text_button, instance): toast(instance.text_field.text) if not self.input_dialog: from kivymd.uix.dialog import MDInputDialog self.input_dialog = MDInputDialog( title="Title", hint_text="Hint text", size_hint=(0.8, 0.4), text_button_ok="Ok", events_callback=result, ) self.input_dialog.open() def show_example_alert_dialog(self): if not self.alert_dialog: from kivymd.uix.dialog import MDDialog self.alert_dialog = MDDialog( title="Title", size_hint=(0.8, 0.4), text_button_ok="Ok", text="This is Alert dialog", events_callback=self.callback_for_menu_items, ) self.alert_dialog.open() def show_example_ok_cancel_dialog(self): if not self.ok_cancel_dialog: from kivymd.uix.dialog import MDDialog self.ok_cancel_dialog = MDDialog( title="Title", size_hint=(0.8, 0.4), text_button_ok="Ok", text="This is Ok Cancel dialog", text_button_cancel="Cancel", events_callback=self.callback_for_menu_items, ) self.ok_cancel_dialog.open() def show_example_long_dialog(self): if not self.long_dialog: from kivymd.uix.dialog import MDDialog self.long_dialog = MDDialog( text="Lorem ipsum dolor sit amet, consectetur adipiscing " "elit, sed do eiusmod tempor incididunt ut labore et " "dolore magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut aliquip " "ex ea commodo consequat. Duis aute irure dolor in " "reprehenderit in voluptate velit esse cillum dolore eu " "fugiat nulla pariatur. Excepteur sint occaecat " "cupidatat non proident, sunt in culpa qui officia " "deserunt mollit anim id est laborum.", title="Title", size_hint=(0.8, 0.4), text_button_ok="Yes", events_callback=self.callback_for_menu_items, ) self.long_dialog.open() def get_time_picker_date(self, time): """Get date for MDTimePicker from the screen Pickers.""" self.data["Pickers"]["object"].ids.time_picker_label.text = str(time) self.previous_time = time def show_example_time_picker(self): """Show MDTimePicker from the screen Pickers.""" from kivymd.uix.picker import MDTimePicker time_dialog = MDTimePicker(self.get_time_picker_date) if self.data["Pickers"][ "object"].ids.time_picker_use_previous_time.active: try: time_dialog.set_time(self.previous_time) except AttributeError: pass time_dialog.open() def set_previous_date(self, date_obj): """Set previous date for MDDatePicker from the screen Pickers.""" self.previous_date = date_obj self.data["Pickers"]["object"].ids.date_picker_label.text = str( date_obj) def show_example_date_picker(self): """Show MDDatePicker from the screen Pickers.""" from kivymd.uix.picker import MDDatePicker if self.data["Pickers"][ "object"].ids.date_picker_use_previous_date.active: pd = self.previous_date try: MDDatePicker(self.set_previous_date, pd.year, pd.month, pd.day).open() except AttributeError: MDDatePicker(self.set_previous_date).open() else: MDDatePicker(self.set_previous_date).open() def show_example_bottom_sheet(self): """Show menu from the screen BottomSheet.""" from kivymd.uix.bottomsheet import MDListBottomSheet if not self.bs_menu_1: self.bs_menu_1 = MDListBottomSheet() self.bs_menu_1.add_item( "Here's an item with text only", lambda x: self.callback_for_menu_items( "Here's an item with text only"), ) self.bs_menu_1.add_item( "Here's an item with an icon", lambda x: self.callback_for_menu_items( "Here's an item with an icon"), icon="clipboard-account", ) self.bs_menu_1.add_item( "Here's another!", lambda x: self.callback_for_menu_items("Here's another!"), icon="nfc", ) self.bs_menu_1.open() def show_example_grid_bottom_sheet(self): """Show menu from the screen BottomSheet.""" if not self.bs_menu_2: from kivymd.uix.bottomsheet import MDGridBottomSheet self.bs_menu_2 = MDGridBottomSheet() self.bs_menu_2.add_item( "Facebook", lambda x: self.callback_for_menu_items("Facebook"), icon_src="./assets/facebook-box.png", ) self.bs_menu_2.add_item( "YouTube", lambda x: self.callback_for_menu_items("YouTube"), icon_src="./assets/youtube-play.png", ) self.bs_menu_2.add_item( "Twitter", lambda x: self.callback_for_menu_items("Twitter"), icon_src="./assets/twitter.png", ) self.bs_menu_2.add_item( "Da Cloud", lambda x: self.callback_for_menu_items("Da Cloud"), icon_src="./assets/cloud-upload.png", ) self.bs_menu_2.add_item( "Camera", lambda x: self.callback_for_menu_items("Camera"), icon_src="./assets/camera.png", ) self.bs_menu_2.open() def set_title_toolbar(self, title): """Set string title in MDToolbar for the whole application.""" self.main_widget.ids.toolbar.title = title def set_appbar(self): """Create MDBottomAppBar for the screen BottomAppBar.""" from kivymd.uix.toolbar import MDBottomAppBar def press_button(inctance): toast("Press Button") self.md_app_bar = MDBottomAppBar( md_bg_color=self.theme_cls.primary_color, left_action_items=[ ["menu", lambda x: x], ["clock", lambda x: x], ["dots-vertical", lambda x: x], ], anchor="right", callback=press_button, ) def move_item_menu(self, anchor): """Sets icons in MDBottomAppBar for the screen BottomAppBar.""" md_app_bar = self.md_app_bar if md_app_bar.anchor != anchor: if len(md_app_bar.right_action_items): md_app_bar.left_action_items.append( md_app_bar.right_action_items[0]) md_app_bar.right_action_items = [] else: left_action_items = md_app_bar.left_action_items action_items = left_action_items[0:2] md_app_bar.right_action_items = [left_action_items[-1]] md_app_bar.left_action_items = action_items def show_password(self, field, button): """ Called when you press the right button in the password field for the screen TextFields. instance_field: kivy.uix.textinput.TextInput; instance_button: kivymd.button.MDIconButton; """ # Show or hide text of password, set focus field # and set icon of right button. field.password = not field.password field.focus = True button.icon = "eye" if button.icon == "eye-off" else "eye-off" def set_error_message(self, *args): """Checks text of TextField with type "on_error" for the screen TextFields.""" text_field_error = args[0] if len(text_field_error.text) == 2: text_field_error.error = True else: text_field_error.error = False def set_list_md_icons(self, text="", search=False): """Builds a list of icons for the screen MDIcons.""" def add_icon_item(name_icon): self.main_widget.ids.scr_mngr.get_screen( "md icons").ids.rv.data.append({ "viewclass": "MDIconItemForMdIconsList", "icon": name_icon, "text": name_icon, "callback": self.callback_for_menu_items, }) self.main_widget.ids.scr_mngr.get_screen("md icons").ids.rv.data = [] for name_icon in md_icons.keys(): if search: if text in name_icon: add_icon_item(name_icon) else: add_icon_item(name_icon) def set_source_code_file(self): """Assigns the file_source_code attribute the file name with example code for the current screen.""" if self.main_widget.ids.scr_mngr.current == "code viewer": return has_screen = False for name_item_drawer in self.data.keys(): if (self.data[name_item_drawer]["name_screen"] == self.main_widget.ids.scr_mngr.current): self.file_source_code = self.data[name_item_drawer].get( "source_code", None) has_screen = True break if not has_screen: self.file_source_code = None def open_context_menu_source_code(self, instance): def callback_context_menu(icon): context_menu.dismiss() if not self.file_source_code: from kivymd.uix.snackbar import Snackbar Snackbar(text="No source code for this example").show() return if icon == "source-repository": if platform in ("win", "linux", "macosx"): webbrowser.open( f"https://github.com/HeaTTheatR/KivyMD/wiki/" f"{os.path.splitext(self.file_source_code)[0]}") return elif icon == "language-python": self.main_widget.ids.scr_mngr.current = "code viewer" if self.file_source_code: with open( f"{self.directory}/KivyMD.wiki/{self.file_source_code}" ) as source_code: self.data["Source code"][ "object"].ids.code_input.text = source_code.read() menu_for_context_menu_source_code = [] data = { "Source code": "language-python", "Open in Wiki": "source-repository", } if self.main_widget.ids.scr_mngr.current == "code viewer": data = {"Open in Wiki": "source-repository"} for name_item in data.keys(): menu_for_context_menu_source_code.append({ "viewclass": "MDIconItemForMdIconsList", "text": name_item, "icon": data[name_item], "text_color": [1, 1, 1, 1], "callback": lambda x=name_item: callback_context_menu(x), }) context_menu = MDDropdownMenu( items=menu_for_context_menu_source_code, max_height=dp(260), width_mult=3, ) context_menu.open(instance.ids.right_actions.children[0]) def open_menu_for_demo_apps(self, instance): """ Called when you click the "Click me" button on the start screen. Creates and opens a list of demo applications. :type instance: <kivymd.uix.button.MDRaisedButton object> """ if not self.instance_menu_demo_apps: menu_for_demo_apps = [] for name_item in self.demo_apps_list: menu_for_demo_apps.append({ "viewclass": "OneLineListItem", "text": name_item, "on_release": lambda x=name_item: self.show_demo_apps(x), }) self.instance_menu_demo_apps = MDDropdownMenu( items=menu_for_demo_apps, max_height=dp(260), width_mult=4, _center=True, ) self.instance_menu_demo_apps.open(instance) def show_demo_apps(self, name_item): self.show_screens_demo(name_item) self.main_widget.ids.scr_mngr.current = name_item.lower() self.instance_menu_demo_apps.dismiss() def on_pause(self): return True def on_start(self): def _load_kv_for_demo(name_screen): from demo_apps.formone import FormOne from demo_apps.shopwindow import ShopWindow from demo_apps.coffeemenu import CoffeeMenu from demo_apps.fitnessclub import FitnessClub from demo_apps.accountpage import AccountPage Builder.load_string(self.data_for_demo[name_screen]["kv_string"]) self.data_for_demo[name_screen]["object"] = eval( self.data_for_demo[name_screen]["class"]) self.main_widget.ids.scr_mngr.add_widget( self.data_for_demo[name_screen]["object"]) async def load_all_kv_files(): for name_screen in self.data.keys(): await asynckivy.sleep(0) self.dialog_load_kv_files.name_kv_file = name_screen Builder.load_string(self.data[name_screen]["kv_string"]) self.data[name_screen]["object"] = eval( self.data[name_screen]["Factory"]) if name_screen == "Bottom App Bar": self.set_appbar() self.data[name_screen]["object"].add_widget( self.md_app_bar) self.main_widget.ids.scr_mngr.add_widget( self.data[name_screen]["object"]) if name_screen == "Text fields": self.data[name_screen]["object"].ids.text_field_error.bind( on_text_validate=self.set_error_message, on_focus=self.set_error_message, ) elif name_screen == "MD Icons": self.set_list_md_icons() elif name_screen == "Tabs": self.build_tabs() elif name_screen == "Refresh Layout": self.set_list_for_refresh_layout() from demo_apps.formone import registration_form_one from demo_apps.shopwindow import screen_shop_window from demo_apps.coffeemenu import screen_coffee_menu from demo_apps.fitnessclub import screen_fitness_club from demo_apps.accountpage import screen_account_page data = { "Registration": registration_form_one, "Shop Window": screen_shop_window, "Coffee Menu": screen_coffee_menu, "Fitness Club": screen_fitness_club, "Account Page": screen_account_page, } for name_screen in data.keys(): await asynckivy.sleep(0) self.dialog_load_kv_files.name_kv_file = name_screen self.data_for_demo[name_screen]["kv_string"] = data[ name_screen] _load_kv_for_demo(name_screen) self.dialog_load_kv_files.dismiss() self.dialog_load_kv_files = DialogLoadKvFiles() self.dialog_load_kv_files.open() asynckivy.start(load_all_kv_files()) def on_stop(self): pass def open_settings(self, *args): return False
class MainApp(MDApp): gridi = None def __init__(self, **kwargs): super(MainApp, self).__init__(**kwargs) Window.bind(on_keyboard=self.events) self.manager_open = False self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, previous=True, ) def build(self): self.saturday = DaiBox() self.sunday = DaiBox() self.monday = DaiBox() self.tuesday = DaiBox() self.wednesday = DaiBox() self.thursday = DaiBox() self.friday = DaiBox() self.day = { 'Saturday': self.saturday, 'Sunday': self.sunday, 'Monday': self.monday, 'Tuesday': self.tuesday, 'Wednesday': self.wednesday, 'Thursday': self.thursday, 'Friday': self.friday, } self.main_screen = Main_screen() self.s = self.main_screen.ids.scroll self.b = self.main_screen.ids.sale_box self.pro = self.main_screen.ids.profile self.pro_scr = self.pro.ids.pro_scr self.pro_scr.current = "review" self.category = self.b.ids.category self.titl = self.b.ids.title self.desc = self.b.ids.description self.amnt = self.b.ids.amount self.price = self.b.ids.price return self.main_screen def s_pop(self, *args): self.s_pop = S_popup() self.s_pop.open() def close_spopup(self, *args): self.s_pop.dismiss() def bottom_sheet(self, *args): self.b_menu = MDListBottomSheet(radius=15, radius_from="top") self.b_menu.add_item(text="Change Profile Photo", callback=self.pro_photo) self.b_menu.add_item(text="Change Cover Photo", callback=self.pro_photo) self.b_menu.open() def pro_photo(self, *args): print("Okk") def dailouge(self, id, *args): self.recent_day = self.day[id.text] self.modal = ModalView(size_hint=(0.95, 0.5), auto_dismiss=False) self.modal.add_widget(self.recent_day) self.modal.open() def dai_ok(self): self.modal.dismiss() Clock.schedule_once(self.daii_ok, 0.2) def daii_ok(self, *args): self.modal.clear_widgets() del self.modal def submit(self, *args): self.sat = [ self.saturday.ids.a.active, self.saturday.ids.b.active, self.saturday.ids.c.active, self.saturday.ids.d.active, self.saturday.ids.e.active ] self.sun = [ self.sunday.ids.a.active, self.sunday.ids.b.active, self.sunday.ids.c.active, self.sunday.ids.d.active, self.sunday.ids.e.active ] self.mon = [ self.monday.ids.a.active, self.monday.ids.b.active, self.monday.ids.c.active, self.monday.ids.d.active, self.monday.ids.e.active ] self.tue = [ self.tuesday.ids.a.active, self.tuesday.ids.b.active, self.tuesday.ids.c.active, self.tuesday.ids.d.active, self.tuesday.ids.e.active ] self.wed = [ self.wednesday.ids.a.active, self.wednesday.ids.b.active, self.wednesday.ids.c.active, self.wednesday.ids.d.active, self.wednesday.ids.e.active ] self.thu = [ self.thursday.ids.a.active, self.thursday.ids.b.active, self.thursday.ids.c.active, self.thursday.ids.d.active, self.thursday.ids.e.active ] self.fri = [ self.friday.ids.a.active, self.friday.ids.b.active, self.friday.ids.c.active, self.friday.ids.d.active, self.friday.ids.e.active ] self.sat = [str(i) for i in self.sat] self.sun = [str(i) for i in self.sun] self.mon = [str(i) for i in self.mon] self.tue = [str(i) for i in self.tue] self.wed = [str(i) for i in self.wed] self.thu = [str(i) for i in self.thu] self.fri = [str(i) for i in self.fri] self.result = {} self.result["category"] = self.category.text self.result["title"] = self.titl.text self.result["description"] = self.desc.text self.result["amount"] = self.amnt.text self.result["Saturday"] = self.sat self.result["Sunday"] = self.sun self.result["Monday"] = self.mon self.result["Tuesday"] = self.tue self.result["Wednesday"] = self.wed self.result["Thursday"] = self.thu self.result["Friday"] = self.fri print(self.result) def file_manager_open(self): if self.gridi == None: self.file_manager.show('/storage/emulated/0/') self.manager_open = True else: toast("Only 1 Photo!") def select_path(self, path): if self.gridi == None: self.path = str(path) self.gridi = self.b.ids.grid_img self.grdimg = GridImage() self.img = self.grdimg.ids.img self.img.source = self.path self.gridi.add_widget(self.grdimg) self.exit_manager() toast(path) else: self.exit_manager() toast("Only 1 Photo!") def close_image(self, *args): self.gridi.remove_widget(self.grdimg) del self.grdimg del self.img self.gridi = None def exit_manager(self, *args): self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True
def storage_bottom_sheet_android(self, *args): #toolbar = MDToolbar(title="This is a toolbar") bottom_sheet_menu = MDListBottomSheet() bottom_sheet_menu.add_item("Internal Storage", lambda x: self.storageLink('/storage/emulated/0'), icon='cellphone-android') bottom_sheet_menu.add_item("SD Card", lambda x: self.storageLink('/storage'), icon='micro-sd') bottom_sheet_menu.open()
def imageGallery_show_list_bottom_sheet(self, *args): #toolbar = MDToolbar(title="This is a toolbar") bottom_sheet_menu = MDListBottomSheet() bottom_sheet_menu.add_item("Astronomy Picture of the Day (APOD)", lambda x: self.imgGal('apod'), icon='numeric-1-circle') bottom_sheet_menu.open()
class RegisterUIDScreen(Screen): # APIs nfc_id = None def __init__(self, **kwargs): # Load KV file for this screen Builder.load_file('kvs/RegisterUIDScreen.kv') # call to user with arguments super(RegisterUIDScreen, self).__init__(**kwargs) # local list that stores all mailadresses currently retrieved from the database self.mail_list = [] # Timeout variables self.timeout_event = None self.timeout_time = 30 # Create the bottom menu self.bottom_sheet_menu = None self.event_loop: AbstractEventLoop = App.get_running_app().loop # # Function is called when the product screen is entered # def on_enter(self, *args): self.timeout_event = Clock.schedule_once(self.on_timeout, self.timeout_time) # # Timeout callback function # def on_timeout(self, dt): if self.bottom_sheet_menu: self.bottom_sheet_menu.dismiss() self.timeout_event.cancel() self.on_cancel() # # reset timing procedure when the screen is pressed # def on_touch_up(self, touch): self.timeout_event.cancel() self.on_enter() # Return to default screen when cancelled def on_cancel(self): self.manager.current = Screens.DEFAULT_SCREEN.value # Saves user-card-mapping to the database def on_save_user(self): # Validate whether a correct user was selected. if self.ids.chosen_user.text not in App.get_running_app( ).user_mapping.keys(): self.ids.chosen_user.text = "Selecteer een account" return selected_user_name = self.ids.chosen_user.text selected_user_email = App.get_running_app( ).user_mapping[selected_user_name] App.get_running_app().loop.call_soon_threadsafe( self.register_card_mapping, selected_user_name, selected_user_email) def register_card_mapping(self, selected_user_name, selected_user_email: str): # Use a POST command to add connect this UID to the user request = App.get_running_app().session_manager.do_post_request( url=Connections.add_user_mapping(), json_data={ 'card_id': str(self.nfc_id), 'email': selected_user_email }) # If the users was added successfully ( status_code : 200), proceed to WelcomeScreen if request.ok: # Store the active user in the app so other screens can use it. App.get_running_app().active_user = selected_user_name self.manager.current = Screens.WELCOME_SCREEN.value else: # User could not be added succesfully, give error 2. Logger.critical( "StellaPayUI: Error " + str(request.status_code) + " occurred when trying to add the user: error message: " + request.text) os._exit(1) # # Whenever the user wants to show the list of users to register the card to. # def on_click_user_list_button(self): # Restart timeout procedure self.timeout_event.cancel() self.on_enter() # Add items to the bottom list self.bottom_sheet_menu = MDListBottomSheet(height="200dp") for user_name, user_email in sorted( App.get_running_app().user_mapping.items()): # store all emails addresses in the sheet_menu self.bottom_sheet_menu.add_item(user_name, self.on_user_selected) # open the bottom sheet menu self.bottom_sheet_menu.open() # When the user selects a user to register for this card. def on_user_selected(self, item): self.timeout_event.cancel() self.on_enter() self.ids.chosen_user.text = item.text def on_leave(self, *args): # Stop the timer self.timeout_event.cancel() # Hide name of selected user self.ids.chosen_user.text = ""
def bottom_layer(self): botton_sheet = MDListBottomSheet(radius=10,radius_from='top') for i in range(10): botton_sheet.add_item(f"item {i+1}",lambda x, y=i: self.call_Back(f"item {y+1} clicked")) botton_sheet.open()
class Main(MDApp): def build(self): return Builder.load_string(kv) def new_thread(self, url): thread = threading.Thread(self.select_res(url)) thread.start() def show_snackbar(self, instance): Snackbar(text=instance).show() def progress_check(self, stream, chunk, bytes_remaining): self.root.ids.spnr.active = False percent = ((fileSize - bytes_remaining) / fileSize) * 100 self.root.ids.btn.text = f"{percent:0.00f} % Downloading" self.root.ids.prgsbr.value = int(percent) self.root.ids.dl.text = f"{percent:0.00f} Download" def download_complete(self, stream, file_path): Snackbar(text="Dowloading Complete") time.sleep(5) self.root.ids.btn.text = "Select Resolution" self.root.ids.prgsbr.value = 0 def select_res(self, instance): try: self.root.ids.spnr.active = True self.v_yt = YouTube(instance) self.v_yt.register_on_progress_callback(self.progress_check) self.v_yt.register_on_complete_callback(self.download_complete) self.bottomsheet = MDListBottomSheet() try: self.r144 = self.v_yt.streams.filter(file_extension='mp4', res='144p', progressive=True).all() self.bottomsheet.add_item( f"144p {self.r144[0].filesize:.2f} MB", lambda x: self.Download(self.r144)) except: self.bottomsheet.add_item(f"144p Unavailable", lambda x: sys.exit()) try: self.r240 = self.v_yt.streams.filter(file_extension='mp4', res='240p', progressive=True).all() self.bottomsheet.add_item( f"240p {self.r240[0].filesize:.2f} MB", lambda x: self.Download(self.r240)) except: self.bottomsheet.add_item(f"240p Unavailable", lambda x: sys.exit()) try: self.r360 = self.v_yt.streams.filter(file_extension='mp4', res='360p', progressive=True).all() self.bottomsheet.add_item( f"360p {self.r360[0].filesize/1000000:.2f} MB", lambda x: self.Download(self.r360)) except: self.bottomsheet.add_item(f"360p Unavailable", lambda x: sys.exit()) try: self.r480 = self.v_yt.streams.filter(file_extension='mp4', res='480p', progressive=True).all() self.bottomsheet.add_item( f"480p {self.r480[0].filesize:.2f} MB", lambda x: self.Download(self.r480)) except: self.bottomsheet.add_item(f"480p Unavailable", lambda x: sys.exit()) try: self.r720 = self.v_yt.streams.filter(file_extension='mp4', res='720p', progressive=True).all() self.bottomsheet.add_item( f"720p {self.r720[0].filesize:.2f} MB", lambda x: self.Download(self.r720)) except: self.bottomsheet.add_item(f"720p Unavailable", lambda x: sys.exit()) self.bottomsheet.open() except: self.show_snackbar("Connect to the Internet") self.root.ids.spnr.active = False def Download(self, instance): global fileSize fileSize = instance[0].filesize self.show_snackbar("Downloading Start") instance[0].download(r"\sdcard")
def show_bottom_sheet(self): bs = MDListBottomSheet() bs.add_item("Model správania", lambda x: x, icon='account-group-outline') #for y in 1,2,3,4,12,13,14,21,23,24,31,32,34,41,42,43,123,124,134,234: # bs.add_item(f"{len(self.bs.children) + y} osobnosť",lambda x: self.behavior1(),icon='account-group-outline') bs.add_item("1", lambda x: self.behavior1(), icon='account-group-outline') bs.add_item("2", lambda x: self.behavior2(), icon='account-group-outline') bs.add_item("3", lambda x: self.behavior3(), icon='account-group-outline') bs.add_item("4", lambda x: self.behavior4(), icon='account-group-outline') bs.add_item("12", lambda x: self.behavior12(), icon='account-group-outline') bs.add_item("13", lambda x: self.behavior13(), icon='account-group-outline') bs.add_item("14", lambda x: self.behavior14(), icon='account-group-outline') bs.add_item("21", lambda x: self.behavior21(), icon='account-group-outline') bs.open()