tkutil.html
001| """Utilities for tkinter applications.
001|
001| Clipboard Copy example:
001| from tkinter import Tk
001| root = Tk()
001| root.withdraw()
001| root.clipboard_clear()
001| root.clipboard_append("Oh, this is almost too much fun!")
001| root.update()
001| root.wm_deiconify()
001| root.destroy()
001|
001| Dialogs:
001| filedialog.askopenfilename(**options)
001| filedialog.askopenfilenames(**options)
001| filedialog.askopenfile(**options)
001| filedialog.askopenfiles(**options)
001| filedialog.asksaveasfilename(**options)
001| filedialog.asksaveasfile(**options)
001| filedialog.askdirectory(**options)
001|
001| options:
001| -parent
001| -title
001| -filetypes=[(label,fspec), ...]
001| -defaultextension
001| -initialdir
001| -initialfile
001| -typevariable
001| -multiple
001|
001| colorchooser.askcolor(color=None, **options)
001|
001| messagebox.showinfo(title=None, message=None, **options)
001| messagebox.showwarning(title=None, message=None, **options)
001| messagebox.showerror(title=None, message=None, **options)
001| messagebox.askquestion(title=None, message=None, **options)
001| messagebox.askokcancel(title=None, message=None, **options)
001| messagebox.askyesno(title=None, message=None, **options)
001| messagebox.askyesnocancel(title=None, message=None, **options)
001| messagebox.askretrycancel(title=None, message=None, **options)
001|
001| simpledialog.askinteger(title, prompt, **kw)
001| simpledialog.askfloat(title, prompt, **kw)
001| simpledialog.askstring(title, prompt, **kw)
001|
001| Grid options:
001| in=master - use master to contain this widget
001| in_=master - see 'in' option description
001| row=number - use cell identified with given row (starting with 0)
001| column=number - use cell identified with given column (starting with 0)
001| rowspan=number - this widget will span several rows
001| columnspan=number - this widget will span several columns
001| sticky=value - if cell larger, which sides this widget sticks to boundary
001| values: "nesw" (or valid subset)
001| padx=amount - add padding in x direction
001| pady=amount - add padding in y direction
001| ipadx=amount - add internal padding in x direction
001| ipady=amount - add internal padding in y direction
001|
001| Pack options:
001| in=master - use master to contain this widget
001| in_=master - see 'in' option description
001| side=value - where to add this widget
001| values: "top" | "bottom" | "left" | "right"
001| anchor=value - position widget according to given direction
001| values: "nesw" (or subset)
001| fill=value - fill widget if widget grows
001| values: "none" | "x" | "y" | "both"
001| expand=bool - expand widget if parent size grows
001| ipadx=amount - add internal padding in x direction
001| ipady=amount - add internal padding in y direction
001| padx=amount - add padding in x direction
001| pady=amount - add padding in y direction
001| before=widget - pack it before you will pack widget
001| after=widget - pack it after you have packed widget
001|
001| Place options:
001| in=master - master relative to which the widget is placed
001| in_=master - see 'in' option description
001| anchor=NSEW - position anchor according to given direction
001| values: "nesw" or subset
001| width=amount - width of this widget in pixel
001| height=amount - height of this widget in pixel
001| x=amount - locate anchor of this widget at position x of master
001| y=amount - locate anchor of this widget at position y of master
001| relx=amount - locate anchor of this widget between 0.0 and 1.0
001| relative to width of master (1.0 is right edge)
001| rely=amount - locate anchor of this widget between 0.0 and 1.0
001| relative to height of master (1.0 is bottom edge)
001| relwidth=amount - width of this widget between 0.0 and 1.0 relative to
001| the width of master (1.0 is same width as master)
001| relheight=amount - height of this widget between 0.0 and 1.0 relative to
001| the height of master (1.0 is same height as master)
001| bordermode= - whether to take border width of master widget into account
001| values: "inside" or "outside"
001|
001| Events:
001| FocusIn, FocusOut,
001| KeyPress (Key), KeyRelease,
001| ButtonPress (Button), ButtonRelease,
001| Selection, SelectionRequest, SelectionClear,
001| Enter, Motion, Leave, MouseWheel,
001| ResizeRequest,
001| Circulate, CirculateRequest,
001| Activate, Deactivate,
001| Create, Destroy, Reparent, Gravity,
001| ClientMessage,
001| Map, Mapping, Unmap, MapRequest, Keymap, Colormap,
001| Visibility, Expose, GraphicsExpose, NoExpose,
001| Configure, ConfigureRequest,
001| Property,
001| VirtualEvent,
001|
001| Event objects have the following attributes (in braces
001| are the event types for which the attribute is valid):
001|
001| serial -serial number of event
001| time -when the event occurred
001| type -type of the event as a number
001| widget -widget in which the event occurred
001| state -state of the event as a number {ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, Motion}
001| state -state as a string {Visibility}
001| keycode -keycode of the pressed key {KeyPress, KeyRelease}
001| keysym -keysym of the event as a string {KeyPress, KeyRelease}
001| keysym_num -keysym of the event as a number {KeyPress, KeyRelease}
001| char -pressed character {KeyPress, KeyRelease}
001| num -mouse button pressed {ButtonPress, ButtonRelease}
001| x -x-position of the mouse
001| y -y-position of the mouse
001| x_root -x-position of the mouse on the screen {ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion}
001| y_root -y-position of the mouse on the screen {ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion}
001| delta -delta of wheel movement {MouseWheel}
001| focus -whether the window has the focus {Enter, Leave}
001| height -height of the exposed window {Configure, Expose}
001| width -width of the exposed window {Configure, Expose}
001| send_event -see X/Windows documentation
001|
001| Activate = <EventType.Activate: '36'>
001| ButtonPress = <EventType.ButtonPress: '4'>
001| ButtonRelease = <EventType.ButtonRelease: '5'>
001| Circulate = <EventType.Circulate: '26'>
001| CirculateRequest = <EventType.CirculateRequest: '27'>
001| ClientMessage = <EventType.ClientMessage: '33'>
001| Colormap = <EventType.Colormap: '32'>
001| Configure = <EventType.Configure: '22'>
001| ConfigureRequest = <EventType.ConfigureRequest: '23'>
001| Create = <EventType.Create: '16'>
001| Deactivate = <EventType.Deactivate: '37'>
001| Destroy = <EventType.Destroy: '17'>
001| Enter = <EventType.Enter: '7'>
001| Expose = <EventType.Expose: '12'>
001| FocusIn = <EventType.FocusIn: '9'>
001| FocusOut = <EventType.FocusOut: '10'>
001| GraphicsExpose = <EventType.GraphicsExpose: '13'>
001| Gravity = <EventType.Gravity: '24'>
001| KeyPress = <EventType.KeyPress: '2'>
001| KeyRelease = <EventType.KeyRelease: '3'>
001| Keymap = <EventType.Keymap: '11'>
001| Leave = <EventType.Leave: '8'>
001| Map = <EventType.Map: '19'>
001| MapRequest = <EventType.MapRequest: '20'>
001| Mapping = <EventType.Mapping: '34'>
001| Motion = <EventType.Motion: '6'>
001| MouseWheel = <EventType.MouseWheel: '38'>
001| NoExpose = <EventType.NoExpose: '14'>
001| Property = <EventType.Property: '28'>
001| Reparent = <EventType.Reparent: '21'>
001| ResizeRequest = <EventType.ResizeRequest: '25'>
001| Selection = <EventType.Selection: '31'>
001| SelectionClear = <EventType.SelectionClear: '29'>
001| SelectionRequest = <EventType.SelectionRequest: '30'>
001| Unmap = <EventType.Unmap: '18'>
001| VirtualEvent = <EventType.VirtualEvent: '35'>
001| Visibility = <EventType.Visibility: '15'>
001|
001| tk.Entry.config():
001| 'background': ('background', 'background', 'Background', <border object: 'SystemWindow'>, 'SystemWindow'),
001| 'foreground': ('foreground', 'foreground', 'Foreground', <color object: 'SystemWindowText'>, 'SystemWindowText'),
001| 'borderwidth': ('borderwidth', 'borderWidth', 'BorderWidth', 1, 1),
001| 'fg': ('fg', '-foreground'),
001| 'bg': ('bg', '-background'),
001| 'bd': ('bd', '-borderwidth'),
001| 'relief': ('relief', 'relief', 'Relief', <index object: 'sunken'>, 'flat'),
001| 'width': ('width', 'width', 'Width', 20, 20),
001| 'font': ('font', 'font', 'Font', <font object: 'TkTextFont'>, 'Arial 10 bold'),
001| 'justify': ('justify', 'justify', 'Justify', <index object: 'left'>, 'left'),
001| 'textvariable': ('textvariable', 'textVariable', 'Variable', '', 'PY_VAR0'),
001| 'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '', ''),
001| 'exportselection': ('exportselection', 'exportSelection', 'ExportSelection', 1, 1),
001| 'show': ('show', 'show', 'Show', '', ''),
001| 'state': ('state', 'state', 'State', <index object: 'normal'>, 'disabled'),
001| 'cursor': ('cursor', 'cursor', 'Cursor', <cursor object: 'xterm'>, 'xterm'),
001| 'validate': ('validate', 'validate', 'Validate', <index object: 'none'>, 'none'),
001| 'validatecommand': ('validatecommand', 'validateCommand', 'ValidateCommand', '', ''),
001| 'vcmd': ('vcmd', '-validatecommand'),
001| 'invalidcommand': ('invalidcommand', 'invalidCommand', 'InvalidCommand', '', ''),
001| 'invcmd': ('invcmd', '-invalidcommand'),
001| 'xscrollcommand': ('xscrollcommand', 'xScrollCommand', 'ScrollCommand', '', '')
001| 'readonlybackground': ('readonlybackground', 'readonlyBackground', 'ReadonlyBackground', <border object: 'SystemButtonFace'>, 'SystemButtonFace'),
001| 'disabledbackground': ('disabledbackground', 'disabledBackground', 'DisabledBackground', <border object: 'SystemButtonFace'>, 'SystemButtonFace'),
001| 'disabledforeground': ('disabledforeground', 'disabledForeground', 'DisabledForeground', <color object: 'SystemDisabledText'>, 'SystemDisabledText'),
001| 'selectbackground': ('selectbackground', 'selectBackground', 'Foreground', <border object: 'SystemHighlight'>, 'SystemHighlight'),
001| 'selectforeground': ('selectforeground', 'selectForeground', 'Background', <color object: 'SystemHighlightText'>, 'SystemHighlightText'),
001| 'selectborderwidth': ('selectborderwidth', 'selectBorderWidth', 'BorderWidth', 0, 0),
001| 'highlightbackground': ('highlightbackground', 'highlightBackground', 'HighlightBackground', <color object: 'SystemButtonFace'>, 'SystemButtonFace'),
001| 'highlightcolor': ('highlightcolor', 'highlightColor', 'HighlightColor', <color object: 'SystemWindowFrame'>, 'SystemWindowFrame'),
001| 'highlightthickness': ('highlightthickness', 'highlightThickness', 'HighlightThickness', 0, 0),
001| 'insertbackground': ('insertbackground', 'insertBackground', 'Foreground', <border object: 'SystemWindowText'>, 'SystemWindowText'),
001| 'insertborderwidth': ('insertborderwidth', 'insertBorderWidth', 'BorderWidth', 0, 0),
001| 'insertofftime': ('insertofftime', 'insertOffTime', 'OffTime', 300, 300),
001| 'insertontime': ('insertontime', 'insertOnTime', 'OnTime', 600, 600),
001| 'insertwidth': ('insertwidth', 'insertWidth', 'InsertWidth', 2, 2),
001|
001| tk.Button.config():
001| 'background': ('background', 'background', 'Background', <border object: 'SystemWindow'>, 'SystemWindow'),
001| 'foreground': ('foreground', 'foreground', 'Foreground', <color object: 'SystemWindowText'>, 'SystemWindowText'),
001| 'borderwidth': ('borderwidth', 'borderWidth', 'BorderWidth', 1, 1),
001| 'bg': ('bg', '-background'),
001| 'fg': ('fg', '-foreground'),
001| 'bd': ('bd', '-borderwidth'),
001| 'relief': ('relief', 'relief', 'Relief', <index object: 'sunken'>, 'sunken'),
001| 'width': ('width', 'width', 'Width', 20, 40),
001| 'font': ('font', 'font', 'Font', <font object: 'TkTextFont'>, 'TkTextFont'),
001| 'justify': ('justify', 'justify', 'Justify', <index object: 'left'>, 'left'),
001| 'textvariable': ('textvariable', 'textVariable', 'Variable', '', 'PY_VAR0'),
001| 'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '', ''),
001| 'exportselection': ('exportselection', 'exportSelection', 'ExportSelection', 1, 1),
001| 'show': ('show', 'show', 'Show', '', ''),
001| 'state': ('state', 'state', 'State', <index object: 'normal'>, 'normal'),
001| 'cursor': ('cursor', 'cursor', 'Cursor', <cursor object: 'xterm'>, 'xterm'),
001| 'validate': ('validate', 'validate', 'Validate', <index object: 'none'>, 'none'),
001| 'validatecommand': ('validatecommand', 'validateCommand', 'ValidateCommand', '', ''),
001| 'vcmd': ('vcmd', '-validatecommand'),
001| 'invalidcommand': ('invalidcommand', 'invalidCommand', 'InvalidCommand', '', ''),
001| 'invcmd': ('invcmd', '-invalidcommand'),
001| 'xscrollcommand': ('xscrollcommand', 'xScrollCommand', 'ScrollCommand', '', '')
001| 'readonlybackground': ('readonlybackground', 'readonlyBackground', 'ReadonlyBackground', <border object: 'SystemButtonFace'>, 'SystemButtonFace'),
001| 'disabledbackground': ('disabledbackground', 'disabledBackground', 'DisabledBackground', <border object: 'SystemButtonFace'>, 'SystemButtonFace'),
001| 'disabledforeground': ('disabledforeground', 'disabledForeground', 'DisabledForeground', <color object: 'SystemDisabledText'>, 'SystemDisabledText'),
001| 'selectbackground': ('selectbackground', 'selectBackground', 'Foreground', <border object: 'SystemHighlight'>, 'SystemHighlight'),
001| 'selectforeground': ('selectforeground', 'selectForeground', 'Background', <color object: 'SystemHighlightText'>, 'SystemHighlightText'),
001| 'selectborderwidth': ('selectborderwidth', 'selectBorderWidth', 'BorderWidth', 0, 0),
001| 'highlightbackground': ('highlightbackground', 'highlightBackground', 'HighlightBackground', <color object: 'SystemButtonFace'>, 'SystemButtonFace'),
001| 'highlightcolor': ('highlightcolor', 'highlightColor', 'HighlightColor', <color object: 'SystemWindowFrame'>, 'SystemWindowFrame'),
001| 'highlightthickness': ('highlightthickness', 'highlightThickness', 'HighlightThickness', 0, 0),
001| 'insertbackground': ('insertbackground', 'insertBackground', 'Foreground', <border object: 'SystemWindowText'>, 'SystemWindowText'),
001| 'insertborderwidth': ('insertborderwidth', 'insertBorderWidth', 'BorderWidth', 0, 0),
001| 'insertofftime': ('insertofftime', 'insertOffTime', 'OffTime', 300, 300),
001| 'insertontime': ('insertontime', 'insertOnTime', 'OnTime', 600, 600),
001| 'insertwidth': ('insertwidth', 'insertWidth', 'InsertWidth', 2, 2),
001|
001| Menu Check and Radio Button forms:
001|
001| def helper ():
001| for ix in [2,3, 5,6,7,8]:
001| mnu = bag['mb']
001| label = mnu.entryconfig(ix, 'label')
001| state = mnu.entryconfig(ix, 'state')
001| indic = mnu.entryconfig(ix, 'indicatoron')
001| print(f'{label[4]}; {state[4]}; {indic[3]}:{indic[4]}')
001| print()
001|
001| CheckButton Configuration:
001| state,
001| label, underline, accelerator, command, variable,
001| background, foreground, activebackground, activeforeground,
001| selectcolor, selectimage,
001| font, bitmap, image,
001| indicatoron, offvalue, onvalue,
001| compound, hidemargin, columnbreak,
001|
001| RadioButton Configuration:
001| state,
001| value,
001| label, underline, accelerator, command, variable,
001| background, foreground, activebackground, activeforeground,
001| selectcolor, selectimage,
001| font, bitmap, image,
001| indicatoron,
001| compound, hidemargin, columnbreak,
001|
001| """
002|
003| from os import path
004| import tkinter as tk
005| import tkinter.ttk as ttk
006| from goodies import typename, KWARG, makefilename, isreallyafile
007| from logger import logger
008|
009| BasePath = r'C:\CJS\prj\Python\ws\tk'
010| CnfgPath = path.join(BasePath, 'cfg')
011| DataPath = path.join(BasePath, 'dat')
012| ListPath = path.join(BasePath, 'out')
013| Log = logger('TkUtil')
014|
015|
016|
017| KEYPRESS_SHIFT = 0x00001
018| KEYPRESS_CTRL = 0x00004
019| KEYPRESS_ALT = 0x20000
020| KEYPRESS_EXT = 0x40000
021|
022|
023|
024| def keypress_states (state):
025| '''Extract flags from state and return text versions.'''
026| mods = (
027|
028| 'Shift', 'Lock', 'Control',
029|
030| 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5',
031|
032| 'Button1', 'Button2', 'Button3', 'Button4', 'Button5'
033| )
034| flags = [m for ix,m in enumerate(mods) if state & (1 << ix)]
035|
036| if state & KEYPRESS_ALT:
037| flags.insert(-1, 'Alt')
038|
039| if state & KEYPRESS_EXT:
040| flags.insert(0, 'Ext')
041|
042| return ','.join(flags)
043|
044|
045|
046| class TkGeometry (tuple):
047| '''Convenience class for tkinter geometry strings.'''
048|
049| def from_string (geom_string):
050| dims,xpos,ypos = geom_string.split('+')
051| xdim,ydim = dims.split('x')
052| return TkGeometry(*[int(x) for x in [xdim,ydim,xpos,ypos]])
053|
054| def __new__ (cls, xdim=800, ydim=600, xpos=150, ypos=50):
055| '''Overloading __new__ to create the right input for tuple.'''
056| return super().__new__(cls, [xdim,ydim,xpos,ypos])
057|
058| @property
059| def xdim (self): return self[0]
060|
061| @property
062| def ydim (self): return self[1]
063|
064| @property
065| def xpos (self): return self[2]
066|
067| @property
068| def ypos (self): return self[3]
069|
070| @property
071| def dims (self): return self[0:2]
072|
073| @property
074| def pos (self): return self[2:4]
075|
076| def __repr__ (self):
077| return f'<{typename(self)} @{id(self):08x}>'
078|
079| def __str__ (self):
080| return f'{self.xdim}x{self.ydim}+{self.xpos}+{self.ypos}'
081|
082|
083|
084| def vibe_get_layout_elements (widget_name='TButton') -> list[str]:
085| '''An Ai said it was okay...
085|
085| Recursive extraction
085| The code walks through all nested elements in the layout.
085|
085| How it works:
085|
085| style.layout("TLabel")
085|
085| Returns the widget’s internal element structure.
085|
085| style.element_options(element)
085|
085| Lists all configurable style options for that element
085| (e.g., -background, -foreground, -font, -padding).
085|
085|
085| Typical TLabel style elements and options
085| On most platforms/themes (e.g., default, clam, alt), you’ll
085| see something like:
085|
085| Label.border → -bordercolor, -relief, -borderwidth
085| Label.padding → -padding
085| Label.label → -foreground, -font, -compound, -anchor, -justify, -text, -image
085|
085| Tip:
085| To change a style option globally for all TLabel widgets:
085|
085| Pythonstyle = ttk.Style()
085| style.configure("TLabel", foreground="blue", font=("Arial", 12, "bold"))
085|
085| '''
086| buf = []
087|
088| def get_layout_elements ():
089| style = ttk.Style()
090|
091|
092| layout = style.layout(widget_name)
093| buf.append(f"{widget_name} layout elements: {layout}")
094|
095|
096| def extract_elements(layout_part):
097| '''Recursive!'''
098| elements = []
099| for item in layout_part:
100| if isinstance(item, tuple):
101| element_name, opts = item
102| elements.append(element_name)
103| if "children" in opts:
104| elements.extend(extract_elements(opts["children"]))
105| return elements
106|
107| elements = extract_elements(layout)
108| buf.append(f"Elements found: {elements}")
109|
110|
111| for element in elements:
112| try:
113| opts = style.element_options(element)
114| buf.append(f"Element: {element}")
115| for opt in opts:
116| buf.append(f" - {opt}")
117|
118| except tk.TclError:
119| pass
120| buf.append(f"Element: <no options>")
121|
122| return buf
123|
124| root = tk.Tk()
125| result = get_layout_elements()
126| root.mainloop()
127|
128| return result
129|
130| """Results from vibe_get_layout_elements:
130| ####################################################################################################
130| TLabel style options: TODO
130|
130| TLabel layout elements: [(
130| 'Label.border', {
130| 'sticky': 'nswe',
130| 'border': '1',
130| 'children': [(
130| 'Label.padding', {
130| 'sticky': 'nswe',
130| 'border': '1',
130| 'children': [(
130| 'Label.label', {
130| 'sticky': 'nswe'
130| }
130| )]
130| }
130| )]
130| }
130| )]
130| Elements found: [
130| 'Label.border',
130| 'Label.padding',
130| 'Label.label'
130| ]
130| Element: Label.border
130| - relief
130| Element: Label.padding
130| - padding
130| - relief
130| - shiftrelief
130| Element: Label.label
130| - compound
130| - space
130| - text
130| - font
130| - foreground
130| - underline
130| - width
130| - anchor
130| - justify
130| - wraplength
130| - embossed
130| - image
130| - stipple
130| - background
130|
130| ####################################################################################################
130| TEntry style options:
130| foreground Text color
130| background Background color of the entry field
130| fieldbackground Background color inside the text area
130| bordercolor Border color (theme-dependent)
130| lightcolor Highlight color when focused
130| darkcolor Shadow color for 3D effect
130| padding Internal padding
130| relief Border style (flat, raised, sunken, etc.)
130| font Font family, size, and style
130|
130| TEntry layout elements: [(
130| 'Entry.field', {
130| 'sticky': 'nswe', 'children': [(
130| 'Entry.background', {
130| 'sticky': 'nswe',
130| 'children': [(
130| 'Entry.padding', {
130| 'sticky': 'nswe',
130| 'children': [(
130| 'Entry.textarea', {
130| 'sticky': 'nswe'
130| }
130| )]
130| }
130| )]
130| }
130| )]
130| }
130| )]
130| Elements found: [
130| 'Entry.field',
130| 'Entry.background',
130| 'Entry.padding',
130| 'Entry.textarea'
130| ]
130| Element: Entry.field
130| Element: Entry.background
130| Element: Entry.padding
130| - padding
130| - relief
130| - shiftrelief
130| Element: Entry.textarea
130| - font
130| - width
130|
130| ####################################################################################################
130| TButton layout elements: [(
130| 'Button.button', {
130| 'sticky': 'nswe', 'children': [(
130| 'Button.focus', {
130| 'sticky': 'nswe',
130| 'children': [(
130| 'Button.padding', {
130| 'sticky': 'nswe',
130| 'children': [(
130| 'Button.label', {
130| 'sticky': 'nswe'
130| }
130| )]
130| }
130| )]
130| }
130| )]
130| }
130| )]
130| Elements found: [
130| 'Button.button',
130| 'Button.focus',
130| 'Button.padding',
130| 'Button.label'
130| ]
130| Element: Button.button
130| Element: Button.focus
130| Element: Button.padding
130| - padding
130| - relief
130| - shiftrelief
130| Element: Button.label
130| - compound
130| - space
130| - text
130| - font
130| - foreground
130| - underline
130| - width
130| - anchor
130| - justify
130| - wraplength
130| - embossed
130| - image
130| - stipple
130| - background
130|
130| """
131|
132|
133| '''eof'''
134|