sysmon_pytk.widgets
Various Tk widgets.
1# SPDX-FileCopyrightText: © 2024 Stacey Adams <stacey.belle.rose@gmail.com> 2# SPDX-License-Identifier: MIT 3 4""" 5Various Tk widgets. 6""" 7 8from . import buttons, meters 9from .autoscrollbar import AutoScrollbar 10from .dropdown import DropDown 11from .edit_menu import EditMenu, EditMenuImages 12from .meter import Meter 13from .scalespinner import ScaleSpinner 14from .scrolling_text import ScrollingText 15from .tooltip import TempToolTip, TextToolTip, ToolTip 16from .url_label import UrlLabel 17 18__all__ = [ 19 "AutoScrollbar", 20 "DropDown", 21 "EditMenuImages", 22 "EditMenu", 23 "Meter", 24 "ScaleSpinner", 25 "ScrollingText", 26 "ToolTip", 27 "TempToolTip", 28 "TextToolTip", 29 "UrlLabel", 30 "buttons", 31 "meters", 32]
23class AutoScrollbar(ttk.Scrollbar): # pylint: disable=too-many-ancestors 24 """ 25 A scrollbar that automatically removes itself when not needed. 26 """ 27 28 def set(self, first: Any, last: Any) -> None: # noqa: ANN401 29 """ 30 Set the fractional values of the slider position. 31 32 Parameters 33 ---------- 34 first : Any 35 A string representation of a float, between 0 and 1. 36 last : Any 37 A string representation of a float, between 0 and 1. 38 """ 39 if float(first) <= 0 and float(last) >= 1: 40 self.grid_remove() 41 else: 42 self.grid() 43 super().set(first, last) 44 45 def pack(self, **_kwargs): # noqa: ANN201 46 """ 47 Disable pack for this widget. 48 """ 49 msg = "cannot use pack with this widget" 50 raise TclError(msg) 51 52 def place(self, **_kwargs): # noqa: ANN201 53 """ 54 Disable place for this widget. 55 """ 56 msg = "cannot use place with this widget" 57 raise TclError(msg) 58 59 @classmethod 60 def add_to_widget( 61 cls, widget: ScrollableWidget, orient: Literal["horizontal", "vertical"], 62 **kwargs 63 ) -> Self: 64 """ 65 Add a scrollbar to a scrollable widget. 66 67 Parameters 68 ---------- 69 widget : ScrollableWidget 70 The parent widget that will be linked to this scrollbar. 71 orient : Literal["horizontal", "vertical"] 72 The scrollbar orientation: horizontal or vertical. 73 **kwargs : dict, optional 74 Arguments to pass to parent `Scrollbar` class. 75 """ 76 scroller = cls(widget.master, orient=orient, **kwargs) 77 if orient == "horizontal": 78 scroller.config(command=widget.xview) 79 widget.config(xscrollcommand=scroller.set) 80 else: 81 scroller.config(command=widget.yview) 82 widget.config(yscrollcommand=scroller.set) 83 return scroller
A scrollbar that automatically removes itself when not needed.
28 def set(self, first: Any, last: Any) -> None: # noqa: ANN401 29 """ 30 Set the fractional values of the slider position. 31 32 Parameters 33 ---------- 34 first : Any 35 A string representation of a float, between 0 and 1. 36 last : Any 37 A string representation of a float, between 0 and 1. 38 """ 39 if float(first) <= 0 and float(last) >= 1: 40 self.grid_remove() 41 else: 42 self.grid() 43 super().set(first, last)
Set the fractional values of the slider position.
Parameters
- first (Any): A string representation of a float, between 0 and 1.
- last (Any): A string representation of a float, between 0 and 1.
45 def pack(self, **_kwargs): # noqa: ANN201 46 """ 47 Disable pack for this widget. 48 """ 49 msg = "cannot use pack with this widget" 50 raise TclError(msg)
Disable pack for this widget.
52 def place(self, **_kwargs): # noqa: ANN201 53 """ 54 Disable place for this widget. 55 """ 56 msg = "cannot use place with this widget" 57 raise TclError(msg)
Disable place for this widget.
59 @classmethod 60 def add_to_widget( 61 cls, widget: ScrollableWidget, orient: Literal["horizontal", "vertical"], 62 **kwargs 63 ) -> Self: 64 """ 65 Add a scrollbar to a scrollable widget. 66 67 Parameters 68 ---------- 69 widget : ScrollableWidget 70 The parent widget that will be linked to this scrollbar. 71 orient : Literal["horizontal", "vertical"] 72 The scrollbar orientation: horizontal or vertical. 73 **kwargs : dict, optional 74 Arguments to pass to parent `Scrollbar` class. 75 """ 76 scroller = cls(widget.master, orient=orient, **kwargs) 77 if orient == "horizontal": 78 scroller.config(command=widget.xview) 79 widget.config(xscrollcommand=scroller.set) 80 else: 81 scroller.config(command=widget.yview) 82 widget.config(yscrollcommand=scroller.set) 83 return scroller
Add a scrollbar to a scrollable widget.
Parameters
- widget (ScrollableWidget): The parent widget that will be linked to this scrollbar.
- orient (Literal["horizontal", "vertical"]): The scrollbar orientation: horizontal or vertical.
- **kwargs (dict, optional):
Arguments to pass to parent
Scrollbarclass.
Inherited Members
- tkinter.ttk.Scrollbar
- Scrollbar
- tkinter.ttk.Widget
- identify
- instate
- state
- tkinter.Scrollbar
- activate
- delta
- fraction
- get
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_clear
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- bind
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_names
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- tkinter.Place
- place_configure
- place_forget
- place_info
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location
21class DropDown(ttk.Combobox): 22 """ 23 A Combobox that takes a dict for values. 24 25 Dict keys are used for display, and dict values are used for the 26 value set or returned. 27 28 Attributes 29 ---------- 30 dictionary : dict 31 The dictionary to use in the dropdown. 32 """ 33 34 def __init__(self, parent: BaseWidget, dictionary: dict, **kwargs) -> None: 35 """ 36 Construct a dropdown widget. 37 38 Parameters 39 ---------- 40 parent : BaseWidget 41 The parent widget. 42 dictionary : dict 43 The dictionary to use in the dropdown. 44 **kwargs : dict, optional 45 Additional keyword arguments for a `Combobox`. 46 """ 47 super().__init__( 48 parent, values=sorted(dictionary.keys()), **kwargs 49 ) 50 self.dictionary = dictionary 51 52 def get(self) -> str: 53 """ 54 Get the selected value of the dropdown. 55 """ 56 key = super().get() 57 return self.dictionary[key] if key else "" 58 59 def set(self, value: str) -> None: 60 """ 61 Set the value of the dropdown, if value is found in the dictionary. 62 """ 63 keys = [key for key, val in self.dictionary.items() if val == value] 64 if len(keys) > 0: 65 super().set(keys[0])
A Combobox that takes a dict for values.
Dict keys are used for display, and dict values are used for the value set or returned.
Attributes
- dictionary (dict): The dictionary to use in the dropdown.
34 def __init__(self, parent: BaseWidget, dictionary: dict, **kwargs) -> None: 35 """ 36 Construct a dropdown widget. 37 38 Parameters 39 ---------- 40 parent : BaseWidget 41 The parent widget. 42 dictionary : dict 43 The dictionary to use in the dropdown. 44 **kwargs : dict, optional 45 Additional keyword arguments for a `Combobox`. 46 """ 47 super().__init__( 48 parent, values=sorted(dictionary.keys()), **kwargs 49 ) 50 self.dictionary = dictionary
Construct a dropdown widget.
Parameters
- parent (BaseWidget): The parent widget.
- dictionary (dict): The dictionary to use in the dropdown.
- **kwargs (dict, optional):
Additional keyword arguments for a
Combobox.
52 def get(self) -> str: 53 """ 54 Get the selected value of the dropdown. 55 """ 56 key = super().get() 57 return self.dictionary[key] if key else ""
Get the selected value of the dropdown.
59 def set(self, value: str) -> None: 60 """ 61 Set the value of the dropdown, if value is found in the dictionary. 62 """ 63 keys = [key for key, val in self.dictionary.items() if val == value] 64 if len(keys) > 0: 65 super().set(keys[0])
Set the value of the dropdown, if value is found in the dictionary.
Inherited Members
- tkinter.ttk.Combobox
- current
- tkinter.ttk.Entry
- bbox
- identify
- validate
- tkinter.ttk.Widget
- instate
- state
- tkinter.Entry
- delete
- icursor
- index
- insert
- scan_mark
- scan_dragto
- selection_adjust
- select_adjust
- selection_clear
- select_clear
- selection_from
- select_from
- selection_present
- select_present
- selection_range
- select_range
- selection_to
- select_to
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- bind
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_names
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- pack
- tkinter.Place
- place_configure
- place_forget
- place_info
- place
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location
- tkinter.XView
- xview
- xview_moveto
- xview_scroll
20@dataclasses.dataclass 21class EditMenuImages: 22 """ 23 Images used for the Edit Menu. 24 """ 25 26 cut: tk.PhotoImage 27 """Image for Cut.""" 28 copy: tk.PhotoImage 29 """Image for Copy.""" 30 paste: tk.PhotoImage 31 """Image for Paste.""" 32 select_all: tk.PhotoImage 33 """Image for Select All."""
Images used for the Edit Menu.
36class EditMenu(tk.Menu): 37 """ 38 Standard Edit Menu with Cut/Copy/Paste/Select All items. 39 40 Attributes 41 ---------- 42 images : `EditMenuImages` 43 A collection of images needed for the menu. 44 """ 45 46 def __init__(self, master: tk.Text, **kwarg) -> None: 47 """ 48 Construct an edit menu for a Text widget. 49 50 Parameters 51 ---------- 52 master : tk.Text 53 The parent Text widget. 54 **kwarg : dict, optional 55 Additional keyword arguments for a `Menu`. 56 """ 57 self.master: tk.Text = master 58 super().__init__(master, **kwarg) 59 self.images = EditMenuImages( 60 cut=tk.PhotoImage(file=get_full_path("images/edit-cut.png")), 61 copy=tk.PhotoImage(file=get_full_path("images/edit-copy.png")), 62 paste=tk.PhotoImage(file=get_full_path("images/edit-paste.png")), 63 select_all=tk.PhotoImage(file=get_full_path("images/edit-select-all.png")) 64 ) 65 self.add_command( 66 label=_("Cut"), command=self.cut, accelerator=_("Ctrl+X"), 67 compound=tk.LEFT, image=self.images.cut 68 ) 69 self.add_command( 70 label=_("Copy"), command=self.copy, accelerator=_("Ctrl+C"), 71 compound=tk.LEFT, image=self.images.copy 72 ) 73 self.add_command( 74 label=_("Paste"), command=self.paste, accelerator=_("Ctrl+V"), 75 compound=tk.LEFT, image=self.images.paste 76 ) 77 self.add_separator() 78 self.add_command( 79 label=_("Select All"), command=self.select_all, 80 accelerator=_("Ctrl+A"), compound=tk.LEFT, image=self.images.select_all 81 ) 82 self.master.bind("<Button-3>", self.show_popup) 83 self.master.bind("<Control-X>", self.cut) 84 self.master.bind("<Control-C>", self.copy) 85 self.master.bind("<Control-V>", self.paste) 86 self.master.bind("<Control-A>", self.select_all) 87 88 def show_popup(self, event: tk.Event) -> None: 89 """ 90 Show the edit menu. 91 """ 92 if self.focus_get() != self: 93 self.focus_set() 94 if self.master.cget("state") == tk.DISABLED: 95 self.entryconfigure(_("Cut"), state=tk.DISABLED) 96 self.entryconfigure(_("Paste"), state=tk.DISABLED) 97 else: 98 self.entryconfigure(_("Cut"), state=tk.NORMAL) 99 self.entryconfigure(_("Paste"), state=tk.NORMAL) 100 self.tk_popup(event.x_root, event.y_root, 0) 101 102 def cut(self, *_args) -> None: 103 """ 104 Generate a Cut Text event. 105 """ 106 if self.master.cget("state") == tk.NORMAL: 107 self.master.event_generate("<<Cut>>") 108 109 def copy(self, *_args) -> None: 110 """ 111 Generate a Copy Text event. 112 """ 113 self.master.event_generate("<<Copy>>") 114 115 def paste(self, *_args) -> None: 116 """ 117 Generate a Paste Text event. 118 """ 119 if self.master.cget("state") == tk.NORMAL: 120 self.master.event_generate("<<Paste>>") 121 122 def select_all(self, *_args) -> None: 123 """ 124 Select all the text in the Text widget. 125 """ 126 self.master.tag_add(tk.SEL, "1.0", "end-1c")
Standard Edit Menu with Cut/Copy/Paste/Select All items.
Attributes
- images (
EditMenuImages): A collection of images needed for the menu.
46 def __init__(self, master: tk.Text, **kwarg) -> None: 47 """ 48 Construct an edit menu for a Text widget. 49 50 Parameters 51 ---------- 52 master : tk.Text 53 The parent Text widget. 54 **kwarg : dict, optional 55 Additional keyword arguments for a `Menu`. 56 """ 57 self.master: tk.Text = master 58 super().__init__(master, **kwarg) 59 self.images = EditMenuImages( 60 cut=tk.PhotoImage(file=get_full_path("images/edit-cut.png")), 61 copy=tk.PhotoImage(file=get_full_path("images/edit-copy.png")), 62 paste=tk.PhotoImage(file=get_full_path("images/edit-paste.png")), 63 select_all=tk.PhotoImage(file=get_full_path("images/edit-select-all.png")) 64 ) 65 self.add_command( 66 label=_("Cut"), command=self.cut, accelerator=_("Ctrl+X"), 67 compound=tk.LEFT, image=self.images.cut 68 ) 69 self.add_command( 70 label=_("Copy"), command=self.copy, accelerator=_("Ctrl+C"), 71 compound=tk.LEFT, image=self.images.copy 72 ) 73 self.add_command( 74 label=_("Paste"), command=self.paste, accelerator=_("Ctrl+V"), 75 compound=tk.LEFT, image=self.images.paste 76 ) 77 self.add_separator() 78 self.add_command( 79 label=_("Select All"), command=self.select_all, 80 accelerator=_("Ctrl+A"), compound=tk.LEFT, image=self.images.select_all 81 ) 82 self.master.bind("<Button-3>", self.show_popup) 83 self.master.bind("<Control-X>", self.cut) 84 self.master.bind("<Control-C>", self.copy) 85 self.master.bind("<Control-V>", self.paste) 86 self.master.bind("<Control-A>", self.select_all)
Construct an edit menu for a Text widget.
Parameters
- master (tk.Text): The parent Text widget.
- **kwarg (dict, optional):
Additional keyword arguments for a
Menu.
88 def show_popup(self, event: tk.Event) -> None: 89 """ 90 Show the edit menu. 91 """ 92 if self.focus_get() != self: 93 self.focus_set() 94 if self.master.cget("state") == tk.DISABLED: 95 self.entryconfigure(_("Cut"), state=tk.DISABLED) 96 self.entryconfigure(_("Paste"), state=tk.DISABLED) 97 else: 98 self.entryconfigure(_("Cut"), state=tk.NORMAL) 99 self.entryconfigure(_("Paste"), state=tk.NORMAL) 100 self.tk_popup(event.x_root, event.y_root, 0)
Show the edit menu.
102 def cut(self, *_args) -> None: 103 """ 104 Generate a Cut Text event. 105 """ 106 if self.master.cget("state") == tk.NORMAL: 107 self.master.event_generate("<<Cut>>")
Generate a Cut Text event.
109 def copy(self, *_args) -> None: 110 """ 111 Generate a Copy Text event. 112 """ 113 self.master.event_generate("<<Copy>>")
Generate a Copy Text event.
115 def paste(self, *_args) -> None: 116 """ 117 Generate a Paste Text event. 118 """ 119 if self.master.cget("state") == tk.NORMAL: 120 self.master.event_generate("<<Paste>>")
Generate a Paste Text event.
122 def select_all(self, *_args) -> None: 123 """ 124 Select all the text in the Text widget. 125 """ 126 self.master.tag_add(tk.SEL, "1.0", "end-1c")
Select all the text in the Text widget.
Inherited Members
- tkinter.Menu
- tk_popup
- activate
- add
- add_cascade
- add_command
- add_separator
- insert
- insert_cascade
- insert_command
- insert_separator
- delete
- entrycget
- entryconfigure
- entryconfig
- index
- invoke
- post
- type
- unpost
- xposition
- yposition
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_clear
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- bind
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_names
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- pack
- tkinter.Place
- place_configure
- place_forget
- place_info
- place
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location
42class Meter(tk.Frame): 43 """ 44 Shows a meter widget, like a speedometer. 45 """ 46 47 GREEN = "#0a0" 48 YELLOW = "#dd0" 49 RED = "#d00" 50 BLUE = "#00a" 51 52 START_ANGLE = 36 53 EXTENT_ANGLE = 180 - 2*START_ANGLE 54 55 def __init__( 56 self, parent: Misc, *, 57 width: int = 300, height: int = 225, 58 min_value: float = 0.0, max_value: float = 100.0, 59 label: str = "", unit: str = "", 60 divisions: int = 10, yellow: float = 15, 61 red: float = 15, blue: float = 0, **kw 62 ) -> None: 63 """ 64 Construct a meter widget. 65 66 Parameters 67 ---------- 68 parent : Misc 69 The parent widget. 70 width : int, default = 300 71 The width of the meter widget. 72 height : int, default = 225 73 The height of the meter widget. 74 min_value : float, default = 0.0 75 The minimum value to display on the meter. 76 max_value : float, default = 100.0 77 The maximum value to display on the meter. 78 label : str, default = "" 79 The label to display above the meter. 80 unit : str, default = "" 81 The units, used when displaying numbers on the meter. 82 divisions : int, default = 10 83 The number of divisions between the start and end of the meter. 84 yellow : float, default = 15 85 The percent of the meter to show in yellow. Appears just before red. 86 red : float, default = 15 87 The percent of the meter to show in red. Appears at the max values. 88 blue : float, default = 0 89 The percent of the meter to show in blue. Appears at the min values. 90 **kw : dict, optional 91 Arguments to pass to parent `Frame` class. 92 """ 93 self._unit = unit 94 self._min_value = min_value 95 self._max_value = max_value 96 self._width = width 97 self._height = height 98 self._divisions = divisions 99 self.range = {"blue": blue, "yellow": yellow, "red": red} 100 self.check_dark_mode() 101 super().__init__(parent, background=self._background, class_="Meter", **kw) 102 self.var = tk.DoubleVar(self, 0) 103 self.rowconfigure(0, weight=1) 104 self.columnconfigure(0, weight=1) 105 # This `canvas_holder` frame is to keep the canvas centered in the widget. 106 canvas_holder = tk.Frame(self) 107 canvas_holder.grid() 108 self.canvas = tk.Canvas( 109 canvas_holder, 110 width=width, 111 height=height, 112 background=self._background, 113 borderwidth=0, 114 highlightthickness=0 115 ) 116 self.canvas_objects = CanvasObjects() 117 self._add_labels(label, unit) 118 self._add_gauge_lines(red, yellow, blue) 119 self._add_inset() 120 self._update_meter_line(Meter.EXTENT_ANGLE + Meter.START_ANGLE) 121 self.var.trace_add("write", self._update_meter) 122 self.canvas.grid(sticky=tk.EW) 123 124 def _add_labels(self, label: str, unit: str) -> None: 125 font_size_lg = int(self._height / 15) 126 font_size_sm = int(self._height / 20) 127 text_font = modify_named_font("TkDefaultFont", size=font_size_lg) 128 large_font = modify_named_font("TkFixedFont", size=font_size_lg) 129 small_font = modify_named_font("TkFixedFont", size=font_size_sm) 130 # Add text: label, mix, max, current 131 self.canvas_objects.label1 = self.canvas.create_text( 132 self._width / 2, self._height / 10, 133 font=text_font, text=label, fill=self._text_color 134 ) 135 self.canvas_objects.min_value = self.canvas.create_text( 136 self._width / 6, self._height * 0.55, 137 font=small_font, text=f"{int(self._min_value)}{unit}", 138 fill=self._text_color, anchor=tk.NE, justify=tk.RIGHT 139 ) 140 self.canvas_objects.max_value = self.canvas.create_text( 141 self._width * 5 / 6, self._height * 0.55, 142 font=small_font, text=f"{int(self._max_value)}{unit}", 143 fill=self._text_color, anchor=tk.NW, justify=tk.LEFT 144 ) 145 self.canvas_objects.current = self.canvas.create_text( 146 self._width / 2, self._height - 1.75*font_size_lg, 147 font=large_font, text=f"{self.var.get()}{self._unit}", 148 fill=self._text_color, anchor=tk.N, justify=tk.CENTER 149 ) 150 151 def _add_gauge_lines(self, red: float, yellow: float, blue: float) -> None: 152 coord = ( 153 self._width / 30, self._height / 4, 154 self._width * 29 / 30, self._height * 1.5 155 ) 156 # Add the divisions 157 self.canvas_objects.wedges = [] 158 for i in range(self._divisions): 159 self.canvas_objects.wedges.append(self.canvas.create_arc( 160 coord, width=1, outline=self._text_color, 161 start=(i * (Meter.EXTENT_ANGLE / self._divisions) + Meter.START_ANGLE), 162 extent=(Meter.EXTENT_ANGLE / self._divisions) 163 )) 164 165 # Add the color scale arcs 166 self.canvas.create_arc( 167 coord, extent=Meter.EXTENT_ANGLE, start=Meter.START_ANGLE, 168 style="arc", outline=self.GREEN, width=self._width / 12 169 ) 170 if red > 0: 171 self.canvas.create_arc( 172 coord, extent=self._percent_to_degrees(red), start=Meter.START_ANGLE, 173 style="arc", outline=self.RED, width=self._width / 12 174 ) 175 if yellow > 0: 176 self.canvas.create_arc( 177 coord, extent=self._percent_to_degrees(yellow), 178 start=self._percent_to_degrees(red) + Meter.START_ANGLE, 179 style="arc", outline=self.YELLOW, width=self._width / 12 180 ) 181 if blue > 0: 182 self.canvas.create_arc( 183 coord, start=Meter.EXTENT_ANGLE + Meter.START_ANGLE, 184 extent=-self._percent_to_degrees(blue), 185 style="arc", outline=self.BLUE, width=self._width / 12 186 ) 187 188 # Add the moving indicator line 189 self.canvas_objects.meter = self.canvas.create_arc( 190 coord, start=Meter.EXTENT_ANGLE + Meter.START_ANGLE, extent=1, 191 fill=self._meter_color, outline=self._meter_color, width=3 192 ) 193 194 def _add_inset(self) -> None: 195 # Add the inset 196 inset_coord = ( 197 self._width * 23 / 60, self._height * 23 / 32, 198 self._width * 37 / 60, self._height * 33 / 32 199 ) 200 self.canvas_objects.inset = self.canvas.create_arc( 201 inset_coord, start=Meter.START_ANGLE, extent=Meter.EXTENT_ANGLE, 202 fill=self._text_color, outline=self._text_color, width=2 203 ) 204 self.canvas_objects.inset_border = self.canvas.create_arc( 205 inset_coord, start=Meter.START_ANGLE, extent=Meter.EXTENT_ANGLE, 206 outline=self._meter_color, style="arc", width=1 207 ) 208 209 def check_dark_mode(self) -> None: 210 """ 211 Detect whether using dark mode and adjust base colors. 212 """ 213 style = ttk.Style() 214 self._text_color = style.lookup("TLabel", "foreground") 215 self._background = style.lookup("TLabel", "background") 216 self._meter_color = StyleManager.test_dark_mode("#cccccc", "#666666") 217 self._meter_red = StyleManager.test_dark_mode("#ff2222", "#cc0000") 218 self._meter_yellow = StyleManager.test_dark_mode("#ffff22", "#cccc00") 219 self._meter_blue = StyleManager.test_dark_mode("#2222ff", "#0000cc") 220 221 def update_for_dark_mode(self) -> None: 222 """ 223 Update the meter colors based on detected dark mode. 224 """ 225 self.check_dark_mode() 226 self.canvas.config(background=self._background) 227 self.canvas.itemconfig(self.canvas_objects.label1, fill=self._text_color) 228 self.canvas.itemconfig(self.canvas_objects.min_value, fill=self._text_color) 229 self.canvas.itemconfig(self.canvas_objects.max_value, fill=self._text_color) 230 self.canvas.itemconfig(self.canvas_objects.current, fill=self._text_color) 231 self.canvas.itemconfig(self.canvas_objects.meter, fill=self._meter_color) 232 self.canvas.itemconfig(self.canvas_objects.meter, outline=self._meter_color) 233 self.canvas.itemconfig(self.canvas_objects.inset, fill=self._text_color) 234 self.canvas.itemconfig(self.canvas_objects.inset, outline=self._text_color) 235 self.canvas.itemconfig(self.canvas_objects.inset_border, outline=self._text_color) 236 for wedge in self.canvas_objects.wedges: 237 self.canvas.itemconfig(wedge, outline=self._text_color) 238 239 def _update_meter_line(self, angle: float) -> None: 240 """ 241 Update the meter line indicator. 242 """ 243 self.canvas.itemconfig(self.canvas_objects.meter, start=angle) 244 self.canvas.itemconfig(self.canvas_objects.current, text=f"{self.var.get()}{self._unit}") 245 246 def _update_meter(self, _name1, _name2, _op) -> None: 247 """ 248 Update the meter display based on the updated variable. 249 """ 250 pct = (self.var.get() - self._min_value)/(self._max_value - self._min_value) 251 if pct * 100 < self.range["blue"]: 252 self.canvas.itemconfig(self.canvas_objects.meter, fill=self._meter_blue) 253 self.canvas.itemconfig(self.canvas_objects.meter, outline=self._meter_blue) 254 elif pct * 100 > 100 - self.range["red"]: 255 self.canvas.itemconfig(self.canvas_objects.meter, fill=self._meter_red) 256 self.canvas.itemconfig(self.canvas_objects.meter, outline=self._meter_red) 257 elif pct * 100 > 100 - self.range["red"] - self.range["yellow"]: 258 self.canvas.itemconfig(self.canvas_objects.meter, fill=self._meter_yellow) 259 self.canvas.itemconfig(self.canvas_objects.meter, outline=self._meter_yellow) 260 else: 261 self.canvas.itemconfig(self.canvas_objects.meter, fill=self._meter_color) 262 self.canvas.itemconfig(self.canvas_objects.meter, outline=self._meter_color) 263 angle = (1 - pct) * Meter.EXTENT_ANGLE + Meter.START_ANGLE 264 self._update_meter_line(angle) 265 266 @classmethod 267 def _percent_to_degrees(cls, pct: float) -> float: 268 return float(Meter.EXTENT_ANGLE) * pct / 100 269 270 def set_value(self, value: float) -> None: 271 """ 272 Set the value to display on the meter. 273 """ 274 self.var.set(value) 275 276 def bind(self, sequence=None, func=None, add=None): # noqa: ANN001,ANN201 277 """ 278 Pass events through to the canvas, since frames don't normally respond to them. 279 """ 280 return self.canvas.bind(sequence, func, add)
Shows a meter widget, like a speedometer.
55 def __init__( 56 self, parent: Misc, *, 57 width: int = 300, height: int = 225, 58 min_value: float = 0.0, max_value: float = 100.0, 59 label: str = "", unit: str = "", 60 divisions: int = 10, yellow: float = 15, 61 red: float = 15, blue: float = 0, **kw 62 ) -> None: 63 """ 64 Construct a meter widget. 65 66 Parameters 67 ---------- 68 parent : Misc 69 The parent widget. 70 width : int, default = 300 71 The width of the meter widget. 72 height : int, default = 225 73 The height of the meter widget. 74 min_value : float, default = 0.0 75 The minimum value to display on the meter. 76 max_value : float, default = 100.0 77 The maximum value to display on the meter. 78 label : str, default = "" 79 The label to display above the meter. 80 unit : str, default = "" 81 The units, used when displaying numbers on the meter. 82 divisions : int, default = 10 83 The number of divisions between the start and end of the meter. 84 yellow : float, default = 15 85 The percent of the meter to show in yellow. Appears just before red. 86 red : float, default = 15 87 The percent of the meter to show in red. Appears at the max values. 88 blue : float, default = 0 89 The percent of the meter to show in blue. Appears at the min values. 90 **kw : dict, optional 91 Arguments to pass to parent `Frame` class. 92 """ 93 self._unit = unit 94 self._min_value = min_value 95 self._max_value = max_value 96 self._width = width 97 self._height = height 98 self._divisions = divisions 99 self.range = {"blue": blue, "yellow": yellow, "red": red} 100 self.check_dark_mode() 101 super().__init__(parent, background=self._background, class_="Meter", **kw) 102 self.var = tk.DoubleVar(self, 0) 103 self.rowconfigure(0, weight=1) 104 self.columnconfigure(0, weight=1) 105 # This `canvas_holder` frame is to keep the canvas centered in the widget. 106 canvas_holder = tk.Frame(self) 107 canvas_holder.grid() 108 self.canvas = tk.Canvas( 109 canvas_holder, 110 width=width, 111 height=height, 112 background=self._background, 113 borderwidth=0, 114 highlightthickness=0 115 ) 116 self.canvas_objects = CanvasObjects() 117 self._add_labels(label, unit) 118 self._add_gauge_lines(red, yellow, blue) 119 self._add_inset() 120 self._update_meter_line(Meter.EXTENT_ANGLE + Meter.START_ANGLE) 121 self.var.trace_add("write", self._update_meter) 122 self.canvas.grid(sticky=tk.EW)
Construct a meter widget.
Parameters
- parent (Misc): The parent widget.
- width (int, default = 300): The width of the meter widget.
- height (int, default = 225): The height of the meter widget.
- min_value (float, default = 0.0): The minimum value to display on the meter.
- max_value (float, default = 100.0): The maximum value to display on the meter.
- label (str, default = ""): The label to display above the meter.
- unit (str, default = ""): The units, used when displaying numbers on the meter.
- divisions (int, default = 10): The number of divisions between the start and end of the meter.
- yellow (float, default = 15): The percent of the meter to show in yellow. Appears just before red.
- red (float, default = 15): The percent of the meter to show in red. Appears at the max values.
- blue (float, default = 0): The percent of the meter to show in blue. Appears at the min values.
- **kw (dict, optional):
Arguments to pass to parent
Frameclass.
209 def check_dark_mode(self) -> None: 210 """ 211 Detect whether using dark mode and adjust base colors. 212 """ 213 style = ttk.Style() 214 self._text_color = style.lookup("TLabel", "foreground") 215 self._background = style.lookup("TLabel", "background") 216 self._meter_color = StyleManager.test_dark_mode("#cccccc", "#666666") 217 self._meter_red = StyleManager.test_dark_mode("#ff2222", "#cc0000") 218 self._meter_yellow = StyleManager.test_dark_mode("#ffff22", "#cccc00") 219 self._meter_blue = StyleManager.test_dark_mode("#2222ff", "#0000cc")
Detect whether using dark mode and adjust base colors.
221 def update_for_dark_mode(self) -> None: 222 """ 223 Update the meter colors based on detected dark mode. 224 """ 225 self.check_dark_mode() 226 self.canvas.config(background=self._background) 227 self.canvas.itemconfig(self.canvas_objects.label1, fill=self._text_color) 228 self.canvas.itemconfig(self.canvas_objects.min_value, fill=self._text_color) 229 self.canvas.itemconfig(self.canvas_objects.max_value, fill=self._text_color) 230 self.canvas.itemconfig(self.canvas_objects.current, fill=self._text_color) 231 self.canvas.itemconfig(self.canvas_objects.meter, fill=self._meter_color) 232 self.canvas.itemconfig(self.canvas_objects.meter, outline=self._meter_color) 233 self.canvas.itemconfig(self.canvas_objects.inset, fill=self._text_color) 234 self.canvas.itemconfig(self.canvas_objects.inset, outline=self._text_color) 235 self.canvas.itemconfig(self.canvas_objects.inset_border, outline=self._text_color) 236 for wedge in self.canvas_objects.wedges: 237 self.canvas.itemconfig(wedge, outline=self._text_color)
Update the meter colors based on detected dark mode.
270 def set_value(self, value: float) -> None: 271 """ 272 Set the value to display on the meter. 273 """ 274 self.var.set(value)
Set the value to display on the meter.
276 def bind(self, sequence=None, func=None, add=None): # noqa: ANN001,ANN201 277 """ 278 Pass events through to the canvas, since frames don't normally respond to them. 279 """ 280 return self.canvas.bind(sequence, func, add)
Pass events through to the canvas, since frames don't normally respond to them.
Inherited Members
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_clear
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_names
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- pack
- tkinter.Place
- place_configure
- place_forget
- place_info
- place
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location
24class ScaleSpinner(ttk.Frame): 25 """ 26 Combination of a Scale and Spinbox, with an optional Label. 27 28 Attributes 29 ---------- 30 variable : Variable 31 The control variable which maintains the selected value. 32 as_int : bool 33 A flag indicating whether to round the values from the `Scale`. 34 scale : Scale 35 The `Scale` widget managed by this widget. 36 spinbox : Spinbox 37 The `Spinbox` widget managed by this widget. 38 """ 39 40 def __init__( 41 self, parent: BaseWidget, variable: Variable, *, 42 text: str | None = None, length: int = 100, from_: float = 0, 43 to: float = 100, as_int: bool = False, **kwargs 44 ) -> None: 45 """ 46 Construct a frame containing a Scale, a Spinbox, and an optional Label. 47 48 Parameters 49 ---------- 50 parent : BaseWidget 51 The parent widget. 52 variable : Variable 53 The control variable which maintains the selected value. 54 text : str, optional 55 The text to display as a `Label`. 56 length : int, default = 100 57 The length of the `Scale` widget. 58 from_ : float, default = 0.0 59 The smallest value allowed for the `Scale` and `Spinbox`. 60 to : float, default = 100.0 61 The largest value allowed for the `Scale` and `Spinbox`. 62 as_int : bool, default = False 63 A flag indicating whether to round the values from the `Scale`. 64 **kwargs : dict, optional 65 Arguments to pass to parent `Frame` class. 66 """ 67 super().__init__(parent, **kwargs) 68 self.variable = variable 69 self.as_int = as_int 70 self.rowconfigure(0, weight=1) 71 self.columnconfigure(1, weight=1) 72 base_font = StyleManager.get_base_font() 73 if text is not None: 74 ttk.Label( 75 self, text=text, anchor=tk.W, font=base_font 76 ).grid(row=0, column=0, sticky=tk.NSEW) 77 self.scale = ttk.Scale( 78 self, orient=tk.HORIZONTAL, length=length, from_=from_, to=to, 79 style="Tick.TScale" 80 ) 81 self.scale.grid(row=0, column=1, pady=10, padx=10, sticky=tk.NSEW) 82 self.scale.set(variable.get()) 83 self.spinbox = ttk.Spinbox( 84 self, textvariable=variable, from_=from_, to=to, 85 width=len(f"{to}")+3, state="readonly", font=base_font, 86 command=self.update_from_spinbox 87 ) 88 self.spinbox.grid(row=0, column=2, sticky=tk.EW) 89 self.scale.configure(command=self.update_from_scale) 90 91 def update_from_spinbox(self) -> None: 92 """ 93 Update font size from spinbox. 94 """ 95 self.scale.set(self.variable.get()) 96 97 def update_from_scale(self, size: str) -> None: 98 """ 99 Update font size from scale widget. 100 """ 101 self.variable.set(round(float(size)) if self.as_int else float(size)) 102 self.spinbox.selection_clear()
Combination of a Scale and Spinbox, with an optional Label.
Attributes
- variable (Variable): The control variable which maintains the selected value.
- as_int (bool):
A flag indicating whether to round the values from the
Scale. - scale (Scale):
The
Scalewidget managed by this widget. - spinbox (Spinbox):
The
Spinboxwidget managed by this widget.
40 def __init__( 41 self, parent: BaseWidget, variable: Variable, *, 42 text: str | None = None, length: int = 100, from_: float = 0, 43 to: float = 100, as_int: bool = False, **kwargs 44 ) -> None: 45 """ 46 Construct a frame containing a Scale, a Spinbox, and an optional Label. 47 48 Parameters 49 ---------- 50 parent : BaseWidget 51 The parent widget. 52 variable : Variable 53 The control variable which maintains the selected value. 54 text : str, optional 55 The text to display as a `Label`. 56 length : int, default = 100 57 The length of the `Scale` widget. 58 from_ : float, default = 0.0 59 The smallest value allowed for the `Scale` and `Spinbox`. 60 to : float, default = 100.0 61 The largest value allowed for the `Scale` and `Spinbox`. 62 as_int : bool, default = False 63 A flag indicating whether to round the values from the `Scale`. 64 **kwargs : dict, optional 65 Arguments to pass to parent `Frame` class. 66 """ 67 super().__init__(parent, **kwargs) 68 self.variable = variable 69 self.as_int = as_int 70 self.rowconfigure(0, weight=1) 71 self.columnconfigure(1, weight=1) 72 base_font = StyleManager.get_base_font() 73 if text is not None: 74 ttk.Label( 75 self, text=text, anchor=tk.W, font=base_font 76 ).grid(row=0, column=0, sticky=tk.NSEW) 77 self.scale = ttk.Scale( 78 self, orient=tk.HORIZONTAL, length=length, from_=from_, to=to, 79 style="Tick.TScale" 80 ) 81 self.scale.grid(row=0, column=1, pady=10, padx=10, sticky=tk.NSEW) 82 self.scale.set(variable.get()) 83 self.spinbox = ttk.Spinbox( 84 self, textvariable=variable, from_=from_, to=to, 85 width=len(f"{to}")+3, state="readonly", font=base_font, 86 command=self.update_from_spinbox 87 ) 88 self.spinbox.grid(row=0, column=2, sticky=tk.EW) 89 self.scale.configure(command=self.update_from_scale)
Construct a frame containing a Scale, a Spinbox, and an optional Label.
Parameters
- parent (BaseWidget): The parent widget.
- variable (Variable): The control variable which maintains the selected value.
- text (str, optional):
The text to display as a
Label. - length (int, default = 100):
The length of the
Scalewidget. - from_ (float, default = 0.0):
The smallest value allowed for the
ScaleandSpinbox. - to (float, default = 100.0):
The largest value allowed for the
ScaleandSpinbox. - as_int (bool, default = False):
A flag indicating whether to round the values from the
Scale. - **kwargs (dict, optional):
Arguments to pass to parent
Frameclass.
91 def update_from_spinbox(self) -> None: 92 """ 93 Update font size from spinbox. 94 """ 95 self.scale.set(self.variable.get())
Update font size from spinbox.
97 def update_from_scale(self, size: str) -> None: 98 """ 99 Update font size from scale widget. 100 """ 101 self.variable.set(round(float(size)) if self.as_int else float(size)) 102 self.spinbox.selection_clear()
Update font size from scale widget.
Inherited Members
- tkinter.ttk.Widget
- identify
- instate
- state
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_clear
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- bind
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_names
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- pack
- tkinter.Place
- place_configure
- place_forget
- place_info
- place
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location
26class ScrollingText(tk.Text): 27 """ 28 Scrollable Text Widget with standard Edit popup menu. 29 30 Attributes 31 ---------- 32 frame : Frame 33 The frame which holds this widget and its accompanying AutoScrollbar. 34 35 Notes 36 ----- 37 This Text widget is configured with several standard tags: 38 39 * `center` : Center the tagged text. 40 * `left` : Left justify the tagged text. 41 * `right` : Right justify the tagged text. 42 * `large` : apply the large font to the tagged text. 43 * `bold` : apply the bold font to the tagged text. 44 * `fixed` : apply the fixed font to the tagged text. 45 * `link` : treat the tagged text as a clickable link. 46 * `linkurl` : follows a link tag, and contains the url to open - hidden text. 47 48 To use links, insert a `link` tag with the clickable link text, and then 49 insert a `linkurl` tag containing the url to open for the previous link 50 text. The `linkurl` text will be hidden, but accessible when the user 51 clicks on the link. When the user clicks, the text position of the click 52 will be determined, from that position, the text will be searched for the 53 next occurrence of a `linkurl` tag, and that url will be opened. 54 """ 55 56 def __init__(self, master: tk.Misc | None = None, **kwargs) -> None: 57 """ 58 Construct a scrolling text widget. 59 60 Parameters 61 ---------- 62 master : Misc, optional 63 The parent widget. 64 **kwargs : dict, optional 65 Arguments to pass to parent `Text` class. 66 """ 67 self.frame = ttk.Frame(master) 68 self.frame.rowconfigure(0, weight=1) 69 self.frame.columnconfigure(0, weight=1) 70 super().__init__(self.frame, **kwargs) 71 self.grid(row=0, column=0, sticky=tk.NSEW) 72 self.configure_tags() 73 AutoScrollbar.add_to_widget(self, orient=tk.VERTICAL).grid( 74 row=0, column=1, sticky=tk.NS 75 ) 76 EditMenu( 77 self, activeborderwidth=0, # relief=tk.FLAT, 78 background=StyleManager.test_dark_mode("#444444", "#dddddd"), 79 foreground=StyleManager.test_dark_mode("#ffffff", "#000000"), 80 font=font.nametofont("TkMenuFont") 81 ) 82 83 def get_frame(self) -> ttk.Frame: 84 """ 85 Get the containing frame. 86 """ 87 return self.frame 88 89 def configure_tags(self) -> None: 90 """ 91 Configure the standard tags for the Text widget. 92 """ 93 self.tag_configure("center", justify="center") 94 self.tag_configure("left", justify="left") 95 self.tag_configure("right", justify="right") 96 self.tag_configure("large", font=StyleManager.get_large_font()) 97 self.tag_configure("bold", font=StyleManager.get_bold_font()) 98 self.tag_configure("fixed", font=StyleManager.get_fixed_font()) 99 self.tag_configure( 100 "link", foreground="#007fff", selectforeground="#007fff", 101 selectbackground="#cccccc" 102 ) 103 self.tag_configure("linkurl", elide=True) # hide the urls from display 104 self.tag_bind("link", "<Enter>", self.show_hand_cursor) 105 self.tag_bind("link", "<Leave>", self.hide_hand_cursor) 106 self.tag_bind("link", "<Button-1>", self.open_link) 107 # TODO add "Open in Browser" edit menu item when hovering over link 108 109 def show_hand_cursor(self, event: tk.Event[tk.Text]) -> None: 110 """ 111 Change the mouse cursor to a "hand", indicating a clickable link. 112 """ 113 event.widget.configure(cursor="hand2") 114 115 def hide_hand_cursor(self, event: tk.Event[tk.Text]) -> None: 116 """ 117 Change the mouse cursor to its standard form, no longer indicating a link. 118 """ 119 event.widget.configure(cursor="") 120 121 def open_link(self, event: tk.Event[tk.Text]) -> None: 122 """ 123 Open the clicked link in a web browser. 124 """ 125 click_position = f"@{event.x},{event.y}" 126 tag_range = event.widget.tag_nextrange("linkurl", click_position) 127 webbrowser.open_new_tab(event.widget.get(*tag_range))
Scrollable Text Widget with standard Edit popup menu.
Attributes
- frame (Frame): The frame which holds this widget and its accompanying AutoScrollbar.
Notes
This Text widget is configured with several standard tags:
center: Center the tagged text.left: Left justify the tagged text.right: Right justify the tagged text.large: apply the large font to the tagged text.bold: apply the bold font to the tagged text.fixed: apply the fixed font to the tagged text.link: treat the tagged text as a clickable link.linkurl: follows a link tag, and contains the url to open - hidden text.
To use links, insert a link tag with the clickable link text, and then
insert a linkurl tag containing the url to open for the previous link
text. The linkurl text will be hidden, but accessible when the user
clicks on the link. When the user clicks, the text position of the click
will be determined, from that position, the text will be searched for the
next occurrence of a linkurl tag, and that url will be opened.
56 def __init__(self, master: tk.Misc | None = None, **kwargs) -> None: 57 """ 58 Construct a scrolling text widget. 59 60 Parameters 61 ---------- 62 master : Misc, optional 63 The parent widget. 64 **kwargs : dict, optional 65 Arguments to pass to parent `Text` class. 66 """ 67 self.frame = ttk.Frame(master) 68 self.frame.rowconfigure(0, weight=1) 69 self.frame.columnconfigure(0, weight=1) 70 super().__init__(self.frame, **kwargs) 71 self.grid(row=0, column=0, sticky=tk.NSEW) 72 self.configure_tags() 73 AutoScrollbar.add_to_widget(self, orient=tk.VERTICAL).grid( 74 row=0, column=1, sticky=tk.NS 75 ) 76 EditMenu( 77 self, activeborderwidth=0, # relief=tk.FLAT, 78 background=StyleManager.test_dark_mode("#444444", "#dddddd"), 79 foreground=StyleManager.test_dark_mode("#ffffff", "#000000"), 80 font=font.nametofont("TkMenuFont") 81 )
Construct a scrolling text widget.
Parameters
- master (Misc, optional): The parent widget.
- **kwargs (dict, optional):
Arguments to pass to parent
Textclass.
83 def get_frame(self) -> ttk.Frame: 84 """ 85 Get the containing frame. 86 """ 87 return self.frame
Get the containing frame.
109 def show_hand_cursor(self, event: tk.Event[tk.Text]) -> None: 110 """ 111 Change the mouse cursor to a "hand", indicating a clickable link. 112 """ 113 event.widget.configure(cursor="hand2")
Change the mouse cursor to a "hand", indicating a clickable link.
115 def hide_hand_cursor(self, event: tk.Event[tk.Text]) -> None: 116 """ 117 Change the mouse cursor to its standard form, no longer indicating a link. 118 """ 119 event.widget.configure(cursor="")
Change the mouse cursor to its standard form, no longer indicating a link.
121 def open_link(self, event: tk.Event[tk.Text]) -> None: 122 """ 123 Open the clicked link in a web browser. 124 """ 125 click_position = f"@{event.x},{event.y}" 126 tag_range = event.widget.tag_nextrange("linkurl", click_position) 127 webbrowser.open_new_tab(event.widget.get(*tag_range))
Open the clicked link in a web browser.
Inherited Members
- tkinter.Text
- bbox
- compare
- count
- debug
- delete
- dlineinfo
- dump
- edit
- edit_modified
- edit_redo
- edit_reset
- edit_separator
- edit_undo
- get
- image_cget
- image_configure
- image_create
- image_names
- index
- insert
- mark_gravity
- mark_names
- mark_set
- mark_unset
- mark_next
- mark_previous
- peer_create
- peer_names
- replace
- scan_mark
- scan_dragto
- search
- see
- tag_add
- tag_unbind
- tag_bind
- tag_cget
- tag_configure
- tag_config
- tag_delete
- tag_lower
- tag_names
- tag_nextrange
- tag_prevrange
- tag_raise
- tag_ranges
- tag_remove
- window_cget
- window_configure
- window_config
- window_create
- window_names
- yview_pickplace
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_clear
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- bind
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- pack
- tkinter.Place
- place_configure
- place_forget
- place_info
- place
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location
- tkinter.XView
- xview
- xview_moveto
- xview_scroll
- tkinter.YView
- yview
- yview_moveto
- yview_scroll
22class ToolTip: 23 """ 24 Display a hovering tooltip while the mouse is over a given widget. 25 26 Attributes 27 ---------- 28 tooltip : tk.Toplevel 29 The actual tooltip popup. 30 parent : Misc 31 The parent widget, which will host the tooltip. 32 text : str 33 The text to display in the tooltip. 34 """ 35 36 def __init__(self, parent: Misc, text: str = "") -> None: 37 """ 38 Construct a tooltip. 39 40 Parameters 41 ---------- 42 parent : Misc 43 The parent widget, which will host the tooltip. 44 text : str 45 The text to display in the tooltip. 46 """ 47 self.tooltip: tk.Toplevel | None = None 48 self.parent = parent 49 self.text = text 50 self.bind_events() 51 52 def bind_events(self) -> None: 53 """ 54 Bind the Enter, Leave, Motion events to the parent widget. 55 """ 56 self.parent.bind("<Enter>", self.on_enter) 57 self.parent.bind("<Motion>", self.on_move) 58 self.parent.bind("<Leave>", self.on_leave) 59 60 def on_enter(self, event: Event) -> None: 61 """ 62 Handle the event when pointer enters the widget. 63 """ 64 self.tooltip = tk.Toplevel(class_="ToolTip") 65 self.tooltip.overrideredirect(True) 66 self.tooltip.geometry(f"+{event.x_root+10}+{event.y_root+10}") 67 ttk.Label( 68 self.tooltip, text=self.text, font=StyleManager.get_small_font(), 69 background="#ffffdd", foreground="#000000", anchor=tk.CENTER 70 ).grid(ipadx=INTERNAL_PAD) 71 72 def on_move(self, event: Event) -> None: 73 """ 74 Handle the event when the pointer moves within the widget. 75 """ 76 if self.tooltip: 77 self.tooltip.geometry(f"+{event.x_root+10}+{event.y_root+10}") 78 79 def on_leave(self, _event: Event) -> None: 80 """ 81 Handle the event when the pointer leaves the widget. 82 """ 83 if self.tooltip: 84 self.tooltip.destroy() 85 self.tooltip = None
Display a hovering tooltip while the mouse is over a given widget.
Attributes
- tooltip (tk.Toplevel): The actual tooltip popup.
- parent (Misc): The parent widget, which will host the tooltip.
- text (str): The text to display in the tooltip.
36 def __init__(self, parent: Misc, text: str = "") -> None: 37 """ 38 Construct a tooltip. 39 40 Parameters 41 ---------- 42 parent : Misc 43 The parent widget, which will host the tooltip. 44 text : str 45 The text to display in the tooltip. 46 """ 47 self.tooltip: tk.Toplevel | None = None 48 self.parent = parent 49 self.text = text 50 self.bind_events()
Construct a tooltip.
Parameters
- parent (Misc): The parent widget, which will host the tooltip.
- text (str): The text to display in the tooltip.
52 def bind_events(self) -> None: 53 """ 54 Bind the Enter, Leave, Motion events to the parent widget. 55 """ 56 self.parent.bind("<Enter>", self.on_enter) 57 self.parent.bind("<Motion>", self.on_move) 58 self.parent.bind("<Leave>", self.on_leave)
Bind the Enter, Leave, Motion events to the parent widget.
60 def on_enter(self, event: Event) -> None: 61 """ 62 Handle the event when pointer enters the widget. 63 """ 64 self.tooltip = tk.Toplevel(class_="ToolTip") 65 self.tooltip.overrideredirect(True) 66 self.tooltip.geometry(f"+{event.x_root+10}+{event.y_root+10}") 67 ttk.Label( 68 self.tooltip, text=self.text, font=StyleManager.get_small_font(), 69 background="#ffffdd", foreground="#000000", anchor=tk.CENTER 70 ).grid(ipadx=INTERNAL_PAD)
Handle the event when pointer enters the widget.
72 def on_move(self, event: Event) -> None: 73 """ 74 Handle the event when the pointer moves within the widget. 75 """ 76 if self.tooltip: 77 self.tooltip.geometry(f"+{event.x_root+10}+{event.y_root+10}")
Handle the event when the pointer moves within the widget.
124class TempToolTip(ToolTip): 125 """ 126 A Temporary tooltip that times out after a few seconds. 127 """ 128 129 def __init__( 130 self, parent: Misc, text: str = "", 131 position: tuple[int, int] = (0, 0), timer_ms: int = 2000 132 ) -> None: 133 """ 134 Construct a temporary tooltip. 135 136 Parameters 137 ---------- 138 parent : Misc 139 The parent widget, which will host the tooltip. 140 text : str 141 The text to display in the tooltip. 142 position : tuple[int, int] 143 The (X, Y) position of the tooltip. 144 timer_ms : int 145 The number of milliseconds to display the tooltip. 146 """ 147 super().__init__(parent, text) 148 self.tooltip = tk.Toplevel(class_="ToolTip") 149 self.tooltip.overrideredirect(True) 150 self.tooltip.geometry(f"+{position[0]}+{position[1]}") 151 ttk.Label( 152 self.tooltip, text=self.text, font=StyleManager.get_small_font(), 153 background="#ffffdd", foreground="#000000", anchor=tk.CENTER 154 ).grid(ipadx=INTERNAL_PAD) 155 self.tooltip.after(timer_ms, self.dismiss) 156 157 def bind_events(self) -> None: 158 """ 159 Don't handle any events. 160 """ 161 162 def dismiss(self) -> None: 163 """ 164 Dismiss the tooltip. 165 """ 166 if self.tooltip: 167 self.tooltip.destroy() 168 self.tooltip = None
A Temporary tooltip that times out after a few seconds.
129 def __init__( 130 self, parent: Misc, text: str = "", 131 position: tuple[int, int] = (0, 0), timer_ms: int = 2000 132 ) -> None: 133 """ 134 Construct a temporary tooltip. 135 136 Parameters 137 ---------- 138 parent : Misc 139 The parent widget, which will host the tooltip. 140 text : str 141 The text to display in the tooltip. 142 position : tuple[int, int] 143 The (X, Y) position of the tooltip. 144 timer_ms : int 145 The number of milliseconds to display the tooltip. 146 """ 147 super().__init__(parent, text) 148 self.tooltip = tk.Toplevel(class_="ToolTip") 149 self.tooltip.overrideredirect(True) 150 self.tooltip.geometry(f"+{position[0]}+{position[1]}") 151 ttk.Label( 152 self.tooltip, text=self.text, font=StyleManager.get_small_font(), 153 background="#ffffdd", foreground="#000000", anchor=tk.CENTER 154 ).grid(ipadx=INTERNAL_PAD) 155 self.tooltip.after(timer_ms, self.dismiss)
Construct a temporary tooltip.
Parameters
- parent (Misc): The parent widget, which will host the tooltip.
- text (str): The text to display in the tooltip.
- position (tuple[int, int]): The (X, Y) position of the tooltip.
- timer_ms (int): The number of milliseconds to display the tooltip.
88class TextToolTip(ToolTip): 89 """ 90 A ToolTip subclass for use with Text widgets. 91 92 Attributes 93 ---------- 94 tag : str 95 A tag used in the Text widget with which to link this tooltip. 96 """ 97 98 def __init__(self, parent: Text, text: str = "", tag: str = "") -> None: 99 """ 100 Construct a tooltip. 101 102 Parameters 103 ---------- 104 parent : Text 105 The parent widget, which will host the tooltip. 106 text : str 107 The text to display in the tooltip. 108 tag : str 109 A tag from the parent Text widget that will be bound for the tooltip. 110 """ 111 self.tag = tag 112 super().__init__(parent, text) 113 114 def bind_events(self) -> None: 115 """ 116 Bind the Enter, Leave, Motion events to the tag on the parent Text widget. 117 """ 118 parent: Text = self.parent # type: ignore[assignment] 119 parent.tag_bind(self.tag, "<Enter>", self.on_enter, "+") 120 parent.tag_bind(self.tag, "<Motion>", self.on_move, "+") 121 parent.tag_bind(self.tag, "<Leave>", self.on_leave, "+")
A ToolTip subclass for use with Text widgets.
Attributes
- tag (str): A tag used in the Text widget with which to link this tooltip.
98 def __init__(self, parent: Text, text: str = "", tag: str = "") -> None: 99 """ 100 Construct a tooltip. 101 102 Parameters 103 ---------- 104 parent : Text 105 The parent widget, which will host the tooltip. 106 text : str 107 The text to display in the tooltip. 108 tag : str 109 A tag from the parent Text widget that will be bound for the tooltip. 110 """ 111 self.tag = tag 112 super().__init__(parent, text)
Construct a tooltip.
Parameters
- parent (Text): The parent widget, which will host the tooltip.
- text (str): The text to display in the tooltip.
- tag (str): A tag from the parent Text widget that will be bound for the tooltip.
114 def bind_events(self) -> None: 115 """ 116 Bind the Enter, Leave, Motion events to the tag on the parent Text widget. 117 """ 118 parent: Text = self.parent # type: ignore[assignment] 119 parent.tag_bind(self.tag, "<Enter>", self.on_enter, "+") 120 parent.tag_bind(self.tag, "<Motion>", self.on_move, "+") 121 parent.tag_bind(self.tag, "<Leave>", self.on_leave, "+")
Bind the Enter, Leave, Motion events to the tag on the parent Text widget.
26class UrlLabel(ttk.Label): 27 """ 28 A label containing a clickable URL. 29 30 Attributes 31 ---------- 32 url : str 33 The URL to use when opening a web browser. 34 """ 35 36 def __init__( 37 self, parent: BaseWidget, text: str, url: str, *, 38 style: str = "URL.TLabel", show_tooltip: bool = False, **kwargs 39 ) -> None: 40 """ 41 Construct a Label with a clickable URL. 42 43 Parameters 44 ---------- 45 parent : BaseWidget 46 The parent widget. 47 text : str 48 The text to display in the label. 49 url : str 50 The URL to use when opening a web browser. 51 style : str 52 A Tcl/Tk style to use for display. 53 show_tooltip : bool 54 A flag to indicate whether to show a tooltip containing the URL. 55 **kwargs : dict, optional 56 Additional keyword arguments for a `Label`. 57 """ 58 self.url = url 59 cursor = "hand2" if self._has_web_protocol() else "arrow" 60 super().__init__(parent, cursor=cursor, style=style, text=text, **kwargs) 61 if show_tooltip and url: 62 ToolTip(self, url) 63 self.bind("<Button-1>", self.open_url) 64 65 def open_url(self, _event: Event) -> None: 66 """ 67 Open the widget's URL in a web browser. 68 """ 69 if self._has_web_protocol(): 70 webbrowser.open_new_tab(self.url) 71 72 def _has_web_protocol(self) -> bool: 73 """ 74 Determine whether the string contains a web protocol (http or https). 75 """ 76 return self.url[0:7] == "http://" or self.url[0:8] == "https://" 77 78 @classmethod 79 def has_web_protocol(cls, url: str) -> bool: 80 """ 81 Determine whether the string contains a web protocol (http or https). 82 """ 83 return url[0:7] == "http://" or url[0:8] == "https://" 84 85 @classmethod 86 def test_web_protocol(cls, url: str, trueval: T, falseval: T) -> T: 87 """ 88 If url uses a web protocol, return trueval; otherwise return falseval. 89 """ 90 return trueval if cls.has_web_protocol(url) else falseval
A label containing a clickable URL.
Attributes
- url (str): The URL to use when opening a web browser.
36 def __init__( 37 self, parent: BaseWidget, text: str, url: str, *, 38 style: str = "URL.TLabel", show_tooltip: bool = False, **kwargs 39 ) -> None: 40 """ 41 Construct a Label with a clickable URL. 42 43 Parameters 44 ---------- 45 parent : BaseWidget 46 The parent widget. 47 text : str 48 The text to display in the label. 49 url : str 50 The URL to use when opening a web browser. 51 style : str 52 A Tcl/Tk style to use for display. 53 show_tooltip : bool 54 A flag to indicate whether to show a tooltip containing the URL. 55 **kwargs : dict, optional 56 Additional keyword arguments for a `Label`. 57 """ 58 self.url = url 59 cursor = "hand2" if self._has_web_protocol() else "arrow" 60 super().__init__(parent, cursor=cursor, style=style, text=text, **kwargs) 61 if show_tooltip and url: 62 ToolTip(self, url) 63 self.bind("<Button-1>", self.open_url)
Construct a Label with a clickable URL.
Parameters
- parent (BaseWidget): The parent widget.
- text (str): The text to display in the label.
- url (str): The URL to use when opening a web browser.
- style (str): A Tcl/Tk style to use for display.
- show_tooltip (bool): A flag to indicate whether to show a tooltip containing the URL.
- **kwargs (dict, optional):
Additional keyword arguments for a
Label.
65 def open_url(self, _event: Event) -> None: 66 """ 67 Open the widget's URL in a web browser. 68 """ 69 if self._has_web_protocol(): 70 webbrowser.open_new_tab(self.url)
Open the widget's URL in a web browser.
78 @classmethod 79 def has_web_protocol(cls, url: str) -> bool: 80 """ 81 Determine whether the string contains a web protocol (http or https). 82 """ 83 return url[0:7] == "http://" or url[0:8] == "https://"
Determine whether the string contains a web protocol (http or https).
85 @classmethod 86 def test_web_protocol(cls, url: str, trueval: T, falseval: T) -> T: 87 """ 88 If url uses a web protocol, return trueval; otherwise return falseval. 89 """ 90 return trueval if cls.has_web_protocol(url) else falseval
If url uses a web protocol, return trueval; otherwise return falseval.
Inherited Members
- tkinter.ttk.Widget
- identify
- instate
- state
- tkinter.BaseWidget
- destroy
- tkinter.Misc
- deletecommand
- tk_strictMotif
- tk_bisque
- tk_setPalette
- wait_variable
- waitvar
- wait_window
- wait_visibility
- setvar
- getvar
- getboolean
- focus_set
- focus
- focus_force
- focus_get
- focus_displayof
- focus_lastfor
- tk_focusFollowsMouse
- tk_focusNext
- tk_focusPrev
- after
- after_idle
- after_cancel
- bell
- clipboard_get
- clipboard_clear
- clipboard_append
- grab_current
- grab_release
- grab_set
- grab_set_global
- grab_status
- option_add
- option_clear
- option_get
- option_readfile
- selection_clear
- selection_get
- selection_handle
- selection_own
- selection_own_get
- send
- lower
- tkraise
- lift
- winfo_atom
- winfo_atomname
- winfo_cells
- winfo_children
- winfo_class
- winfo_colormapfull
- winfo_containing
- winfo_depth
- winfo_exists
- winfo_fpixels
- winfo_geometry
- winfo_height
- winfo_id
- winfo_interps
- winfo_ismapped
- winfo_manager
- winfo_name
- winfo_parent
- winfo_pathname
- winfo_pixels
- winfo_pointerx
- winfo_pointerxy
- winfo_pointery
- winfo_reqheight
- winfo_reqwidth
- winfo_rgb
- winfo_rootx
- winfo_rooty
- winfo_screen
- winfo_screencells
- winfo_screendepth
- winfo_screenheight
- winfo_screenmmheight
- winfo_screenmmwidth
- winfo_screenvisual
- winfo_screenwidth
- winfo_server
- winfo_toplevel
- winfo_viewable
- winfo_visual
- winfo_visualid
- winfo_visualsavailable
- winfo_vrootheight
- winfo_vrootwidth
- winfo_vrootx
- winfo_vrooty
- winfo_width
- winfo_x
- winfo_y
- update
- update_idletasks
- bind
- unbind
- bind_all
- unbind_all
- bind_class
- unbind_class
- mainloop
- quit
- nametowidget
- register
- configure
- config
- cget
- keys
- pack_propagate
- propagate
- pack_slaves
- slaves
- place_slaves
- grid_anchor
- anchor
- grid_bbox
- bbox
- grid_columnconfigure
- columnconfigure
- grid_location
- grid_propagate
- grid_rowconfigure
- rowconfigure
- grid_size
- size
- grid_slaves
- event_add
- event_delete
- event_generate
- event_info
- image_names
- image_types
- tkinter.Pack
- pack_configure
- pack_forget
- forget
- pack_info
- info
- pack
- tkinter.Place
- place_configure
- place_forget
- place_info
- place
- tkinter.Grid
- grid_configure
- grid_forget
- grid_remove
- grid_info
- grid
- location