diff --git a/README.md b/README.md index 43591e1..a28c582 100644 --- a/README.md +++ b/README.md @@ -1255,6 +1255,8 @@ Constructor args: in the `Label` as defined by `lwidth`. Method: +* `__call__(row, col=None)` Returns the `Label` instance at a single location. +If no `col` is provided 1D addressing is assumed. * `__getitem__` Returns an iterator enabling `Label` instances to be accessed. * `__setitem__` Assign a value to one or more labels. If multiple labels are specified and a single text value is passed, all labels will receive that @@ -1284,7 +1286,18 @@ grid[1:3, 1:3] = (str(n) for n in range(2)) # Produces # 0 1 # 1 1 ``` -Read access: +Read access: +It is important to note that array index notation always returns an iterator, +even if only a single element is required. One way to access a single element is +```python +it = grid[0 : 0] +label = next(it) +``` +however function call syntax is more intuitive: +```python +label = grid(0, 0) +``` +Accessing labels in a single row, by column: ```python for label in grid[2, 0:]: v = label.value() # Access text of each label in row 2 diff --git a/gui/widgets/grid.py b/gui/widgets/grid.py index 677ea97..b7e89cb 100644 --- a/gui/widgets/grid.py +++ b/gui/widgets/grid.py @@ -20,9 +20,23 @@ def _do_slice(sli, nbytes): stop = min(stop if stop >= 0 else max(nbytes + stop, 0), nbytes) return (start, stop) if start < stop else None # Caller should check + # lwidth may be integer Label width in pixels or a tuple/list of widths class Grid(Widget): - def __init__(self, writer, row, col, lwidth, nrows, ncols, invert=False, fgcolor=None, bgcolor=BLACK, bdcolor=None, justify=0): + def __init__( + self, + writer, + row, + col, + lwidth, + nrows, + ncols, + invert=False, + fgcolor=None, + bgcolor=BLACK, + bdcolor=None, + justify=0, + ): self.nrows = nrows self.ncols = ncols self.ncells = nrows * ncols @@ -41,7 +55,9 @@ class Grid(Widget): c = col for _ in range(self.nrows): for cw in self.cwidth: - self.cells.append(Label(writer, r, c, cw - 4, invert, fgcolor, bgcolor, False, justify)) # No border + self.cells.append( + Label(writer, r, c, cw - 4, invert, fgcolor, bgcolor, False, justify) + ) # No border c += cw r += self.cheight c = col @@ -55,7 +71,7 @@ class Grid(Widget): # grid[[r, c]] = {"text": str(n), "fgcolor" : RED} def __setitem__(self, *args): x = args[1] # Value - indices = do_args(args[: -1], self.nrows, self.ncols) + indices = do_args(args[:-1], self.nrows, self.ncols) for i in indices: try: z = next(x) # May be a generator @@ -66,6 +82,9 @@ class Grid(Widget): v = self.cells[i].value # method of Label _ = v(**z) if isinstance(x, dict) else v(z) + def __call__(self, row, col=None): # Return a single Label + return self.cells[row if col is None else col + row * self.ncols] + def show(self): super().show() # Draw border if self.has_border: # Draw grid