tkmilan.fn#

Functions to manipulate widgets and other objects, that make no sense to be used externally.

If useful, they should be exposed as methods.

Module Attributes

VARNAME_AUTOPREFIX

The variable name automatic prefix marker.

VARNAME_AUTOID

The variable name automatic identifier.

Functions

ask_directory_load(parent[, title, ...])

Wrap a file dialog that returns a directory name, for loading data.

ask_directory_save(parent[, title, ...])

Wrap a file dialog that returns a directory name, for saving data.

ask_file_load(parent[, title, full_title, ...])

Wrap a file dialog that returns a file name, for loading data.

ask_file_save(parent[, title, full_title, ...])

Wrap a file dialog that returns a file name, for saving data.

bind_mousewheel(widget, up, down, **kwargs)

OS-independent mouse wheel bindings.

binding_disable([event])

Disable the binding (stop chaining the bind functions).

configure_grid(master, column_weights, ...)

Configure the grid.

debugWidget(widget)

Log all information about the given widget.

grid_size(*widgets)

Get the grid size for the given widgets.

label2id(label)

Turn a label into an identifier.

label_fallback(*labels)

Calculate the fallback for several label objects.

label_size(chars)

DEPRECATED.

label_width(label, *[, font])

Estimate a label size (in pixels) for the given label.

onDebugPWidget(event)

Run debugWidget on the event widget's parent widget.

onDebugWidget(event)

Run debugWidget on the event widget.

process_scaling_dpi(*[, win_awareness])

Configure scaling awareness for the current process.

scrollGenCommand(fn, why, what, fn_scrollstate)

scrollTo(widget, *, x, y, anchor)

state_bindtags(widget, state, *, bt_on, bt_off)

Change the widget state based on bindtags state.

state_ignore(*toignore)

Ignore some subwidgets for container widgets.

valFloat(string)

Validate a number is a float.

valFraction(string)

Validate a number is a Fraction (ratio between integers).

valInteger(string)

Validate a number is an int, in any supported base.

valNumber(string)

DEPRECATED.

validation_fail(label[, why])

Absorvent validation function, denies everything.

validation_pass(label[, why])

Neutral validation function, accepts everything.

vname(variable)

Collect the variable name.

vname_choose(vnames)

Choose the best variable name

vname_sort(evname)

Sort variable names according to some rules:

widget_toolwindow(window)

Change the widget "toolwindow" state.

window_center(window, where, *[, adjustOOB, ...])

Center window on a root window where.

tkmilan.fn.ask_directory_load(parent: mixin.MixinWidget, title: str = 'Folder', full_title: str | None = None, initialDirectory: Path | None = None, **kwargs) Path | None#

Wrap a file dialog that returns a directory name, for loading data.

Since this is for loading data, it will guarantee the directory exists.

Parameters:
  • title (str) – Window Title, prefixed by the operation mode.

  • full_title (str | None) – Override final title, ignoring the operation mode. Optional.

  • initialDirectory (Path | None) –

    Initial Directory to open the dialog, or None to use the OS-specific default.

    Optional, defaults to None.

  • kwargs – Passed to the upstream function.

Returns:

If the user bails, return None. Otherwise return a Path, guaranteed to be a directory.

Return type:

Path | None

See also

See ask_directory_save for the Save alternative to this function.

tkmilan.fn.ask_directory_save(parent: mixin.MixinWidget, title: str = 'Folder', full_title: str | None = None, initialDirectory: Path | None = None, **kwargs) Path | None#

Wrap a file dialog that returns a directory name, for saving data.

Since this is for saving data, it allows for non-existing directories.

Parameters:
  • title (str) – Window Title, prefixed by the operation mode.

  • full_title (str | None) – Override final title, ignoring the operation mode. Optional.

  • initialDirectory (Path | None) –

    Initial Directory to open the dialog, or None to use the OS-specific default.

    Optional, defaults to None.

  • kwargs – Passed to the upstream function.

Returns:

If the user bails, return None. Otherwise return a Path.

Return type:

Path | None

See also

See ask_directory_load for the Load alternative to this function.

