Best Python code snippet using pyatom_python
Region.py
Source:Region.py  
1# Copyright 2010-2013, Sikuli.org2# Released under the MIT License.3# modified RaiMan 20134from org.sikuli.basics import Debug5from org.sikuli.script import Region as JRegion6from org.sikuli.script import ObserverCallBack7from org.sikuli.script.Constants import *8import sys9import inspect10DEBUG=False11class Region(JRegion):12    # support for with:13    # override all global sikuli functions by this region's methods.14    def __enter__(self):15        exclude_list = [ 'ROI' ]16        if DEBUG: print "with: entering *****", self17        self._global_funcs = {}18        dict = sys.modules['__main__'].__dict__19        for name in dir(self):20            if name in exclude_list: continue21            try:22                if not inspect.ismethod(getattr(self,name)):23                    continue24            except:25                continue26            if dict.has_key(name):27                self._global_funcs[name] = dict[name]28                if DEBUG and name == 'checkWith': print "with: save %s ( %s )"%(name, str(dict[name])[1:])29                dict[name] = eval("self."+name)30                if DEBUG and name == 'checkWith': print "with: is now: %s"%(str(dict[name])[1:])31        return self32    def __exit__(self, type, value, traceback):33        if DEBUG: print "with: exiting ****", self34        dict = sys.modules['__main__'].__dict__35        for name in self._global_funcs.keys():36            dict[name] = self._global_funcs[name]37            if DEBUG and name == 'checkWith':38                print "with restore: %s"%(str(dict[name])[1:])39        self._global_funcs = None40#######################################################################41#---- SIKULI  PUBLIC  API42#######################################################################43# Python wait() needs to be here because Java Object has a final method: wait(long timeout).44# If we want to let Sikuli users use wait(int/long timeout), we need this Python method.45    def wait(self, target, timeout=None):46        if isinstance(target, int) or isinstance(target, long):47            target = float(target)48        if timeout == None:49            return JRegion.wait(self, target)50        else:51            return JRegion.wait(self, target, timeout)52# the new Region.text() feature (Tesseract 3) returns utf853    def text(self):54        return JRegion.text(self).encode("utf8")55# observe(): Special setup for Jython56# assures, that in any case the same region object is used57    def onAppear(self, target, handler = None):58        if not handler:59            return self.onAppearJ(target, None)60        class AnonyObserver(ObserverCallBack):61            def appeared(self, event):62                handler(event)63        return self.onAppearJ(target, AnonyObserver())64    def onVanish(self, target, handler = None):65        if not handler:66            return self.onVanishJ(target, None)67        class AnonyObserver(ObserverCallBack):68            def vanished(self, event):69                handler(event)70        return self.onVanishJ(target, AnonyObserver())71    def onChange(self, arg1=0, arg2=None):72        if isinstance(arg1, int):73            min_size = arg174            handler = arg275        else:76            if (arg2 != None):77                raise Exception("onChange: Invalid parameters set")78            min_size = 079            handler = arg180        if not handler:81            return self.onChangeJ(min_size, None)82        class AnonyObserver(ObserverCallBack):83            def changed(self, event):84                handler(event)85        return self.onChangeJ(min_size, AnonyObserver())86    def observe(self, time=FOREVER, background=False):...view.py
Source:view.py  
1import tkinter as tk2from typing import List, Dict, Callable, Any, Tuple, Iterator, Type3from .event import Event4from .window import BaseWindow5LoopHookCallback = Callable[[], None]6ObserverCallback = Callable[[Any], None]7class ViewError(Exception):8    pass9class View:10    """11    View is a concrete class that provides a layer between tkinter and a controller class. View owns the tk root window12    and starts its mainloop.13    Custom window classes are passed to View to be created and then shown/hidden as directed.14    Windows can trigger Events through View that will be handled by a controller class. The controller class hooks into15    the program loop through add_loop_hook. Windows also add observers to View which are triggered when a controller16    updates those values.17    """18    def __init__(self) -> None:19        self._tk_root = tk.Tk()20        self._tk_root.overrideredirect(1)21        self._tk_root.withdraw()22        self._observers: Dict[str, ObserverCallback] = {}23        self._events: List[Event] = []24        self._windows: Dict[str, tk.Toplevel] = {}25        self._loop_hooks: List[Tuple[LoopHookCallback, int]] = []26    def start_mainloop(self) -> None:27        for func, interval in self._loop_hooks:28            self._tk_root.after(interval, lambda: self._run_loop_hook(func, interval))29        self._tk_root.mainloop()30    def add_loop_hook(self, func: LoopHookCallback, interval: int) -> None:31        self._loop_hooks.append((func, interval))32    def _run_loop_hook(self, func: LoopHookCallback, interval: int) -> None:33        func()34        self._tk_root.after(interval, lambda: self._run_loop_hook(func, interval))35    def add_observer(self, name: str, callback: ObserverCallback) -> None:36        self._observers[name] = callback37    def set_value(self, name: str, value: Any) -> None:38        self._observers[name](value)39    def add_event(self, event: Event) -> None:40        self._events.append(event)41    def get_events(self, n: int = 0) -> Iterator[Event]:42        """43        Yields the next n events. If n == 0, yields all events.44        """45        if n == 0:46            n = len(self._events)47        for i in range(n):48            if len(self._events) > 0:49                yield self._events.pop(0)50            else:51                yield None52    def add_window(self, window_name: str, window_cls: Type[BaseWindow], *args, **kwargs) -> None:53        if window_name not in self._windows:54            new_window = tk.Toplevel(self._tk_root)55            new_window.withdraw()56            window_cls(self, new_window, *args, **kwargs)57            self._windows[window_name] = new_window58        else:59            raise ViewError('Window name already exists.')60    def show_window(self, window_name: str) -> None:61        if window_name in self._windows:62            self._windows[window_name].deiconify()63    def hide_window(self, window_name: str) -> None:64        if window_name in self._windows:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
