def build(self): # Register the app directory as a resource directory kvres.resource_add_path(self.directory) self._slider_transport = None self._slider_protocol = None self._fired = 0 self._led_updates = 0
def _test(): import os from kivy.resources import resource_add_path, resource_find from kivy.factory import Factory from kivy.lang import Builder from kivy.base import runTouchApp from kivy.properties import DictProperty, ObjectProperty import yaml for parent, __1, __2 in os.walk('./data'): resource_add_path(parent) Builder.load_string(r''' <Button>: font_size: 30 <RootWidget>: BoxLayout: BoxLayout: orientation: 'vertical' Button: text: 'play' on_press: root.bgmplayer.play(spinner.text) Button: text: 'play(save_previous)' on_press: root.bgmplayer.play(spinner.text, save_previous_bgm_offset=True) Button: text: 'stop' on_press: root.bgmplayer.stop() Button: text: 'pause' on_press: root.bgmplayer.pause() AnchorLayout: anchor_y: 'top' anchor_x: 'center' Spinner: id: spinner sync_height: True size_hint_y: None height: 50 ''') class RootWidget(Factory.FloatLayout): soundfile_dict = DictProperty() bgmplayer = ObjectProperty() def __init__(self, *, soundfile_dict, **kwargs): super().__init__(soundfile_dict=soundfile_dict, **kwargs) self.bgmplayer = BgmPlayer(soundfile_dict) spinner = self.ids.spinner spinner.values = list(soundfile_dict.keys()) spinner.text = spinner.values[0] with open(resource_find('soundfile_dict.yaml'), 'rt') as reader: soundfile_dict = { key: filename for key, filename in yaml.load(reader).items() if key.startswith('bgm_') } print(soundfile_dict) runTouchApp(RootWidget(soundfile_dict=soundfile_dict))
def get_system_fonts_dir(): """Return the Directory used by the system for fonts. """ if LabelBase._fonts_dirs: return LabelBase._fonts_dirs fdirs = [] if platform == "linux": fdirs = [ "/usr/share/fonts/truetype", "/usr/local/share/fonts", os.path.expanduser("~/.fonts"), os.path.expanduser("~/.local/share/fonts"), ] elif platform == "macosx": fdirs = ["/Library/Fonts", "/System/Library/Fonts", os.path.expanduser("~/Library/Fonts")] elif platform == "win": fdirs = [os.environ["SYSTEMROOT"] + os.sep + "Fonts"] elif platform == "ios": fdirs = ["/System/Library/Fonts"] elif platform == "android": fdirs = ["/system/fonts"] if fdirs: fdirs.append(kivy_data_dir + os.sep + "fonts") # let's register the font dirs rdirs = [] for _dir in fdirs: if os.path.exists(_dir): resource_add_path(_dir) rdirs.append(_dir) LabelBase._fonts_dirs = rdirs return rdirs raise Exception("Unknown Platform {}".format(platform))
def emulate_file(filename): root=None dirname=os.path.dirname(filename) sys.path.append(dirname) resource_add_path(dirname) emulator_area().screen_display.screen.clear_widgets() if os.path.splitext(filename)[1] =='.kv': # load the kivy file directly try: # cahching error with kivy files Builder.unload_file(filename) root = Builder.load_file(filename) except: traceback.print_exc() print("You kivy file has a problem") elif os.path.splitext(filename)[1] =='.py': load_defualt_kv(filename) try: # cahching error with python files root = load_py_file(filename) except: traceback.print_exc() print("You python file has a problem") if root: emulator_area().screen_display.screen.add_widget(root) else: pass sys.path.pop() resource_remove_path(dirname)
def emulate_file(filename, threaded=False): if not filename: Logger.error( "KivyStudio: No file selected press Ctrl-E to select file for emulation" ) return Logger.info("Emulator: Starting Emulation on file '{}'".format(filename)) root = None if not os.path.exists(filename): Logger.error("KivyStudio: file {} not found".format(filename)) return with open(filename) as fn: file_content = fn.read() if app_not_run_properly(file_content): Logger.error( "Emulator: App not run properly 'try running under if __name__ == '__main__':" ) return dirname = os.path.dirname(filename) sys.path.append(dirname) os.chdir(dirname) resource_add_path(dirname) get_emulator_area().screen_display.screen.clear_widgets() if threaded: Thread(target=partial( start_emulation, filename, file_content, threaded=threaded)).start() else: start_emulation(filename, file_content, threaded=threaded)
def main(fake): # make sure we stash forced value cfg.FAKE = fake # but if we don't have picamera, we have to fake it anyway if not cfg.FAKE and not _has_cam: cfg.FAKE = True if not cfg.FAKE: Config.set("graphics", 'show_cursor', 0) Config.set('graphics', 'width', '320') Config.set('graphics', 'height', '240') # this is needed so kv files can find images resources.resource_add_path( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'res' )) # and this one is for loading kv files resources.resource_add_path( os.path.join( os.path.dirname(os.path.realpath(__file__)), 'kv' )) # launch app if cfg.FAKE: CamApp(None).run() else: with picamera.PiCamera(sensor_mode=cfg.MODE, framerate=cfg.FRAME_RATE) as camera: CamApp(camera).run()
def config(width, height): Config.set('graphics', 'resizable', False) Config.set('graphics', 'width', width) Config.set('graphics', 'height', height) resource_add_path("./modell") resource_add_path("./view/standard_theme/figures") Window.size = (width, height)
def __init__(self, *largs): self.resources = list(self.search_data_files()) resource_add_path(dirname(__file__)) Builder.load_file(join(dirname(__file__), 'map.kv')) super(MapServer, self).__init__(*largs) self.timeout = 0 self.timemsg = 0 self.players = {} # init client table for client in self.controler.clients: self.players[client] = { 'client': client, 'name': self.controler.get_client_name(client), 'ready': False, 'done': False, 'place': self.controler.metadata[client]['place'], 'count': 0 } #store mapitems and thumbs in order to display them on main screen #or remove them from clients self.mapitems = {} #filename: [client, index] self.thumbs = {} #index: [client, pos] #get map layers list from json self.load_json()
def build(self): if hasattr(sys, '_MEIPASS'): resource_add_path(os.path.join(sys._MEIPASS, 'resources')) else: resource_add_path('resources') LabelBase.register( name='SourceCodePro', fn_regular=resource_find('fonts/SourceCodePro-Regular.ttf')) layout = Builder.load_string(layout_pc.kv) self._writing_layout = Builder.load_string( layout_pc.write_lesson_panel) self._reading_layout = Builder.load_string(layout_pc.read_lesson_panel) self._content_block = layout.ids[LayoutIds.content_panel] self.icon = resource_find('images/cw_typist.ico') action_previous = layout.ids[LayoutIds.action_previous] action_previous.app_icon = resource_find('images/cw_typist.png') Window.size = (dp(1200), dp(500)) Window.clearcolor = (0.15, 0.15, 0.15, 1) Window.bind(on_key_down=self.key_down_handler) Window.bind(on_key_up=self.key_up_handler) self._key_lock = False self.title = f'CW Typist v{cw_typist_version.version}' self._bind_lesson_buttons(layout) self._bind_file_menu(layout) self._bind_sound_menu(layout) self._bind_help_menu(layout) self._bind_write_layout(self._writing_layout) self._bind_read_layout(self._reading_layout) self.switch_to_write(None) return layout
def get_system_fonts_dir(): '''Return the Directory used by the system for fonts. ''' if LabelBase._fonts_dirs: return LabelBase._fonts_dirs fdirs = [] if platform == 'linux': fdirs = [ '/usr/share/fonts/truetype', '/usr/local/share/fonts', os.path.expanduser('~/.fonts'), os.path.expanduser('~/.local/share/fonts')] elif platform == 'macosx': fdirs = ['/Library/Fonts', '/System/Library/Fonts', os.path.expanduser('~/Library/Fonts')] elif platform == 'win': fdirs = [os.environ['SYSTEMROOT'] + os.sep + 'Fonts'] elif platform == 'ios': fdirs = ['/System/Library/Fonts'] elif platform == 'android': fdirs = ['/system/fonts'] if fdirs: fdirs.append(kivy_data_dir + os.sep + 'fonts') # let's register the font dirs rdirs = [] for _dir in fdirs: if os.path.exists(_dir): resource_add_path(_dir) rdirs.append(_dir) LabelBase._fonts_dirs = rdirs return rdirs raise Exception("Unknown Platform {}".format(platform))
def build_config(self, config): config.app = self Config.app = self config.adddefaultsection("Karaokivy") config.setdefaults("Karaokivy", { "theme": "Default", "fullscreen": "no", "dual_screen": "off", "bg_type": "Color", "bg_image": "", "bg_color": "#000000", "sung_color": "#FF0000", "tosing_color": "#00FF00", "font_family": "sans-serif", "soundfont": ""}) self.theme = str(self.config.get("Karaokivy", "theme")) self.themepath = self.get_theme_path(self.theme) resources.resource_add_path(self.themepath) manifest = self.pm.load_plugin_manifest(join(self.themepath, "manifest.json")) plug = self.pm.load_plugin(manifest) self.theme_plugin = {"manifest": manifest, "module": plug} kv = join(self.themepath, "theme.kv") if os.path.exists(kv): self.load_kv(kv)
def FromFile(cls, filename, use_cache = False): Logger.info('From File with ' + str(filename)) if not use_cache: Logger.info(' From File without cache') from os.path import split from kivy.resources import resource_add_path import sys resource_add_path(split(filename)[0]) sys.path.append(split(filename)[0]) name, filename = find_template_path(filename) #Add filename dir to ressources folder to facilitate relativ import #Load & return all templates from a file as a list. Take an optionnal filter from kivy.lang import Builder # Remove any former trace of the file if use_cache and filename in templateList.templates: res = templateList[filename] res = [r.blank() for r in res] else: Builder.unload_file(filename) # Now create a widget try: Builder.load_file(filename) res = cls._process_file_build(filename) templateList[filename] = res except Exception, E: from utils import alert from utils import log import traceback alert(str(E)) Logger.error('[Error] While trying to import Template %s'%filename) log(E, traceback.print_exc()) res = list()
def __init__(self, **kwargs): super(main_display, self).__init__(**kwargs) resource_add_path('./fonts') LabelBase.register(DEFAULT_FONT, 'ARIALUNI.TTF') Window.clearcolor = (1, 1, 1, 1) session = ObjectProperty() headers = ObjectProperty() self.cols = 1 search_bar = Builder.template('Search_Bar', size_hint=(1, 0.06)) self.add_widget(search_bar) info_display = GridLayout(cols=1, spacing=10, size_hint_y=None) info_display.bind(minimum_height=info_display.setter('height')) self.session, self.headers, search_result = self.search('') if search_result != []: for novel in search_result: novel_info_view = Builder.template('Novel_Info', **novel, cols=1, size_hint_y=None) info_display.add_widget(novel_info_view) tag_box = GridLayout(cols=4, size_hint=(1, None)) for tag in novel['tags']: tag_button = Button(text=tag) tag_box.add_widget(tag_button) info_display.add_widget(tag_box) scrollView_page = ScrollView(size=(Window.width, Window.height * 0.94)) scrollView_page.add_widget(info_display) else: scrollView_page = ScrollView(size=(Window.width, Window.height * 0.94)) scrollView_page.add_widget(info_display) self.add_widget(scrollView_page)
def load(self): curdir = join(dirname(__file__), 'data') json_filename = join(curdir, 'scenario.json') resource_add_path(curdir) with open(json_filename, 'r') as fd: data = load(fd) self.layers = data['layers']
def load_kv(self, filename=''): """ Loads a kivy language file manually """ resource_add_path(os.path.dirname(os.path.abspath(__file__))) Builder.load_file( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'anontunnel.kv'))
def build(self): resource_add_path('C:/Users/Noah/Documents/allthingspython/SimpleApp') resource_find('ball.jpg') resource_find('field.jpg') game = Game() game.serve_ball() Clock.schedule_interval(game.update, 1 / 60.0) return game
def build(self): resource_add_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'resources')) screen = ReloaderScreen.screen() self.saveEvent = Clock.schedule_interval(Settings.settings().save, Config.config().getfloat('core', 'settingsSaveInterval')) bus.emit('app/start') return screen
def main(): # HACK: Add gui to resource path to find sub-dir icons # TODO: Figure out what to do with resource paths. resource_add_path(os.path.join(os.path.dirname(__file__), 'gui')) gui = TheApp() controller = MainController(gui, game_factory) controller.add_game('2-Back', 'nback', dict(n_back=2)) gui.run()
def init_load(self): """Creates any config files and adds :attr:`data_path` to the kivy resource PATH when the app is instantiated. """ d = self.data_path if isdir(d): resource_add_path(d) self.ensure_file(self.yaml_config_path)
def register_kv_and_data(): '''Registers the data and kv paths in Kivy resources system.''' global _registered if _registered: return for path in _data_paths + _kv_paths: p = os.path.join(_base_path, path) resource_add_path(p) _registered = True
def gui_run(): resource_add_path('../resources') LabelBase.register(DEFAULT_FONT, 'ipaexg.ttf') Config.set('kivy','window_icon','../DetExploit.ico') run_on = platform.system() if run_on == 'Windows': detexploit().run() else: exit(1)
def set_kivy_resource_path(): from os.path import dirname, abspath from kivy.resources import resource_add_path, resource_paths # Add this directory to kivy resource path. # NOTE: All kivy widgets must have unique names so this is not an additional constraint. kv_dir = abspath(dirname(__file__)) Logger.info('Adding {} to resource path'.format(kv_dir)) resource_add_path(kv_dir) Logger.info('Resource path={}'.format(resource_paths))
def load(self): curdir = join(dirname(__file__), 'data') json_filename = join(curdir, 'scenario.json') resource_add_path(curdir) with open(json_filename, 'r') as fd: data = load(fd) self.date_start = data['date_start'] self.date_end = data['date_end'] self.date_step = data['date_step'] self.date_allowed_offset = data['date_allowed_offset'] self.data = data['items']
def build(self): """create and config main app""" resource_add_path(PATH_TO_IMAGES) screen_manager = ScreenManager() screen_manager.add_widget(MainScreen(name="main")) screen_manager.add_widget(ResultScreen(name="result")) screen_manager.add_widget(FailScreen(name="fail")) return screen_manager
def run_gui(translator): if hasattr(sys, '_MEIPASS'): resource_add_path(os.path.join(sys._MEIPASS)) if translator == "": from telsistrans import telsis_translator translator = telsis_translator() app = TelsisApp() app.set_translator(translator) Window.size = (480, 720) app.run()
def _load_font_paths(self): # Add local machine fonts path if os.path.isdir(os.path.join(self.machine_path, self.machine_config['mpf-mc']['paths']['fonts'])): resource_add_path(os.path.join(self.machine_path, self.machine_config['mpf-mc']['paths']['fonts'])) # Add mpfmc fonts path resource_add_path(os.path.join(os.path.dirname(mpfmc.__file__), 'fonts'))
def main() : try : if kivy.platform == u'win' : win_root= os.environ.get( u'%SystemRoot%', u'C:\\WINDOWS' ) win_fonts= os.path.join( win_root, u'Fonts' ) resource_add_path( win_fonts ) elif kivy.platform == u'android' : resource_add_path( u'/system/fonts/' ) GameApp().run() except Exception, e : Logger.error( traceback.format_exc() )
def load(self): curdir = join(dirname(__file__), "data") json_filename = join(curdir, "scenario.json") resource_add_path(curdir) with open(json_filename, "r") as fd: data = load(fd) self.date_start = data["date_start"] self.date_end = data["date_end"] self.date_step = data["date_step"] self.date_allowed_offset = data["date_allowed_offset"] self.data = data["items"]
def get_mod(modname,moddir): mod_str = '' resource_add_path(moddir) modpath = resource_find(modname + '.module') print 'Manjeet: modpath ',modpath if modpath == None: print 'Module not found' , modpath return mod_str with open(modpath,'r') as mf: mod_str += mf.read() print 'Manjeet: module str:\n', mod_str return mod_str
def get_font_list(): '''Get a list of all the fonts available on this system. ''' CoreLabel._fonts_dirs.append(FONTS_DIR) fonts_path = CoreLabel.get_system_fonts_dir() flist = [] resource_add_path(FONTS_DIR) for fdir in fonts_path: for fpath in sorted(os.listdir(fdir)): if fpath.endswith('.ttf'): flist.append(fpath[:-4]) return sorted(flist)
def build(self): root = os.path.join(os.path.dirname(__file__)) # Register shiny font font_path = os.path.join(root, 'assets', 'FuturaRenner-Regular.ttf') LabelBase.register("Futura", font_path) # Set images directory resource_add_path(os.path.join(root, "images")) Factory.register(cls=BoxLastLayout, classname="BoxLastLayout") return FlightPanel(DEFAULT_HOST, 27257)
def build(self): filename = self.options["filename"] if isdir(filename): directory = filename filename = join(filename, "presentation.kv") else: directory = dirname(filename) sys.path += [directory] resource_add_path(directory) template_fn = join(directory, "templates.kv") if exists(template_fn): Builder.load_file(template_fn) return Builder.load_file(filename)
def __init__(self, **kwargs): Window.size = (1024, 500) Window.minimum_width = 900 Window.minimum_height = 600 Window.x = 0 Window.y = 0 resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources') resource_add_path(resource_path) resource_add_path(os.path.join(resource_path, 'shaders')) super(SpikeGlApp, self).__init__(**kwargs) Config.set("input", "mouse", "mouse,disable_multitouch") Config.set("kivy", "exit_on_escape", 0) Logger.info("Starting up")
def run_app(): kv_file = find_package_resource("katrain/gui.kv") popup_kv_file = find_package_resource("katrain/popups.kv") resource_add_path(os.path.split(kv_file)[0]) Builder.load_file(kv_file) Builder.load_file(popup_kv_file) app = KaTrainApp() signal.signal(signal.SIGINT, app.signal_handler) try: app.run() except Exception as e: print(e) app.on_request_close() raise
def __init__(self, api, language=None, **kwargs): resource_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'resources') resource_add_path(resource_path) resource_add_path(os.path.join(resource_path, 'objects')) resource_add_path(os.path.join(resource_path, 'shaders')) resource_add_path(os.path.join(resource_path, 'images')) self.last_print = LastPrint() self.api = api self.setting_translation = SettingsMapper(self.api) if language: lang = language else: lang = locale.getdefaultlocale()[0] Logger.info("Specifed Language Locale: %s" % lang) if lang not in self.supported_languages: lang = 'en_GB' Window.size = (1000, 700) Window.minimum_width = 1000 Window.minimum_height = 700 super(PeachyPrinter, self).__init__(**kwargs) self.lang = lang Config.set("input", "mouse", "mouse,disable_multitouch") Config.set("kivy", "exit_on_escape", 0) Config.adddefaultsection('internal') self.switch_lang(self.lang) self.manager = None
def build(self): self.icon = ICON # how you're supposed to set an icon self.title = f"KaTrain v{VERSION}" self.theme_cls.theme_style = "Dark" self.theme_cls.primary_palette = "Gray" self.theme_cls.primary_hue = "200" kv_file = find_package_resource("katrain/gui.kv") popup_kv_file = find_package_resource("katrain/popups.kv") resource_add_path(PATHS["PACKAGE"] + "/fonts") resource_add_path(PATHS["PACKAGE"] + "/sounds") resource_add_path(PATHS["PACKAGE"] + "/img") resource_add_path(os.path.abspath(os.path.expanduser(DATA_FOLDER))) # prefer resources in .katrain theme_file = resource_find("theme.json") if theme_file: try: with open(theme_file) as f: theme_overrides = json.load(f) for k, v in theme_overrides.items(): setattr(Theme, k, v) print(f"[{theme_file}] Found theme override {k} = {v}") except Exception as e: # noqa E722 print(f"Failed to load theme file {theme_file}: {e}") Theme.DEFAULT_FONT = resource_find(Theme.DEFAULT_FONT) Builder.load_file(kv_file) Window.bind(on_request_close=self.on_request_close) Window.bind(on_dropfile=lambda win, file: self.gui.load_sgf_file(file.decode("utf8"))) self.gui = KaTrainGui() Builder.load_file(popup_kv_file) return self.gui
def emulate_file(filename, threaded=False): root = None dirname = os.path.dirname(filename) sys.path.append(dirname) resource_add_path(dirname) emulator_area().screen_display.screen.clear_widgets() if threaded: Thread(target=partial(start_emulation, filename, threaded=threaded)).start() else: start_emulation(filename, threaded=threaded)
def __init__(self, **kwargs): Window.size = (1024, 500) Window.minimum_width = 900 Window.minimum_height = 600 Window.x = 0 Window.y = 0 resource_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'resources') resource_add_path(resource_path) resource_add_path(os.path.join(resource_path, 'shaders')) super(SpikeGlApp, self).__init__(**kwargs) Config.set("input", "mouse", "mouse,disable_multitouch") Config.set("kivy", "exit_on_escape", 0) Logger.info("Starting up")
def __init__(self, api, language=None, **kwargs): resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources') resource_add_path(resource_path) resource_add_path(os.path.join(resource_path, 'objects')) resource_add_path(os.path.join(resource_path, 'shaders')) resource_add_path(os.path.join(resource_path, 'images')) self.last_print = LastPrint() self.api = api self.setting_translation = SettingsMapper(self.api) if language: lang = language else: lang = locale.getdefaultlocale()[0] Logger.info("Specifed Language Locale: %s" % lang) if lang not in self.supported_languages: lang = 'en_GB' Window.size = (1000, 700) Window.minimum_width = 1000 Window.minimum_height = 700 super(PeachyPrinter, self).__init__(**kwargs) self.lang = lang Config.set("input", "mouse", "mouse,disable_multitouch") Config.set("kivy", "exit_on_escape", 0) Config.adddefaultsection('internal') self.switch_lang(self.lang) self.manager = None
def __init__(self, **kwargs): super(LogScreen, self).__init__(**kwargs) platform = os.sys.platform font_name = 'DroidSansThai.ttf' if platform == 'linux2': resources.resource_add_path('/usr/share/fonts/truetype/droid/') elif platform == 'darwin': resources.resource_add_path('/Library/Fonts') self.cols = 2 self.add_widget(Label(text=u'ชื่อผู้ใช้งาน',font_name=font_name)) self.username = TextInput(multiline=False) self.add_widget(self.username) self.add_widget(Label(text=u'รหัสผ่าน',font_name=font_name)) self.password = TextInput(password=True, multiline=False) self.add_widget(self.password)
def extract_package(self): from zipfile import ZipFile import os import tempfile zip_name = self.name zip_path = os.path.abspath(zip_name) temp_dir = tempfile.mkdtemp(prefix='BGM_%s'%os.path.split(self.name)[-1]) from kivy.resources import resource_add_path resource_add_path(temp_dir) with ZipFile(zip_path, 'r') as zip_file: # Build a list of only the members below ROOT_PATH members = zip_file.namelist() # Extract only those members to the temp directory zip_file.extractall(temp_dir, members) from kivy.app import App dm = App.get_running_app().root.ids.deck #Looping on all mebers, resolving differntly depending on file type for m in members: if m.endsiwth('.kv'): m = os.path.join(temp_dir,m) Logger.info('Registering Package Template %s'%m) from template import templateList templateList.register_file(os.path.join(temp_dir, m)) #then deck elif m.endswith('.csv'): m = os.path.join(temp_dir,m) Logger.info('Loading CSV File %s'%m) dm.load_file_csv(os.path.join(temp_dir, m)) elif m.endwith('.xlsx'): m = os.path.join(temp_dir,m) Logger.info('Loading XLSX File %s'%m) dm.load_file(os.path.join(temp_dir, m)) elif m.endswith('.py'): #First python from imp import load_source m = os.path.join(temp_dir,m) Logger.info('Executing Package file %s'%m) load_source(m[:-3],m) from utils import start_file start_file(temp_dir) #Ensure the last CSV file is not saved, as it is parts of a package dm.record_last_file('')
def __init__(self, *largs): self.resources = list(self.search_data_files()) resource_add_path(dirname(__file__)) Builder.load_file(join(dirname(__file__), "fresco.kv")) super(FrescoServer, self).__init__(*largs) self.timeout = 0 self.timemsg = 0 self.players = {} # init client table for client in self.controler.clients: self.players[client] = { "client": client, "name": self.controler.get_client_name(client), "ready": False, "done": False, "place": self.controler.metadata[client]["place"], "count": 0, }
def load_file(self, filepath='myxlsfile.xlsx'): stack = self.ids['stack'] from kivy.resources import resource_add_path from os.path import split resource_add_path(split(filepath)[0]) from utils import XLRDDictReader from utils import find_path self.record_last_file(filepath) boxes = list() with open(filepath, 'rb') as XLFile: stds_headers = {'qt', 'source', 'template', 'dual', 'layout_x', 'layout_y', 'layout_w', 'layout_h', 'layout_angle', 'layout_page' } for obj in XLRDDictReader(XLFile): box = StackPart() box.qt = int(obj.get('qt', 0)) box.dual = 'dual' in obj and obj['dual'] values = dict() if "template" in obj and obj['template']: box.template = obj['template'] if 'source' in obj and obj['source']: _s = find_path(obj['source']) if _s is None: _s = obj['source'] box.source = _s if 'layout_x' in obj and 'layout_y' in obj and 'layout_w' in obj and 'layout_h' in obj and 'layout_angle' in obj and 'layout_page' in obj: box.layout = obj['layout_x'], obj['layout_y'], obj['layout_w'], obj['layout_h'], obj['layout_angle'], obj['layout_page'] for attr in obj: if attr in stds_headers: continue if obj[attr]: values[attr] = obj[attr] box.values = values stack.add_widget(box) boxes.append(box) boxes.reverse() self.refresh(boxes, msg='Import %s over'%split(filepath)[-1])
def get_system_fonts_dir(): """Return the directories used by the system for fonts. """ if LabelBase._fonts_dirs: return LabelBase._fonts_dirs fdirs = [] if platform == "linux": fdirs = [ "/usr/share/fonts", "/usr/local/share/fonts", os.path.expanduser("~/.fonts"), os.path.expanduser("~/.local/share/fonts"), ] elif platform == "macosx": fdirs = ["/Library/Fonts", "/System/Library/Fonts", os.path.expanduser("~/Library/Fonts")] elif platform == "win": fdirs = [os.path.join(os.environ["SYSTEMROOT"], "Fonts")] elif platform == "ios": fdirs = ["/System/Library/Fonts"] elif platform == "android": fdirs = ["/system/fonts"] else: raise Exception("Unknown platform: {}".format(platform)) fdirs.append(os.path.join(kivy_data_dir, "fonts")) # register the font dirs rdirs = [] _font_dir_files = [] for fdir in fdirs: for _dir, dirs, files in os.walk(fdir): _font_dir_files.extend(files) resource_add_path(_dir) rdirs.append(_dir) LabelBase._fonts_dirs = rdirs LabelBase._font_dirs_files = _font_dir_files return rdirs
def get_system_fonts_dir(): '''Return the directories used by the system for fonts. ''' if LabelBase._fonts_dirs: return LabelBase._fonts_dirs fdirs = [] if platform == 'linux': fdirs = [ '/usr/share/fonts', '/usr/local/share/fonts', os.path.expanduser('~/.fonts'), os.path.expanduser('~/.local/share/fonts')] elif platform == 'macosx': fdirs = ['/Library/Fonts', '/System/Library/Fonts', os.path.expanduser('~/Library/Fonts')] elif platform == 'win': fdirs = [os.path.join(os.environ['SYSTEMROOT'], 'Fonts')] elif platform == 'ios': fdirs = ['/System/Library/Fonts'] elif platform == 'android': fdirs = ['/system/fonts'] else: raise Exception("Unknown platform: {}".format(platform)) fdirs.append(os.path.join(kivy_data_dir, 'fonts')) # register the font dirs rdirs = [] _font_dir_files = [] for fdir in fdirs: for _dir, dirs, files in os.walk(fdir): _font_dir_files.extend(files) resource_add_path(_dir) rdirs.append(_dir) LabelBase._fonts_dirs = rdirs LabelBase._font_dirs_files = _font_dir_files return rdirs
from kivy.lang import Builder from os.path import dirname, realpath, join from gui import MicrogridApp from kivy.base import EventLoop from kivy.resources import resource_add_path SCRIPT_DIR = dirname(realpath(__file__)) resource_add_path(join(SCRIPT_DIR, 'resources')) Builder.load_file(join(SCRIPT_DIR, 'gui.kv')) if __name__ == '__main__': EventLoop.ensure_window() MicrogridApp().run()
if __name__ == '__main__': from designer.app import DesignerApp from kivy.resources import resource_add_path import os.path data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') resource_add_path(data) DesignerApp().run()
from PIL import Image import graficando_octavas import graficando_protectores import datos_protectores import H import H_prima import H_prt import H_prima_prt import butter_tercio import FileDialog from scipy.special import _ufuncs_cxx from kivy.resources import resource_add_path resource_add_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")) __author__ = "David Manuel Buitrago Montañez" __copyright__ = "Copyright 2013, David Manuel Buitrago Montañez, Trabajo Fin de Máster, Universidad Politécnica de Madrid" __credits__ = ["David Manuel Buitrago Montañez", "Alvaro Javier Buitrago Montañez", "Angela Patricia Giraldo Chaparro", "http://www.freesound.org/" ] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "David Manuel Buitrago Montañez" __email__ = "*****@*****.**" __status__ = "Prototype" init(frequency=44100, size=-16, channels=2, buffer=4096) # inicialindo pygame.mixer DatosIntroducidos = namedtuple("DatosIntroducidos", ["edad", "sexo", "fractil", "tiempo_exposicion", "nivel_exposicion" ]) resultado = None
""" import logging.config import logging.handlers import os.path from sys import stdout from kivy.app import App from kivy.lang import Builder from kivy.properties import BooleanProperty, StringProperty from kivy.resources import resource_add_path import kivy.logger from kivy.uix.boxlayout import BoxLayout # --- フォントファイル等を階層依存無しに名称のみで呼び出せるように以下を実施 # cf https://github.com/kivy/kivy/issues/4458 and watch for updates resource_add_path(os.path.abspath(os.path.join(os.path.dirname(__file__), 'resources', 'SourceHanSansJP'))) # --- logger = None # _init_logging()内で設定される # ### flags ### DEBUG_MODE = True # ############# def _init_logging(): """ログ出力の初期設定を行う""" global logger # === ファイルログ出力設定 ### 他モジュールのインポート *前に* 行う必要がある ### logging.Logger.manager.root = kivy.logger.Logger # cf http://stackoverflow.com/a/36109848/3799649
from kivy.factory import Factory from kivy.logger import Logger from kivy.modules import inspector import math from cplcom.utils import ColorTheme import cplcom.app import itertools import sys import numpy as np from os.path import dirname, join, isdir from collections import deque from skimage import measure resource_add_path(join(dirname(cplcom.app.__file__), 'media')) resource_add_path(join(dirname(cplcom.app.__file__), 'media', 'flat')) class FormulaGraph(Graph): plot_widget = ObjectProperty(None) def __init__(self, **kwargs): self._with_stencilbuffer = False super(FormulaGraph, self).__init__(**kwargs) from kivy.core.window import Window Window.fbind('mouse_pos', self._update_mouse_pos) def _update_mouse_pos(self, instance, pos): plot_widget = self.plot_widget
''' __all__ = ('NavigationDrawer', ) from kivy.animation import Animation from kivy.uix.widget import Widget from kivy.uix.stencilview import StencilView from kivy.metrics import dp from kivy.clock import Clock from kivy.properties import (ObjectProperty, NumericProperty, OptionProperty, BooleanProperty, StringProperty) from kivy.resources import resource_add_path from kivy.lang import Builder import os.path resource_add_path(os.path.dirname(__file__)) Builder.load_string(''' <NavigationDrawer>: size_hint: (1,1) _side_panel: sidepanel _main_panel: mainpanel _join_image: joinimage side_panel_width: max(dp(250), 0.5*self.width) BoxLayout: id: sidepanel y: root.y x: root.x - \ (1-root._anim_progress)* \ root.side_panel_init_offset*root.side_panel_width height: root.height
from kivy.utils import get_color_from_hex from kivy.vector import Vector from kivy.animation import Animation from kivy.uix.anchorlayout import AnchorLayout from kivy.properties import StringProperty, NumericProperty from kivy.resources import resource_add_path from kivy.lang import Builder from kivy.graphics import Color, Rectangle, Ellipse from kivy.clock import Clock # local from penta_color import penta_schemes, penta_colors from penta_common import PentaListContainer resource_add_path(dirname(__file__)) Builder.load_file(join(dirname(__file__), 'pentaminos.kv')) square_background = Image(join(dirname(__file__), 'penta-square.png')) square_shadow = Image(join(dirname(__file__), 'penta-square-shadow.png')) penta_background = Image(join(dirname(__file__), 'penta-background.png')) penta_background.texture.wrap = 'repeat' penta_background_bottom = Image(join(dirname(__file__), 'penta-background-bottom.png')) background = Image(join(dirname(__file__), 'background.png')) background.texture.wrap = 'repeat' SQUARE = 100 SQUARE_MM = 75 SQUARE_M = 5
def main(): data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') if isinstance(data, bytes): data = data.decode(get_fs_encoding()) resource_add_path(data) DesignerApp().run()
def add_path(*paths): for p in reversed(paths): resource_add_path(p)
import pythonpath pythonpath.AddSysPath("../..") # (pwd: test) from cryptikchaos.core.env.configuration import constants from cryptikchaos.core.comm.service import CommService from cryptikchaos.core.device.service import DeviceService from cryptikchaos.core.gui.consolesv import ConsoleScrollView from cryptikchaos.libs.utilities import get_time from kivy.app import App from kivy import Logger from kivy.resources import resource_add_path # Add kivy resource paths resource_add_path(constants.KIVY_RESOURCE_PATH_1) class CryptikChaosTestApp(App): "Test sever application." def build(self): self.test_win = ConsoleScrollView() # Display initial text self.test_win.display_text( """ ========================= CryptikChaos Test_ Server
# This file is part of ELiDE, frontend to LiSE, a framework for life simulation games. # Copyright (c) Zachary Spector, [email protected] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. from kivy.resources import resource_add_path resource_add_path(__path__[0] + '/assets') __all__ = ['board', 'app', 'card', 'dialog', 'game', 'spritebuilder']
#=============================================================================== from kivy.lang import Builder from kivy import resources from kivy.factory import Factory from kivy.core.window import Window from browser import CefBrowser from browser import cefpython from jsdialogs import JSDialogs import os #Add folder to the kivy resource path list #We are able than to just define relative paths regarding from the module directory. resources.resource_add_path(os.path.abspath(os.path.join(os.path.dirname(__file__)))) Builder.load_file(resources.resource_find("popup.kv")) RESOURCE_DIR = "" class PopupBrowser(CefBrowser): def __init__(self, **kwargs): super(PopupBrowser, self).__init__(resources_dir=RESOURCE_DIR, **kwargs) def on_touch_down(self, touch, *kwargs): if not self.collide_point(*touch.pos): return if self.keyboard_mode == "global": self.request_keyboard()