tkmilan.fn.ask_file_load(parent: mixin.MixinWidget, title: str = 'File', full_title: str | None = None, initialDirectory: Path | None = None, filetypes: FileTypes | None = None, includeSupported: bool = True, includeAll: bool = True, configureDefault: bool = False, **kwargs) Path | None#

Wrap a file dialog that returns a file name, for loading data.

Since this is for loading data, it will guarantee the file exists.

Parameters:
  • title (str) – Window Title, prefixed by the operation mode.

  • full_title (str | None) – Override final title, ignoring the operation mode. Optional.

  • initialDirectory (Path | None) – Initial Directory to open the dialog, or None to use the OS-specific default. Optional, defaults to None.

  • filetypes (FileTypes | None) –

    FileTypes object with all supported FileType patterns.

    This is a mapping from UI string, to FileType object. The default option is the first one, but this interacts with includeSupported.

    Optional, when not given it acts as no filetypes are supported. See includeAll.

  • includeSupported (bool) –

    Include a pattern for all supported filetypes, on the filetypes list.

    This is included as the first pattern, therefor it acts as the default selection. Only included if there is more that one filetype.

    Defaults to True.

  • includeAll (bool) –

    Include a pattern for all files, on the filetypes list.

    This is included as the last pattern, so it will be the default only if there are no supported filetypes.

    Defaults to True.

  • configureDefault (bool) –

    Configure the default suffix as the first element on filetypes (if exists). This is pure evil because the user will get a suffix added that is not shown anywhere.

    Defaults to False.

  • kwargs – Passed to the upstream function.

Note

Giving no filetypes forces includeAll to True.

Returns:

If the user bails or the selected file is not supported, return None. Otherwise return a Path, guaranteed to be a file.

Return type:

Path | None

See also

See ask_file_save for the Save alternative to this function.

tkmilan.fn.ask_file_save(parent: mixin.MixinWidget, title: str = 'File', full_title: str | None = None, initialDirectory: Path | None = None, filetypes: FileTypes | None = None, includeSupported: bool = False, includeAll: bool = False, configureDefault: bool = False, **kwargs) Path | None#

Wrap a file dialog that returns a file name, for saving data.

Since this is for saving data, it allows for non-existing files.

Parameters:
  • title (str) – Window Title, prefixed by the operation mode.

  • full_title (str | None) – Override final title, ignoring the operation mode. Optional.

  • initialDirectory (Path | None) – Initial Directory to open the dialog, or None to use the OS-specific default. Optional, defaults to None.

  • filetypes (FileTypes | None) –

    FileTypes object with all supported FileType patterns.

    This is a mapping from UI string, to FileType object. The default option is the first one, but this interacts with includeSupported.

    Optional, when not given it acts as no filetypes are supported. See includeAll.

  • includeSupported (bool) –

    Include a pattern for all supported filetypes, on the filetypes list.

    This is included as the first pattern, therefor it acts as the default selection. Only included if there is more that one filetype.

    Defaults to False.

  • includeAll (bool) –

    Include a pattern for all files, on the filetypes list.

    This is included as the last pattern, so it will be the default only if there are no supported filetypes.

    Defaults to False.

  • configureDefault (bool) –

    Configure the default suffix as the first element on filetypes (if exists). This is pure evil because the user will get a suffix added that is not shown anywhere.

    Defaults to False.

  • kwargs – Passed to the upstream function.

Note

Giving no filetypes forces includeAll to True.

Returns:

If the user bails or the selected file is not supported, return None. Otherwise return a Path.

Return type:

Path | None

See also

See ask_file_load for the Load alternative to this function.

tkmilan.fn.bind_mousewheel(widget, up: Callable, down: Callable, **kwargs) Binding | Tuple[Binding, Binding]#

OS-independent mouse wheel bindings.

This is a digital scroll.

