libtextworker 0.1.4
Cross-platform, free and open library for Python projects
miscs.py
1 """
2 @package libtextworker.interface.tk.miscs
3 """
4 
5 # A cross-platform library for Python apps.
6 # Copyright (C) 2023-2024 Le Bao Nguyen and contributors.
7 # This is a part of the libtextworker project.
8 # Licensed under the GNU General Public License version 3.0 or later.
9 
10 from typing import Literal
11 from tkinter import Menu, Misc
12 
13 def CreateMenu(items: list[dict[str]], parent: Misc | None = None,
14  tearoff: Literal[0, 1] = 0, title: str = ...) -> Menu:
15  """
16  Make a Tkinter menu with commands inside.
17 
18  Available keys can be found on tkinter.Menu.add_*, but whatever:
19  - label [str] - handler [str|typing.Callable]
20  - accelerator [str] - onvalue [=None]
21  - offvalue [=None] - variable [=None]
22  - state [normal, active, disabled][=normal]
23  - kind [check, option, separator, normal] [=normal]
24 
25  @param items (list[dict[str]]): Menu items to be added
26  @param parent (Misc | None = None): Where to place the Menu, optional
27  @param tearoff (1 or 0, defaults to 0): Whatever... Optional, ofc
28  @param title (str): Optional too, the title for the menu
29  @return tkinter.Menu
30  """
31 
32  target = Menu(parent, tearoff=tearoff, title=title)
33  none_to_blank = {None: ""}
34  none_to_blank_2 = {None: ...}
35 
36  def convert(item: str | None, type: Literal[1, 2]):
37  if type == 2:
38  return none_to_blank_2.get(item, item)
39  else:
40  return none_to_blank.get(item, item)
41 
42  for item in items:
43  label = convert(item.get("label", None), 1)
44  acc = convert(item.get("accelerator", None), 1)
45  handler = convert(item.get("handler", None), 2)
46  onvalue = convert(item.get("onvalue", None), 2)
47  offvalue = convert(item.get("offvalue", None), 2)
48  variable = convert(item.get("variable", None), 2)
49  state = item.get("state", "normal")
50  kind = item.get("kind", "normal")
51 
52  args = {"accelerator": acc, "command": handler, "label": label, "state": state}
53 
54  if kind == "normal":
55  target.add_command(**args)
56 
57  if kind == "check":
58  target.add_checkbutton(
59  **args, onvalue=onvalue, offvalue=offvalue, variable=variable
60  )
61 
62  if kind == "separator":
63  target.add_separator()
64 
65  if kind == "option":
66  target.add_radiobutton(
67  **args,
68  variable=variable,
69  )
70 
71  return target
Menu CreateMenu(list[dict[str]] items, Misc|None parent=None, Literal[0, 1] tearoff=0, str title=...)
Definition: miscs.py:14