def build(self): root = self.root Config.set ('input','mouse','mouse,disable_multitouch') # disable multi-touch file_name = '../grasp_db/unlabeled_grasps.dat' file_object = open(file_name, 'rb') # binary encoding self.grasps = pickle.load(file_object) shuffle(self.grasps) # randomly sort images self.renderer = Renderer(self.grasps[0]) save_button = SaveButton(labeled_grasps = self.grasps) next_button = NextButton(grasps = self.grasps) help_button = HelpButton() rot_left_button = RotLeftButton(pos_hint = {'x':.58,'y':.15}, size_hint = (.1,.07), text = 'Roll left') rot_right_button = RotRightButton(pos_hint = {'x':.58,'y':.05}, size_hint = (.1,.07), text = 'Roll right') rot_up_button = RotUpButton(pos_hint = {'x':.7,'y':.15}, size_hint = (.1,.07), text = 'Roll up') rot_down_button = RotDownButton(pos_hint = {'x':.7,'y':.05}, size_hint = (.1,.07), text = 'Roll down') zoom_in_button = ZoomInButton(pos_hint = {'x':.82,'y':.15}, size_hint = (.1,.07), text = 'Larger') zoom_out_button = ZoomOutButton(pos_hint = {'x':.82,'y':.05}, size_hint = (.1,.07), text = 'Smaller') compare_image = Image(pos_hint = {'top':.84,'x':.05}, size_hint = (.4, .4), source = 'shoe_compare1.png') compare_image2 = Image(pos_hint = {'top':.44,'x':.05}, size_hint = (.4, .4), source = 'shoe_compare2.png') root.add_widget(self.renderer) root.add_widget(save_button) root.add_widget(next_button) root.add_widget(help_button) root.add_widget(zoom_in_button) root.add_widget(zoom_out_button) root.add_widget(rot_left_button) root.add_widget(rot_right_button) root.add_widget(rot_up_button) root.add_widget(rot_down_button) root.add_widget(compare_image) root.add_widget(compare_image2) return root
def _configure(self): from time import strftime from kivy.config import Config log_dir = Config.get("kivy", "log_dir") log_name = Config.get("kivy", "log_name") _dir = kivy.kivy_home_dir if len(log_dir) and log_dir[0] == "/": _dir = log_dir else: _dir = os.path.join(_dir, log_dir) if not os.path.exists(_dir): os.mkdir(_dir) self.purge_logs(_dir) pattern = log_name.replace("%_", "@@NUMBER@@") pattern = os.path.join(_dir, strftime(pattern)) n = 0 while True: filename = pattern.replace("@@NUMBER@@", str(n)) if not os.path.exists(filename): break n += 1 if n > 10000: # prevent maybe flooding ? raise Exception("Too many logfile, remove them") FileHandler.filename = filename FileHandler.fd = open(filename, "w") Logger.info("Logger: Record log in %s" % filename)
def build(self): Config.set('input','mouse', 'mouse,disable_multitouch') self.title = 'Snarky Screening' self.root = Builder.load_string(kv) self.root.remove_widget(self.root.ids.bottom_layout) self.root.add_widget(self.root.ids.bottom_layout) fc = FileChooserIconView() fc.on_submit = self.handle_selection self.popup = Popup(title='Open file', content=fc) self.root.ids.snarky_opendialog.on_release = self.popup.open self.root.remove_widget(self.root.ids.snarky_divider) self.root.remove_widget(self.root.ids.snarky_opendialog) self.root.ids._context_menu.add_widget(self.root.ids.snarky_divider) self.root.ids._context_menu.add_widget(self.root.ids.snarky_opendialog) if UseLucidaFax: self.root.ids.snarky_chatstream.font_name = 'LucidaFax' self.root.ids.snarky_chatstream.text += """ Welcome to a [b]Snarky Screening[/b]! [i]You[/i] need to kick off [i]auto-scroll[/i] by scrolling this text up so you can see the whole thing. You'll also need to re-do it if you [i]resize[/i] the window.""" if len(argv) > 1: self.root.ids.video.source = argv[1] reactor.listenTCP(8000, EchoFactory(self))
def _encoder_selected(self, encoder_pos): self._encoder_point = encoder_pos Logger.info('Encoder point set at: {}'.format(str(encoder_pos))) Config.set(self.section, 'encoder_point', json.dumps(self._encoder_point)) self._configure_encoder() self._selecting_encoder = False self._enable_all()
def build(self): Config.set('graphics', 'width', '300') Config.set('graphics', 'height', '200') self.title = "Unicode to Zawgyi Converter" self.root = Builder.load_file("gui.kv") return self.root
def build(self): Config.set('graphics', 'width', '200') Config.set('graphics', 'height', '200') self.clock = Clock.schedule_interval(self.update, 1) # define the ClockEvent object self.root = Builder.load_file('clock_demo.kv') return self.root
def _configure_module(self, name): if "module" not in self.mods[name]: try: self.import_module(name) except ImportError: return # convert configuration like: # -m mjpegserver:port=8080,fps=8 # and pass it in context.config token config = dict() args = Config.get("modules", name) if args != "": values = Config.get("modules", name).split(",") for value in values: x = value.split("=", 1) if len(x) == 1: config[x[0]] = True else: config[x[0]] = x[1] self.mods[name]["context"].config = config # call configure if module have one if hasattr(self.mods[name]["module"], "configure"): self.mods[name]["module"].configure(config)
def _configure(self, *largs, **kwargs): from time import strftime from kivy.config import Config log_dir = Config.get('kivy', 'log_dir') log_name = Config.get('kivy', 'log_name') _dir = kivy.kivy_home_dir if log_dir and os.path.isabs(log_dir): _dir = log_dir else: _dir = os.path.join(_dir, log_dir) if not os.path.exists(_dir): os.makedirs(_dir) self.purge_logs(_dir) pattern = log_name.replace('%_', '@@NUMBER@@') pattern = os.path.join(_dir, strftime(pattern)) n = 0 while True: filename = pattern.replace('@@NUMBER@@', str(n)) if not os.path.exists(filename): break n += 1 if n > 10000: # prevent maybe flooding ? raise Exception('Too many logfile, remove them') if FileHandler.filename == filename and FileHandler.fd is not None: return FileHandler.filename = filename if FileHandler.fd is not None: FileHandler.fd.close() FileHandler.fd = open(filename, 'w') Logger.info('Logger: Record log in %s' % filename)
def run(self): q = self._queue.appendleft url = self.url req_body = self.req_body req_headers = self.req_headers or {} if ( Config.has_section('network') and 'useragent' in Config.items('network') ): useragent = Config.get('network', 'useragent') req_headers.setdefault('User-Agent', useragent) try: result, resp = self._fetch_url(url, req_body, req_headers, q) if self.decode: result = self.decode_result(result, resp) except Exception as e: q(('error', None, e)) else: q(('success', resp, result)) # using trigger can result in a missed on_success event self._trigger_result() # clean ourself when the queue is empty while len(self._queue): sleep(.1) self._trigger_result() # ok, authorize the GC to clean us. if self in g_requests: g_requests.remove(self)
def _configure_module(self, name): if 'module' not in self.mods[name]: try: self.import_module(name) except ImportError: return # convert configuration like: # -m mjpegserver:port=8080,fps=8 # and pass it in context.config token config = dict() args = Config.get('modules', name) if args != '': values = Config.get('modules', name).split(',') for value in values: x = value.split('=', 1) if len(x) == 1: config[x[0]] = True else: config[x[0]] = x[1] self.mods[name]['context'].config = config # call configure if module have one if hasattr(self.mods[name]['module'], 'configure'): self.mods[name]['module'].configure(config)
def emit(self, message): # during the startup, store the message in the history if Logger.logfile_activated is None: FileHandler.history += [message] return # startup done, if the logfile is not activated, avoid history. if Logger.logfile_activated is False: FileHandler.history = [] return if FileHandler.fd is None: try: self._configure() from kivy.config import Config Config.add_callback(self._configure, 'kivy', 'log_dir') Config.add_callback(self._configure, 'kivy', 'log_name') except Exception: # deactivate filehandler... FileHandler.fd = False Logger.exception('Error while activating FileHandler logger') return while FileHandler.history: _message = FileHandler.history.pop() self._write_message(_message) self._write_message(message)
def _configure(self): from time import strftime from kivy.config import Config log_dir = Config.get('kivy', 'log_dir') log_name = Config.get('kivy', 'log_name') _dir = kivy.kivy_home_dir if len(log_dir) and log_dir[0] == '/': _dir = log_dir else: _dir = os.path.join(_dir, log_dir) if not os.path.exists(_dir): os.mkdir(_dir) self.purge_logs(_dir) pattern = log_name.replace('%_', '@@NUMBER@@') pattern = os.path.join(_dir, strftime(pattern)) n = 0 while True: filename = pattern.replace('@@NUMBER@@', str(n)) if not os.path.exists(filename): break n += 1 if n > 10000: # prevent maybe flooding ? raise Exception('Too many logfile, remove them') FileHandler.filename = filename FileHandler.fd = open(filename, 'w') Logger.info('Logger: Record log in %s' % filename)
def activate_module(self, name, win): '''Activate a module on a window''' if not name in self.mods: Logger.warning('Modules: Module <%s> not found' % name) return if not 'module' in self.mods[name]: try: self.import_module(name) except ImportError: return module = self.mods[name]['module'] if not self.mods[name]['activated']: # convert configuration like: # -m mjpegserver:port=8080,fps=8 # and pass it in context.config token config = dict() args = Config.get('modules', name) if args != '': values = Config.get('modules', name).split(',') for value in values: x = value.split('=', 1) if len(x) == 1: config[x[0]] = True else: config[x[0]] = x[1] msg = 'Modules: Start <%s> with config %s' % (name, str(config)) Logger.debug(msg) self.mods[name]['context'].config = config module.start(win, self.mods[name]['context'])
def build(self): Config.set('graphics', 'width', '1100') Config.set('graphics', 'height', '800') self.poseidonWidget = Poseidon(app=self) self.root = self.poseidonWidget self.root.jobNameLabel.text = self.config.get('job','jobName') if self.config.get('locks','lockSettings') == 'True': self.config.set('locks','lockSettings','False') self.config.write() if self.config.get('locks','lockPoint') == 'False': self.config.set('locks','lockPoint','True') self.config.write() if self.config.get('locks','measuring') == 'True': self.config.set('locks','measuring','False') self.config.write() if self.config.get('locks','lockSurvey') == 'True': self.config.set('locks','lockSurvey','False') self.config.write() if self.config.get('job','currentPointName') != '': self.config.set('job','currentPointName','') self.config.write()
def create_window(self, *largs): # ensure the mouse is still not up after window creation, otherwise, we # have some weird bugs self.dispatch('on_mouse_up', 0, 0, 'all', []) # force display to show (available only for fullscreen) displayidx = Config.getint('graphics', 'display') if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1: environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx # init some opengl, same as before. self.flags = pygame.HWSURFACE | pygame.OPENGL | \ pygame.DOUBLEBUF # right now, activate resizable window only on linux. # on window / macosx, the opengl context is lost, and we need to # reconstruct everything. Check #168 for a state of the work. if platform() in ('linux', 'macosx', 'win') and \ Config.getint('graphics', 'resizable'): self.flags |= pygame.RESIZABLE try: pygame.display.init() except pygame.error, e: raise CoreCriticalException(e.message)
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # setup ! w, h = self._size resizable = Config.getboolean('graphics', 'resizable') gl_size = self._win.setup_window(pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable) # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) else: w, h = self._size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() # auto add input provider Logger.info('Window: auto add sdl input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')
def build(self): self.set_sizes() self.title = "Floor is Lava" Config.set('graphics', 'resizable', 0) #Config.set('graphics', 'height', str(glo.const.HEIGHT)) #Config.set('graphics', 'width', str(glo.const.WIDTH)) return FilGame()
def build(self): Config.set('graphics', 'width', self.settings.WINDOW_WIDTH) Config.set('graphics', 'height', self.settings.WINDOW_HEIGHT) game = World(self.settings) game.draw() Clock.schedule_interval(game.update, self.settings.UPDATE_SPEED) return game
def __init__(self, **kwargs): Config.set('graphics', 'width', '300') #this has to be done before calling super() Config.set('graphics', 'height', '600') super().__init__(**kwargs) self.orientation = 'vertical' self.resetDataValues() self.startDrawing()
def build(self): # Raspberry 7" resolution test Config.set('graphics', 'width', 800) Config.set('graphics', 'height', 480) game = PongGame() game.serve_ball() Clock.schedule_interval(game.update, 1.0/60.0) return game
def build(self): # Set the window's width and height Config.set('graphics', 'width', '700') Config.set('graphics', 'height', '500') self.title = "Tic Tac Toe" self.root = Builder.load_file('gui.kv') return self.root
def load(self, path, filename, start_height): self.last_directory = path Config.set('internal', 'last_directory', self.last_directory) Config.write() self.dismiss_popup() App.get_running_app().last_print.set("file", filename) self.parent.current = 'printingui' self.parent.printing_ui.print_file(filename, start_height)
def _roi_selected(self, point1, point2, video_size): self._selecting_roi = False try: self.scanner.set_region_of_interest_from_abs_points(point1, point2, video_size) Config.set(self.section, 'roi', json.dumps(self.scanner.roi.get_points())) except: pass self._enable_all()
def __init__(self, camera, **kwargs): super(CameraControls, self).__init__(**kwargs) Config.adddefaultsection('camera') for setting in camera.get_settings(): name = setting['name'] value = setting['value'] control = CameraControl(name, value, camera.set_setting) self.camera_control.add_widget(control, -1)
def build(self): Config.set('input','mouse','mouse,disable_multitouch') box = MyBoxLayout mybox = box() mybox.setfilename() return mybox
def save(self): print('---') print(self._win.win) print('---') Config.set('graphics', 'height', self.size[0]) Config.set('graphics', 'width', self.size[1]) Config.set('graphics', 'top', self.top) Config.set('graphics', 'left', self.left) Config.write()
def on_server_success(self,req,result): if result == 'test1': self.text_pane = 'text1.png' self.image_pane = 'img1.jpg' if result == 'test2': self.text_pane = 'text2.png' self.image_pane = 'img2.jpg' if result == 'go_fullscreen': Config.set('graphics', 'fullscreen', 'auto')
def app_loop_tick(self): """Runs once every frame before any entity code or rendering.""" # Do this once but late from kivy.config import Config Config.set('graphics', 'show_cursor', 0) if Game.first_registered_entity: from kivy import platform as kivy_platform if kivy_platform == 'android': self.hide_android_soft_keys()
def build(self): global game #FIXME: THIS IS MOST CERTAINLY NOT THE WAY TO DO IT, BUT HOW ELSE ?!?!? game = Game() self.config = MainConfig() Config.set('graphics', 'width', self.config.windowWidth) #this has to be done before calling super() Config.set('graphics', 'height', self.config.windowHeight) self.screen = Screen(game=game) game.screen = self.screen return self.screen
def build(self): self.icon = 'cropped_lumpy2.png' Config.set("input", "mouse", "mouse, disable_multitouch") root = RootHome() self.title = 'hello' self.store = JsonStore('projectlist.json') from kivy.core.window import Window # Window.borderless = True return root
mkdir(kivy_home_dir) if not exists(kivy_usermodules_dir): mkdir(kivy_usermodules_dir) if not exists(kivy_userexts_dir): mkdir(kivy_userexts_dir) if not exists(icon_dir): try: shutil.copytree(join(kivy_data_dir, 'logo'), icon_dir) except: Logger.exception('Error when copying logo directory') # configuration from kivy.config import Config # Set level of logger level = LOG_LEVELS.get(Config.get('kivy', 'log_level')) Logger.setLevel(level=level) # Can be overrided in command line if 'KIVY_UNITTEST' not in environ and 'KIVY_PACKAGING' not in environ: # save sys argv, otherwize, gstreamer use it and display help.. sys_argv = sys.argv sys.argv = sys.argv[:1] try: opts, args = getopt(sys_argv[1:], 'hp:fkawFem:sr:dc:', [ 'help', 'fullscreen', 'windowed', 'fps', 'event', 'module=', 'save', 'fake-fullscreen', 'auto-fullscreen', 'display=', 'size=', 'rotate=', 'config=', 'debug', 'dpi=' ])
from threading import Thread from random import randint from kivy.app import App from kivy.config import Config from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.popup import Popup from kivy.clock import Clock from kivy.graphics import Rectangle from motionize.ball_detection import run Config.set('graphics', 'width', '1024') Config.set('graphics', 'height', '768') miner_position = Queue() class MainScreen(FloatLayout): def __init__(self): open_cv = Thread(target=self.open_cv_worker, daemon=True) open_cv.start() super(MainScreen, self).__init__() self.points = 0 self.score = Button(size_hint=(None, None), pos=(10, 10), size=(150, 40)) self.score.text = 'Your Score is: {}'.format(self.points)
import wiringpi import kivy from kivy.config import Config kivy.require('1.9.1') Config.set('kivy', 'exit_on_escape', 1) Config.set('graphics', 'fullscreen', 0) Config.set('graphics', 'width', '1920') Config.set('graphics', 'height', '1080') Config.write() from kivy.app import App from kivy.uix.label import Label from kivy.uix.scatter import Scatter from kivy.properties import StringProperty from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window class Picture(Scatter): source = StringProperty(None) class CamelRaceApp(App): pinsToSense = [[8, 9, 7], [0, 2, 3], [12, 13, 14]] def __init__(self, **kwargs): super(CamelRaceApp, self).__init__(**kwargs) self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
def __init__(self): dist = Config.getint('postproc', 'triple_tap_distance') self.triple_tap_distance = dist / 1000.0 time = Config.getint('postproc', 'triple_tap_time') self.triple_tap_time = time / 1000.0 self.touches = {}
from kivy.app import App from kivy.config import Config from kivy.core.window import Window from kivy import clock from kivy import properties from xls2expressionmap import convert WINDOW_W = 400 WINDOW_H = 480 Window.minimum_width = WINDOW_W Window.minimum_height = WINDOW_H Window.size = (WINDOW_W, WINDOW_H) Config.set("kivy", "log_enable", "0") """ GUI Main window class """ class ConvertGUIApp(App): """ ctor """ def __init__(self, **kvargs): super(ConvertGUIApp, self).__init__(**kvargs) self.title = "XLS2ExpressionMap GUI" self.message_label = properties.ObjectProperty(None) self.converter = None self.finished = False
def runTouchApp(widget=None, slave=False): '''Static main function that starts the application loop. You got some magic things, if you are using argument like this : :Parameters: `<empty>` To make dispatching work, you need at least one input listener. If not, application will leave. (MTWindow act as an input listener) `widget` If you pass only a widget, a MTWindow will be created, and your widget will be added on the window as the root widget. `slave` No event dispatching are done. This will be your job. `widget + slave` No event dispatching are done. This will be your job, but we are trying to get the window (must be created by you before), and add the widget on it. Very usefull for embedding Kivy in another toolkit. (like Qt, check kivy-designed) ''' from kivy.input import MotionEventFactory, kivy_postproc_modules # Ok, we got one widget, and we are not in slave mode # so, user don't create the window, let's create it for him ! if widget: EventLoop.ensure_window() # Instance all configured input for key, value in Config.items('input'): Logger.debug('Base: Create provider from %s' % (str(value))) # split value args = str(value).split(',', 1) if len(args) == 1: args.append('') provider_id, args = args provider = MotionEventFactory.get(provider_id) if provider is None: Logger.warning('Base: Unknown <%s> provider' % str(provider_id)) continue # create provider p = provider(key, args) if p: EventLoop.add_input_provider(p) # add postproc modules for mod in kivy_postproc_modules.values(): EventLoop.add_postproc_module(mod) # add main widget if widget and EventLoop.window: EventLoop.window.add_widget(widget) # start event loop Logger.info('Base: Start application main loop') EventLoop.start() # we are in a slave mode, don't do dispatching. if slave: return # in non-slave mode, they are 2 issues # # 1. if user created a window, call the mainloop from window. # This is due to glut, it need to be called with # glutMainLoop(). Only FreeGLUT got a gluMainLoopEvent(). # So, we are executing the dispatching function inside # a redisplay event. # # 2. if no window is created, we are dispatching event lopp # ourself (previous behavior.) # try: if EventLoop.window is None: _run_mainloop() else: EventLoop.window.mainloop() finally: stopTouchApp()
else: self.new_operation_obj = self.operation_obj.text.replace("x", "*") self.result_obj.text = str(round(eval(self.new_operation_obj), 10)) for child in self.ids.grid.children: if child.text == ".": child.color = (236 / 255, 137 / 255, 116 / 255, 1) child.text = "c" class Calculator(App): def supprim(self, wid, *args): l = list(wid.text) if l: l.pop() ch = "".join(l) wid.text = ch pass def build(self): return MainWidget() if __name__ == "__main__": from kivy.config import Config Config.set("graphics", "width", 380) Config.set("graphics", "height", 650) Calculator().run()
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # setup ! w, h = self.system_size resizable = Config.getboolean('graphics', 'resizable') state = (Config.get('graphics', 'window_state') if self._is_desktop else None) self.system_size = _size = self._win.setup_window( pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable, state) # calculate density sz = self._win._get_gl_size()[0] self._density = density = sz / _size[0] if self._is_desktop and self.size[0] != _size[0]: self.dpi = density * 96. # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) else: w, h = self.system_size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() if self.initialized: return # auto add input provider Logger.info('Window: auto add sdl2 input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')
import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import Screen from kivy.uix.scrollview import ScrollView from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.button import ButtonBehavior from kivy.uix.widget import Widget from kivy.properties import ObjectProperty from kivy.config import Config Config.set('graphics', 'width', '350') Config.set('graphics', 'height', '650') class MyGrid(Widget): name = ObjectProperty(None) email = ObjectProperty(None) class GenreApp(App): def build(self): return MyGrid() if __name__ == "__main__": GenreApp().run()
def _mainloop(self): EventLoop.idle() while True: event = self._win.poll() if event is False: break if event is None: continue action, args = event[0], event[1:] if action == 'quit': EventLoop.quit = True self.close() break elif action in ('fingermotion', 'fingerdown', 'fingerup'): # for finger, pass the raw event to SDL motion event provider # XXX this is problematic. On OSX, it generates touches with 0, # 0 coordinates, at the same times as mouse. But it works. # We have a conflict of using either the mouse or the finger. # Right now, we have no mechanism that we could use to know # which is the preferred one for the application. if platform == "ios": SDL2MotionEventProvider.q.appendleft(event) pass elif action == 'mousemotion': x, y = args x, y = self._fix_mouse_pos(x, y) self._mouse_x = x self._mouse_y = y # don't dispatch motion if no button are pressed if len(self._mouse_buttons_down) == 0: continue self._mouse_meta = self.modifiers self.dispatch('on_mouse_move', x, y, self.modifiers) elif action in ('mousebuttondown', 'mousebuttonup'): x, y, button = args x, y = self._fix_mouse_pos(x, y) btn = 'left' if button == 3: btn = 'right' elif button == 2: btn = 'middle' eventname = 'on_mouse_down' self._mouse_buttons_down.add(button) if action == 'mousebuttonup': eventname = 'on_mouse_up' self._mouse_buttons_down.remove(button) self._mouse_x = x self._mouse_y = y self.dispatch(eventname, x, y, btn, self.modifiers) elif action.startswith('mousewheel'): self._update_modifiers() x, y, button = args btn = 'scrolldown' if action.endswith('up'): btn = 'scrollup' elif action.endswith('right'): btn = 'scrollright' elif action.endswith('left'): btn = 'scrollleft' self._mouse_meta = self.modifiers self._mouse_btn = btn #times = x if y == 0 else y #times = min(abs(times), 100) #for k in range(times): self._mouse_down = True self.dispatch('on_mouse_down', self._mouse_x, self._mouse_y, btn, self.modifiers) self._mouse_down = False self.dispatch('on_mouse_up', self._mouse_x, self._mouse_y, btn, self.modifiers) elif action == 'dropfile': dropfile = args self.dispatch('on_dropfile', dropfile[0]) # video resize elif action == 'windowresized': self._size = self._win.window_size # don't use trigger here, we want to delay the resize event cb = self._do_resize Clock.unschedule(cb) Clock.schedule_once(cb, .1) elif action == 'windowresized': self.canvas.ask_update() elif action == 'windowrestored': self.canvas.ask_update() elif action == 'windowexposed': self.canvas.ask_update() elif action == 'windowminimized': if Config.getboolean('kivy', 'pause_on_minimize'): self.do_pause() elif action == 'joyaxismotion': stickid, axisid, value = args self.dispatch('on_joy_axis', stickid, axisid, value) elif action == 'joyhatmotion': stickid, hatid, value = args self.dispatch('on_joy_hat', stickid, hatid, value) elif action == 'joyballmotion': stickid, ballid, xrel, yrel = args self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel) elif action == 'joybuttondown': stickid, buttonid = args self.dispatch('on_joy_button_down', stickid, buttonid) elif action == 'joybuttonup': stickid, buttonid = args self.dispatch('on_joy_button_up', stickid, buttonid) elif action in ('keydown', 'keyup'): mod, key, scancode, kstr = args key_swap = { SDLK_LEFT: 276, SDLK_RIGHT: 275, SDLK_UP: 273, SDLK_DOWN: 274, SDLK_HOME: 278, SDLK_END: 279, SDLK_PAGEDOWN: 281, SDLK_PAGEUP: 280, SDLK_SHIFTR: 303, SDLK_SHIFTL: 304, SDLK_SUPER: 309, SDLK_LCTRL: 305, SDLK_RCTRL: 306, SDLK_LALT: 308, SDLK_RALT: 307, SDLK_CAPS: 301, SDLK_INSERT: 277, SDLK_F1: 282, SDLK_F2: 283, SDLK_F3: 284, SDLK_F4: 285, SDLK_F5: 286, SDLK_F6: 287, SDLK_F7: 288, SDLK_F8: 289, SDLK_F9: 290, SDLK_F10: 291, SDLK_F11: 292, SDLK_F12: 293, SDLK_F13: 294, SDLK_F14: 295, SDLK_F15: 296, SDLK_KEYPADNUM: 300, SDLK_KP_DEVIDE: 267, SDLK_KP_MULTIPLY: 268, SDLK_KP_MINUS: 269, SDLK_KP_PLUS: 270, SDLK_KP_ENTER: 271, SDLK_KP_DOT: 266, SDLK_KP_0: 256, SDLK_KP_1: 257, SDLK_KP_2: 258, SDLK_KP_3: 259, SDLK_KP_4: 260, SDLK_KP_5: 261, SDLK_KP_6: 262, SDLK_KP_7: 263, SDLK_KP_8: 264, SDLK_KP_9: 265 } if platform == 'ios': # XXX ios keyboard suck, when backspace is hit, the delete # keycode is sent. fix it. key_swap[127] = 8 # back try: key = key_swap[key] except KeyError: pass if action == 'keydown': self._update_modifiers(mod, key) else: self._update_modifiers(mod) # ignore the key, it # has been released # if mod in self._meta_keys: if (key not in self._modifiers and key not in self.command_keys.keys()): try: kstr = unichr(key) except ValueError: pass #if 'shift' in self._modifiers and key\ # not in self.command_keys.keys(): # return if action == 'keyup': self.dispatch('on_key_up', key, scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', key, scancode, kstr, self.modifiers): continue self.dispatch('on_keyboard', key, scancode, kstr, self.modifiers) elif action == 'textinput': text = args[0] self.dispatch('on_textinput', text) # XXX on IOS, keydown/up don't send unicode anymore. # With latest sdl, the text is sent over textinput # Right now, redo keydown/up, but we need to seperate both call # too. (and adapt on_key_* API.) #self.dispatch() #self.dispatch('on_key_down', key, None, args[0], # self.modifiers) #self.dispatch('on_keyboard', None, None, args[0], # self.modifiers) #self.dispatch('on_key_up', key, None, args[0], # self.modifiers) # unhandled event ! else: Logger.trace('WindowSDL: Unhandled event %s' % str(event))
# File name: race.py from kivy.config import Config Config.set('graphics', 'width', '1200') Config.set('graphics', 'height', '675') Config.set('graphics', 'resizable', '0') import kivy kivy.require('1.11.1') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.relativelayout import RelativeLayout from kivy.properties import NumericProperty, StringProperty from kivy.lang import Builder # Besides Screen we have to import ScreenManager. from kivy.uix.screenmanager import Screen, ScreenManager Builder.load_file('widgets.kv') # Load the Bets and Results kv files. Builder.load_file('bets.kv') Builder.load_file('results.kv') # Here's the screen manager class. class RaceScreenManager(ScreenManager): pass class SlugStats(BoxLayout):
# Kivy版本号 kivy.require('1.11.1') # ======================================== 查找文件 ======================================== # 查找文件 from common.util.yushirui_find_file_or_dir import yushirui_find_file_or_dir # ======================================== 指定配置文件 ======================================== # 查找配置文件 config_path = yushirui_find_file_or_dir('config/kivy_config.ini') # 读取配置,支持中文 from kivy.config import Config # 读取配置文件 Config.read(config_path) # ======================================== 设置字体 ======================================== # 查找字体文件 font_path = yushirui_find_file_or_dir('font/simkai.ttf') # 设置字体 from kivy.core.text import LabelBase # 注册字体 LabelBase.register('.', font_path) # ======================================== 设置资源目录 ======================================== # 查找资源目录 resource_dir_path = yushirui_find_file_or_dir('res') # 设置资源目录 from kivy.resources import resource_add_path
from kivy.app import App from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.config import Config from kivy.uix.boxlayout import BoxLayout import random Config.set('graphics', 'resizable', '0') Config.set('graphics', 'width', '400') Config.set('graphics', 'height', '650') def calc3(a, b, c, d, y): def fit(x): global result delta = [ abs(a * x[i][0] + b * x[i][1] + c * x[i][2] + d * x[i][3] - y) for i in range(len(x)) ] k = 0 for i in range(len(delta)): try: k += 1 / delta[i] except: result = x[i] return 0 return [round((1 / n) / k * 100) for n in delta] def nextpopulation(p, f):
if __name__ == '__main__': root = FloatLayout() # create a button to release everything def release_all_keyboard(*l): Window.release_all_keyboards() btn = Button(text='Release\nall\nkeyboards', size_hint=(None, None), halign='center') btn.bind(on_release=release_all_keyboard) root.add_widget(btn) # show current configuration lbl = 'Configuration keyboard_mode is %r, keyboard_layout is %r' % ( Config.get('kivy', 'keyboard_mode'), Config.get('kivy', 'keyboard_layout')) label = Label(text=lbl, size_hint_y=None, height=50, pos_hint={'top': 1}) root.add_widget(label) s = Scatter(size_hint=(None, None), pos=(300, 300)) s.add_widget(TextInput(size_hint=(None, None), size=(100, 50))) root.add_widget(s) s = Scatter(size_hint=(None, None), pos=(400, 300), rotation=45) s.add_widget(TextInput(size_hint=(None, None), size=(100, 50))) root.add_widget(s) runTouchApp(root)
from kivy.config import Config Config.set('input', 'mouse', 'mouse,disable_multitouch') from kivy.app import App from ia_scribe.uix.widgets.marc.MARC import MARCPopup class MarcWidgetTestApp(App): def build(self): return MARCPopup() def on_start(self): self.root_window.size = (1200, 720) if __name__ == '__main__': MarcWidgetTestApp().run()
#BoxLayout allows us to use this layout from kivy.uix.boxlayout import BoxLayout #Random allows us to use random choice and other random triggers import random #Allows us to trigger window size or make the app full screen from kivy.core.window import Window #Setting the size of the window that opens Window.fullscreen = 'auto' #Deciding if user can resize the window or not from kivy.config import Config Config.set('graphics', 'resizable', True) #Importing a CSV import csv class Idiom_Generation(BoxLayout): #Male Name Generation def Idiom_Gen(self, *args): Idiom = [] with open(r'Idioms.csv', encoding="utf8") as f: reader = csv.reader(f, skipinitialspace=True) for col in reader: ##This verifies it doesn't get a blank or the column title and if it does it continues until it doesn't get a blank if not col[1] or col[1] == "Field": continue else:
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with IcarusTouch. If not, see <http://www.gnu.org/licenses/>. ''' import pygame.midi import kivy kivy.require('1.7.0') from kivy.app import App from kivy.config import Config # for making screenshots with F12: Config.set('modules', 'keybinding', '') Config.set('modules', 'inspector', '') from kivy.base import EventLoop from kivy.animation import Animation from kivy.properties import ObjectProperty, NumericProperty, StringProperty from kivy.uix.image import Image from kivy.uix.widget import Widget from settingfile import SettingFile from settingmidi import SettingMIDI from keyboard import Keyboard from mysettingspanel import MySettingsPanel ''' #################################### ##
# first, logging level lower import os os.environ["KCFG_KIVY_LOG_LEVEL"] = os.environ.get("KCFG_KIVY_LOG_LEVEL", "warning") os.environ['KIVY_AUDIO'] = "sdl2" # force working audio # next, icon from katrain.core.utils import find_package_resource # isort:skip from kivy.config import Config # isort:skip ICON = find_package_resource("katrain/img/icon.ico") # isort:skip # find icon Config.set("kivy", "window_icon", ICON) # isort:skip # set icon # finally, window size from kivy.metrics import dp WINDOW_X, WINDOW_Y = 1300, 1000 try: from screeninfo import get_monitors scale = 1.0 for m in get_monitors(): scale = min(scale, (m.height - 100) / WINDOW_Y, (m.width - 100) / WINDOW_X) WINDOW_SCALE_FAC = max(0.4, scale) except Exception as e: print("Exception while getting screen resolution", e) WINDOW_SCALE_FAC = 1 Config.set("graphics", "width", int(WINDOW_SCALE_FAC * WINDOW_X)) Config.set("graphics", "height", int(WINDOW_SCALE_FAC * WINDOW_Y))
from db.entidades import questions from db.repositorios import users_repositorio import configparser Builder.load_file('main.kv') try: import crypt # Unix except: import pcrypt as crypt # Windows config = configparser.ConfigParser() config.read('config.ini') Config.set('graphics', 'fullscreen', config['DISPLAY']['fullscreen']) Config.set('graphics', 'width', config['DISPLAY']['width']) Config.set('graphics', 'height', config['DISPLAY']['height']) Config.set('kivy', 'window_icon', 'img/logo.png') record = 0 class User(Screen): mudar_nick = 1 mudar_pass = 1 def nickMudar(self): global mudar_nick if self.mudar_nick == 1: self.mudar_nick = 0
img = 0 annotations = [] mode = 0 #0 = draw, 1 = erase all_annotations = {} try: a = np.load("annotations/annotations.npy") all_annotations = a[()] except Exception: pass from kivy.config import Config Config.set('graphics', 'width', int(img_dim[1] * 1.25)) Config.set('graphics', 'height', int(img_dim[0])) Config.set('graphics', 'resizable', 0) Builder.load_string(''' <PaintWidget> id: 'PaintWidget' size_hint_x: 0.8 size_y:1 Image: source: root.parent.parent.img_src opacity: 1.0 <RootWidget> BoxLayout: orientation: 'horizontal' PaintWidget:
from kivy.config import Config Config.set('modules', 'inspector', '') # 右クリックで赤丸がでるのを抑止する Config.set('input', 'mouse', 'mouse,multitouch_on_demand') from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import StringProperty, ObjectProperty import numpy as np from kivy.graphics.texture import Texture from event import ClickEvent from event import ImageClickEvent from event import ClickEventCode from data import CollisionManager def create_texture(): width = 800 height = 400 color = (255,0,0) img = np.full((height,width,3),color,dtype=np.uint8) img[:,int(width/2):] = (0,255,0) texture = Texture.create(size=(img.shape[1], img.shape[0]), colorfmt='bgr', bufferfmt='ubyte') # BGRモードで用意,ubyteはデフォルト引数なので指定なくてもよい texture.blit_buffer(img.tostring(),colorfmt='bgr', bufferfmt='ubyte') # ★ここもここもBGRで指定しないとRGBになって色の表示がおかしくなる texture.flip_vertical() # 画像を上下反転する return texture class ImageWidget(Widget): image = ObjectProperty(None) image_texture = ObjectProperty(None) clickevent = None
import matplotlib.pyplot as plt # Importing the Kivy packages from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.graphics import Color, Ellipse, Line from kivy.config import Config from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.clock import Clock from ai import DQN Config.set( 'input', 'mouse', 'mouse, multitouch_on_demand' ) # Adding this line if we don't want the right click to put a red point # Introducing last_signal1, last_signal2 and last_signal3 to let the brain know if it's getting further or closer to the obstacle. last_signal1 = 0 last_signal2 = 0 last_signal3 = 0 last_x = 0 last_y = 0 GOAL = 'airport' BOUNDARY = 20 # Getting our AI, which we call "dqn", and that contains our neural network that represents our Q-function dqn = DQN(8, 3, 0.9) # 5 signals, 3 actions, gamma = 0.9
def set_mode(self, mode): """ Sets the keyboard mode to the one specified """ Config.set("kivy", "keyboard_mode", mode.replace("'", "")) Config.write() self.center_label.text = "Please restart the application for this\n" \ "setting to take effect."
if c.text == 'Waiting data...': c.text = msg.strip() + '\n' else: c.text += msg.strip() + '\n' return msg def new_client(self, label_name): """On connection generate a new tabbed panel. """ LogServerApp.s.generate_panel_tab(label_name) def client_leave(self, tab_name): """On client leave, remove the corresponding panel. """ c = None for item in LogServerApp.s.panel.tab_list: # print "text ", item.text if item.text == tab_name: c = item break if c != None: LogServerApp.s.panel.remove_widget(c) if __name__ == '__main__': Config.set('graphics', 'fullscreen', '0') LogServerApp().run()
import kivy kivy.require('1.10.0') from kivy.app import App from kivy.config import Config Config.set('graphics', 'width', '200') Config.set('graphics', 'height', '100') class WindowWithLabelApp(App): pass if __name__ == '__main__': WindowWithLabelApp().run()
import os import time import kivy from kivy.config import Config Config.set('kivy', 'keyboard_mode', 'systemandmulti') from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.clock import Clock from kivy.graphics import Color, Rectangle from kivy.uix.image import AsyncImage from kivy.lang import Builder from kivy.uix.image import Image from kivy.uix.popup import Popup from kivy.uix.vkeyboard import VKeyboard from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.lang import builder from kivy.uix.screenmanager import ScreenManager, Screen Window.fullscreen = True class Main_Menu(Screen): cycle_count = None def __init__(self, **kwargs): super().__init__(**kwargs)
# from kivy.logger import Logger # from kivy.uix.togglebutton import ToggleButton # from kivy.uix.behaviors.focus import FocusBehavior # from kivy.uix.boxlayout import BoxLayout # from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition # from kivy.properties import ObjectProperty, ConfigParserProperty # import io # from kivy.uix.image import Image # from kivy.core.image import Image as CoreImage # from functools import partial # import os # Hide the cursor Config.set("graphics", "show_cursor", 0) # Allow virtual Keyboard for Preferences Config.set('kivy', 'keyboard_mode', 'systemandmulti') # Change the transition effect between screens screen_manager = ScreenManager(transition=FadeTransition()) # FOLDER_PHOTOS = "DCIM" # # --------- Refacto # import pihqcam.device.CameraHelper # import pihqcam.uix.image.MemoryImage import pihqcam.uix.screen.quit as quit_screen import pihqcam.uix.screen.shutdown as shutdown_screen import pihqcam.uix.screen.main as main_screen
j.obstacle, j.way = False, True elif j.source: j.source, j.way = False, True elif j.target: j.target, j.way = False, True elif j.path: j.path, j.way = False, True obstacle_list.clear() #------------------------------------------------------------------------------------------------------------------------------------- # -------------------------------------------- GUI -------------------------------------------------- # setting the size of the window Config.set('graphics', 'resizable', False) Config.set('graphics', 'width', 500) Config.set('graphics', 'height', 550) class Interface(BoxLayout): size_factor = 9.5 pos_factor = 10 grid_size = 50 def __init__(self, **kwargs): super(Interface, self).__init__(**kwargs) self.orientation = 'vertical' self.wid = Widget()
# Importing the Kivy packages from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.graphics import Color, Ellipse, Line from kivy.config import Config from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.clock import Clock # Importing the Dqn object from our AI in ai.py from ai import Dqn # Adding this line if we don't want the right click to put a red point Config.set('input', 'mouse', 'mouse,multitouch_on_demand') # Introducing last_x and last_y, used to keep the last point in memory when we draw the sand on the map last_x = 0 last_y = 0 n_points = 0 length = 0 # Getting our AI, which we call "brain", and that contains our neural network that represents our Q-function brain = Dqn(5, 3, 0.9) action2rotation = [0, 20, -20] last_reward = 0 scores = [] totalscore = [] # Initializing the map
additional processes without entering a recursion loop. """ # Icon made by https://www.flaticon.com/authors/freepik from # https://www.flaticon.com/ if __name__ == '__main__': import os if os.environ.get('COVERAGE_PROCESS_START', None) == '1': import coverage coverage.process_startup() import multiprocessing multiprocessing.freeze_support() from kivy.config import Config Config.set('graphics', 'vsync', '1') from ceed.main import run_app app = run_app() from kivy.core.window import Window for child in Window.children[:]: Window.remove_widget(child) from kivy.logger import LoggerHistory LoggerHistory.clear_history() import gc import weakref app = weakref.ref(app) gc.collect() import logging