On Linux, this is implemented as two special mouse buttons (“up” and “down”. Windows supports analog mouse wheels, but this function emulates a digital scroll out of that.

The return value is platform-specific:

  • On Linux, return the two Binding object, for “up” and “down” mouse scroll.

  • On Windows, returns the single Binding object for the analog mouse scroll.

Note

This uses regular Binding objects, remember that immediate=True is needed to activate the binding on start.

tkmilan.fn.binding_disable(event=None)#

Disable the binding (stop chaining the bind functions).

Attach this function to a Binding event to disable the processing, even for further validations.

tkmilan.fn.configure_grid(master: mixin.ContainerWidget, column_weights: Sequence[int], row_weights: Sequence[int], **kwargs: Mapping[str, Any]) None#

Configure the grid.

Weights can be:

  • 0 : Fit the widgets, never resize

  • >0: Resize with this number as weight

Make sure to include all columns and rows. When in doubt, use 0.

Parameters:
  • column_weights (Sequence[int]) – List of column weights

  • row_weights (Sequence[int]) – List of row weights

  • kwargs (Mapping[str, Any]) – Extra arguments to the configuration functions columnconfigure / rowconfigure.

tkmilan.fn.debugWidget(widget)#

Log all information about the given widget.

As the name implies, this is a debug function, only available on __debug__.

This should be used like this, on the RootWindow:

def setup_adefaults(self):
    if __debug__:
        BindingGlobal(self, '<Shift-Button-2>', fn.onDebugWidget,
                      immediate=True, description='Debug GUI for Current Widget')
        BindingGlobal(self, '<Control-Shift-Button-2>', fn.onDebugPWidget,
                      immediate=True, description='Debug GUI on Parent Widget')

Choose your own binding keys, these are just an example.

See also

See the wrapper functions onDebugWidget, onDebugPWidget.

See the TKMILAN_DEBUG environment variable for extra debug settings.

tkmilan.fn.grid_size(*widgets: mixin.MixinWidget) model.GridSize#

Get the grid size for the given widgets.

This should be used by a frame to calculate its grid size, by checking the values for all its children widgets.

Parameters:

widgets (mixin.MixinWidget) – Widgets in the same grid. There should be at least one.

tkmilan.fn.label2id(label: str) str#

Turn a label into an identifier.

Replace all non-alphanumeric characters with _.

tkmilan.fn.label_fallback(*labels: str | None) str | None#

Calculate the fallback for several label objects.

Similar to a series of or operator applications, considering edge cases like the label ''.

tkmilan.fn.label_size(chars: int) int#

DEPRECATED. See label_width.

tkmilan.fn.label_width(label: str, *, font: Font | None = None) int#

Estimate a label size (in pixels) for the given label.

When not given a font, count the number of chars and make an educated guess. When given the actual font to be used, it’s a measurement, not a estimative.

Parameters:
  • label (str) – The label to estimate

  • font (Font | None) – The font object to measure.

tkmilan.fn.onDebugPWidget(event)#

Run debugWidget on the event widget’s parent widget.

tkmilan.fn.onDebugWidget(event)#

Run debugWidget on the event widget.

tkmilan.fn.process_scaling_dpi(*, win_awareness: Literal[1, 2] = 2) bool#

Configure scaling awareness for the current process.

Use OS primitives to mark this process as aware of DPI scaling. This is only a suggestion to the operating system.

This function affects the whole process, it should only run once, and as soon as possible. Critically, it must run before creating the first widget.

See also the scaling_dpi style in RootWindow.Style, they are related.

Parameters:

win_awareness (Literal[1, 2]) – For Windows OS, define the PROCESS_DPI_AWARENESS setting. Defaults to PROCESS_PER_MONITOR_DPI_AWARE. See SetProcessDpiAwareness function documentation.

Note

Only Windows OS are supported, it’s a no-op on other OS.

tkmilan.fn.state_bindtags(widget: Widget, state: bool, *, bt_on: Tuple[str, ...], bt_off: Tuple[str, ...])#

Change the widget state based on bindtags state.

This is useful to truly disable all events flowing to a widget, since the Tk state might keep some events enabled.

There is no Python documentation, see Tk bindtags documentation.

Parameters:
  • widget (Widget) – Widget to modify

  • state (bool) – Should the widget be enabled (regular state) or disabled (fully dead).

  • bt_on (Tuple[str, ...]) – BindTags when enabled. Mandatory, usually widget.bindtags() when the widget is created.

  • bt_off (Tuple[str, ...]) – BindTags when disabled. Mandatory, usually widget.bindtags()[-2:] when the widget is created.

tkmilan.fn.state_ignore(*toignore: mixin.MixinWidget)#

Ignore some subwidgets for container widgets.

Mark those widgets with the ignoreContainerState flag. Should be called as part of the setup_widgets function in container widgets.

tkmilan.fn.valFloat(string: str) float | None#

Validate a number is a float.

This ignores all possible whitespace.

Returns:

None if cannot be parsed as a floating point, float otherwise.

Return type:

float | None

tkmilan.fn.valFraction(string: str) Fraction | None#

Validate a number is a Fraction (ratio between integers).

This ignores all possible whitespace, it is more lenient than the upstream Fraction function.

Returns:

None if cannot be parsed as fraction, Fraction otherwise.

Return type:

Fraction | None

tkmilan.fn.valInteger(string: str) int | None#

Validate a number is an int, in any supported base.

Returns:

None if not a number, int otherwise.

Return type:

int | None

tkmilan.fn.valNumber(string: str) int | None#

DEPRECATED. See valInteger.

tkmilan.fn.validation_fail(label: str, why: VWhy | None = None, **kwargs) bool | None#

Absorvent validation function, denies everything.

Use this function to invalidate all states, as the fn parameter for model.VSettings.

tkmilan.fn.validation_pass(label: str, why: VWhy | None = None, **kwargs) bool | None#

Neutral validation function, accepts everything.

Use this function to validate all states, as the fn parameter for model.VSettings.

tkmilan.fn.vname(variable: Variable) str#

Collect the variable name.

This is set on the object, but there’s no typing support for it. Double check it here.

tkmilan.fn.vname_choose(vnames: Iterable[str]) str#

Choose the best variable name

This might be technically subjective, but is implemented by following the rules in vname_sort, and taking the “best” scoring name.

If the top two elements contain VARNAME_AUTOID, take the common prefix.

Parameters:

vnames (Iterable[str]) – A sequence of possible variable names

Returns:

The best scoring variable name.

Return type:

str

tkmilan.fn.vname_sort(evname) Tuple[int, str]#

Sort variable names according to some rules:

Lowest score is the best. For names with the same score, order by alphabetic order.

Note

This is to be used as key on sorted or list.sort.

tkmilan.fn.widget_toolwindow(window: Wm)#

Change the widget “toolwindow” state.

This state makes the window present itself as a kind of toolbar window for another window. Can also be used on the RootWindow, in which case the window takes similar properties.

See Tk wm transient documentation. This is only a window manager hint.

This is an irreversible action. Depending on the platform, this is defined in several ways:

All other platforms are unsupported.

tkmilan.fn.window_center(window: Toplevel, where: Tk | Toplevel, *, adjustOOB: bool = True, window_requested: bool = False) bool#

Center window on a root window where.

Considers the sizes of both elements.

The adjustOOB argument controls if this functions “guarantees” the window will not move out of bounds. On Windows, this will use special API to gather a desktop “work area” (ignoring taskbars), then include some heuristic values that should make sure the window cannot fall out of bounds. On Linux, this is less important, most window managers do not move windows out of bounds. Tiling window managers are even more lenient in funky geometry requests.

This is only a window manager hint, the geometry might not actually move. This is confirmed in tiling window managers.

Parameters:
  • window (Toplevel) – The window to move.

  • where (Tk | Toplevel) – The RootWindow to consider as the “center”.

  • adjustOOB (bool) – Adjust Out-of-Bounds geometries. Enabled by default, see the details above.

  • window_requested (bool) – Consider the requested size, instead of the actual size. See the upstream functions MixinWidget.wsize, MixinWidget.wgeometry. Defaults to False.

Returns:

Returns True is the window moved to its requested location, False otherwise.

Return type:

bool

tkmilan.fn.VARNAME_AUTOID = '__'#

The variable name automatic identifier. See menu.process.

tkmilan.fn.VARNAME_AUTOPREFIX = 'PY_VAR'#

The variable name automatic prefix marker. Implemented upstream.