def grid(self, **kw): kw = StaticUtils.mergeJson(kw, self._smartWidgetGrid, True) if self.__frame: self.__frame.columnconfigure(1, weight=1) self.__frame.grid(sticky=W + E, **kw) self.__caption.grid(column=0, row=0, sticky=W) self.__valueLabel.grid(column=1, padx=(20, 0), row=0, sticky=E) self.__scale.grid(column=0, columnspan=2, pady=(20, 0), row=1, sticky=W + E) else: padxRight = kw["padx"][1] # TODO It can also be a scalar! kw["padx"][1] = 0 # TODO It can also be a scalar! self.__caption.grid(sticky=E, **kw) kw["column"] += 1 kw["padx"] = [20, 0] self.__valueLabel.grid(sticky=W + E, **kw) kw["column"] += 1 kw["padx"][1] = padxRight self.__scale.grid(**kw)
def createChain(size=None, signed=None, value=None, fields=None): chain = fields if chain: for i, field in enumerate(chain): if i: field.__offset = chain[i - 1].nextOffset else: chain = [] args = (size, signed, value) def count(): for x in args: if StaticUtils.isIterable(x): return len(x) raise ValueError() for index in range(count()): params = tuple(v[index] if StaticUtils.isIterable(v) else v for v in args) chain.append( Field(params[0], previousField=chain[index - 1] if index else None, signed=params[1], value=params[2])) return chain
def _getValueStorage(self): if not self._smartWidgetName: raise ValueError("Can't serialize nameless widgets") storage = self._smartWidgetStorage for domain in self.__valueDomains: storage = StaticUtils.setIfAbsentAndGet( storage, f"{'.'.join(domain)}={str(self._topLevelContainer.getSmartWidget(*domain).getValue())}", dict()) for name in (*self._namePrefix, self._smartWidgetName): storage = StaticUtils.setIfAbsentAndGet(storage, name, dict()) return storage
def __init__(self, master, **kw): self.__multiplyValue = kw.pop("multiplyValue", False) twoRows = kw.pop("twoRows", False) kw["columns"] = 1 if twoRows else 3 kw["rows"] = 1 valueIsNone = "value" not in kw SmartWidget._setVariable(kw, "IntVar") self.__frame = Frame(master) if twoRows else None super().__init__(master, **kw) if self.__frame: master = self.__frame # = Step = # self.__step = kw.get("step", 1) # = Caption = # self.__caption = Label(master, text=kw["text"]) self.__valueLabel = Label(master, anchor=E) # = Scale = # self.getRawValue().trace_add("write", self.onChanged) storage = self._getValueStorage() for index, key in enumerate(("from_", "to")): if key in storage: kw["range"][index] = storage[key] self.getRawValue().set( StaticUtils.setIfAbsentAndGet( storage, "value", (kw["range"][0] if valueIsNone else self.getValue()) // self.__step)) from_, to = tuple(v // self.__step for v in kw["range"]) self.__scale = Scale(master, from_=from_, length=400, to=to, variable=self.getRawValue()) if "state" in kw: self.__scale["state"] = kw["state"] self.__setValueWidth()
def load(self, notebook, wholeConfig, wholeStorage, package=None, **baseTabKw): self.__notebook = notebook self.__wholeStorage = wholeStorage notebook.bind("<<NotebookTabChanged>>", self._onTabChanged) explicitAddition = wholeConfig.get("explicitAddition", False) selectedIndex = wholeStorage.get("selectedIndex", 0) tabsDir = wholeConfig["tabsDir"] self.__tabs = dict() for name, config in wholeConfig["tabs"].items(): if not config.get("skip", explicitAddition): storage = wholeStorage for key in ("tabs", name, "values"): storage = StaticUtils.setIfAbsentAndGet( storage, key, dict()) tab = import_module(f"{tabsDir}.{name}", package).Tab(notebook, config, storage, **baseTabKw) self.__tabs[name] = tab notebook.add(tab, text=tab.baseTabCaption) if self.__tabs: if selectedIndex >= len(self.__tabs): selectedIndex = len(self.__tabs) - 1 notebook.select(selectedIndex) return self.__tabs
def __setValueWidth(self): self.__valueLabel["width"] = max( StaticUtils.getPlaces([ x * self.__step for x in (self.__scale["from"], self.__scale["to"]) ]))
def grid(self, **kw): self.__class__._TKINTER_BASE.grid( self, **StaticUtils.mergeJson(kw, self._smartWidgetGrid, True))
def __loadValue(self): self.__value.set( StaticUtils.setIfAbsentAndGet(self._getValueStorage(), "value", self._defaultValue))
def __init__(self, master, **kw): self._parentContainer = master self.__getValueWhenStoring \ , self._namePrefix \ , self._smartWidgetStorage \ , self._smartWidgetGrid \ , self._smartWidgetName = DictPopper(kw) \ .add("getValueWhenStoring", False) \ .add("namePrefix") \ .add("storage") \ .add("grid") \ .add("name", None) # Can be reset in children. self._smartWidgetStyle = StaticUtils.mergeJson( *map( lambda styleName: SmartWidget._STYLE_INSTANCE.configure( styleName) or dict(), [self.__class__.STYLE, kw.get("style", "")]), True) if hasattr(self._parentContainer, "_topLevelContainer"): self._topLevelContainer = self._parentContainer._topLevelContainer if self._smartWidgetName: result = self._topLevelContainer.getSmartWidget(*self._namePrefix) if isinstance(result, SmartWidget): result = result._baseContainerNamedChildren result[self._smartWidgetName] = self for d in (self._smartWidgetGrid, self._smartWidgetStyle): for key, value in d.items(): if key in ("padx", "pady", "childPadx", "childPady"): value = [value] if isinstance(value, Number) else [ float(v) for v in value.split() ] if isinstance(value, str) else value if isinstance( value, list) else None if len(value) == 1: value.append(value[0]) d[key] = value self.__columns = kw.pop("columns", 1) self.__rows = kw.pop("rows", 1) self.__value = kw.pop("value", None) if self.__value: self._defaultValue = self.__value.get() self.__valueDomains = tuple( map(self.__processValueDomains, kw.pop("valueDomains", []))) if not self.__value and self.__valueDomains: raise ValueError( f"'valueDomains' specified for '{self._smartWidgetName}', but there's no value to serialize" ) if self.__class__._TKINTER_BASE: if issubclass(self.__class__._TKINTER_BASE, Widget) and "style" not in kw: kw["style"] = self.__class__.STYLE self.__class__._TKINTER_BASE.__init__(self, master, **kw)
from commonutils import Global, StaticUtils from os import sys, path from tkinter import Tk from tkinter.ttk import Notebook, Style from .basetabloader import BaseTabLoader from .json import Config, Storage from .ttk import CommonUIComponents, SmartWidget from .version import __version__ user32 = None if StaticUtils.isWindows(): from ctypes import WinDLL user32 = WinDLL("user32") class AppLauncher: def __init__(self): self.__root = Tk() self.__notebook = Notebook() if user32: self.__notebook.bind("<Map>", self._maximizeUnderWindows) @property def root(self): return self.__root def run(self, entry, baseTabLoader = BaseTabLoader()):
def isOpen(self): StaticUtils.notImplemented()
def __addRemoveConnectionListener(self, add, connectionListener): StaticUtils.assertInheritance(connectionListener, ConnectionListener, "connectionListener") getattr(self.__connectionListeners, "add" if add else "remove")(connectionListener)
def _write(self, packet): StaticUtils.notImplemented()
def _open(self, path = None, **kw): StaticUtils.notImplemented()
def _close(self): StaticUtils.notImplemented()
def count(): for x in args: if StaticUtils.isIterable(x): return len(x) raise ValueError()