tktable module
This contains a wrapper class for the tktable widget as well a class for using tcl arrays that are, in some instances, required by tktable.
# Copyright (c) 2008, Guilherme Polo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
This contains a wrapper class for the tktable widget as well a class for using
tcl arrays that are, in some instances, required by tktable.
"""
__author__ = "Guilherme Polo "
__all__ = ["ArrayVar", "Table"]
import collections
import os
try:
import tkinter
except ImportError:
import Tkinter as tkinter
def _setup_master(master):
if master is None:
if tkinter._support_default_root:
master = tkinter._default_root or tkinter.Tk()
else:
raise RuntimeError("No master specified and Tkinter is "
"configured to not support default master")
return master
class ArrayVar(tkinter.Variable):
"""Class for handling Tcl arrays.
An array is actually an associative array in Tcl, so this class supports
some dict operations.
"""
def __init__(self, master=None, name=None):
# Tkinter.Variable.__init__ is not called on purpose! I don't wanna
# see an ugly _default value in the pretty array.
self._master = _setup_master(master)
self._tk = self._master.tk
if name:
self._name = name
else:
self._name = 'PY_VAR%s' % id(self)
def __del__(self):
if bool(self._tk.call('info', 'exists', self._name)):
self._tk.globalunsetvar(self._name)
def __len__(self):
return int(self._tk.call('array', 'size', str(self)))
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
self.set(**{str(key): value})
def names(self):
return self._tk.call('array', 'names', self._name)
def get(self, key=None):
if key is None:
flatten_pairs = self._tk.call('array', 'get', str(self))
return dict(list(zip(flatten_pairs[::2], flatten_pairs[1::2])))
return self._tk.globalgetvar(str(self), str(key))
def set(self, **kw):
self._tk.call('array', 'set', str(self), tkinter._flatten(list(kw.items())))
def unset(self, pattern=None):
"""Unsets all of the elements in the array. If pattern is given, only
the elements that match pattern are unset. """
self._tk.call('array', 'unset', str(self), pattern)
_TKTABLE_LOADED = False
class Table(tkinter.Widget):
"""Create and manipulate tables."""
_switches = ('holddimensions', 'holdselection', 'holdtags', 'holdwindows', 'keeptitles', '-')
_tabsubst_format = ('%c', '%C', '%i', '%r', '%s', '%S', '%W')
_tabsubst_commands = ('browsecommand', 'browsecmd', 'command',
'selectioncommand', 'selcmd', 'validatecommand', 'valcmd')
def __init__(self, master=None, **kw):
master = _setup_master(master)
global _TKTABLE_LOADED
if not _TKTABLE_LOADED:
tktable_lib = os.environ.get('TKTABLE_LIBRARY')
if tktable_lib:
master.tk.eval('global auto_path; lappend auto_path {%s}' % tktable_lib)
try:
master.tk.call('package', 'require', 'Tktable')
except tkinter._tkinter.TclError:
print("\033[93mThe Tcl/Tk extension named 'Tktable' is not installed in your system.\n"
"You need first to install it to use this wrapper library.\n"
"If you're seeing this message, you probably downloaded this module from "
"this Github's repository 'https://github.com/nelson-brochado/tktable'.\033[0m\n")
_TKTABLE_LOADED = True
tkinter.Widget.__init__(self, master, 'table', kw)
def _options(self, cnf, kw=None):
if kw:
cnf = tkinter._cnfmerge((cnf, kw))
else:
cnf = tkinter._cnfmerge(cnf)
res = ()
for k, v in cnf.items():
if isinstance(v, collections.Callable):
if k in self._tabsubst_commands:
v = "%s %s" % (self._register(v, self._tabsubst), ' '.join(self._tabsubst_format))
else:
v = self._register(v)
res += ('-%s' % k, v)
return res
def _tabsubst(self, *args):
if len(args) != len(self._tabsubst_format):
return args
tk = self.tk
c, C, i, r, s, S, W = args
e = tkinter.Event()
e.widget = self
e.c = tk.getint(c)
e.i = tk.getint(i)
e.r = tk.getint(r)
e.C = "%d,%d" % (e.r, e.c)
e.s = s
e.S = S
try:
e.W = self._nametowidget(W)
except KeyError:
e.W = None
return (e,)
def _handle_switches(self, args):
args = args or ()
return tuple(('-%s' % x) for x in args if x in self._switches)
def activate(self, index):
"""Set the active cell to the one indicated by index."""
self.tk.call(self._w, 'activate', index)
def bbox(self, first, last=None):
"""Return the bounding box for the specified cell (range) as a
4-tuple of x, y, width and height in pixels. It clips the box to
the visible portion, if any, otherwise an empty tuple is returned."""
return self._getints(self.tk.call(self._w, 'bbox', first, last)) or ()
def clear(self, option, first=None, last=None):
"""This is a convenience routine to clear certain state information
managed by the table. first and last represent valid table indices.
If neither are specified, then the command operates on the whole
table."""
self.tk.call(self._w, 'clear', option, first, last)
def clear_cache(self, first=None, last=None):
"""Clear the specified section of the cache, if the table has been
keeping one."""
self.clear('cache', first, last)
def clear_sizes(self, first=None, last=None):
"""Clear the specified row and column areas of specific height/width
dimensions. When just one index is specified, for example 2,0, that
is interpreted as row 2 and column 0."""
self.clear('sizes', first, last)
def clear_tags(self, first=None, last=None):
"""Clear the specified area of tags (all row, column and cell tags)."""
self.clear('tags', first, last)
def clear_all(self, first=None, last=None):
"""Perform all of the above clear functions on the specified area."""
self.clear('all', first, last)
def curselection(self, value=None):
"""With no arguments, it returns the sorted indices of the currently
selected cells. Otherwise it sets all the selected cells to the given
value if there is an associated ArrayVar and the state is not
disabled."""
result = self.tk.call(self._w, 'curselection', value)
if value is None:
return result
def curvalue(self, value=None):
"""If no value is given, the value of the cell being edited (indexed
by active) is returned, else it is set to the given value. """
return self.tk.call(self._w, 'curvalue', value)
def delete_active(self, index1, index2=None):
"""Deletes text from the active cell. If only one index is given,
it deletes the character after that index, otherwise it deletes from
the first index to the second. index can be a number, insert or end."""
self.tk.call(self._w, 'delete', 'active', index1, index2)
def delete_cols(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'delete', 'cols', *args)
def delete_rows(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'delete', 'rows', *args)
def get(self, first, last=None):
"""Returns the value of the cells specified by the table indices
first and (optionally) last."""
return self.tk.call(self._w, 'get', first, last)
def height(self, row=None, **kwargs):
"""If row and kwargs are not given, a list describing all rows for
which a width has been set is returned.
If row is given, the height of that row is returnd.
If kwargs is given, then it sets the key/value pairs, where key is a
row and value represents the height for the row."""
if row is None and not kwargs:
pairs = self.tk.splitlist(self.tk.call(self._w, 'height'))
return dict(pair.split() for pair in pairs)
elif row:
return int(self.tk.call(self._w, 'height', str(row)))
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'height', *args)
def hidden(self, *args):
"""When called without args, it returns all the hidden cells (those
cells covered by a spanning cell). If one index is specified, it
returns the spanning cell covering that index, if any. If multiple
indices are specified, it returns 1 if all indices are hidden cells,
0 otherwise."""
return self.tk.call(self._w, 'hidden', *args)
def icursor(self, arg=None):
"""If arg is not specified, return the location of the insertion
cursor in the active cell. Otherwise, set the cursor to that point in
the string.
0 is before the first character, you can also use insert or end for
the current insertion point or the end of the text. If there is no
active cell, or the cell or table is disabled, this will return -1."""
return self.tk.call(self._w, 'icursor', arg)
def index(self, index, rc=None):
"""Return the integer cell coordinate that corresponds to index in the
form row, col. If rc is specified, it must be either 'row' or 'col' so
only the row or column index is returned."""
res = self.tk.call(self._w, 'index', index, rc)
if rc is None:
return res
else:
return int(res)
def insert_active(self, index, value):
"""The value is a text string which is inserted at the index postion
of the active cell. The cursor is then positioned after the new text.
index can be a number, insert or end. """
self.tk.call(self._w, 'insert', 'active', index, value)
def insert_cols(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'insert', 'cols', *args)
def insert_rows(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'insert', 'rows', *args)
# def postscript(self, **kwargs):
# """Skip this command if you are under Windows.
#
# Accepted options:
# colormap, colormode, file, channel, first, fontmap, height,
# last, pageanchor, pageheight, pagewidth, pagex, pagey, rotate,
# width, x, y
# """
# args = ()
# for key, val in kwargs.iteritems():
# args += ('-%s' % key, val)
#
# return self.tk.call(self._w, 'postscript', *args)
def reread(self):
"""Rereads the old contents of the cell back into the editing buffer.
Useful for a key binding when is pressed to abort the edit
(a default binding)."""
self.tk.call(self._w, 'reread')
def scan_mark(self, x, y):
self.tk.call(self._w, 'scan', 'mark', x, y)
def scan_dragto(self, x, y):
self.tk.call(self._w, 'scan', 'dragto', x, y)
def see(self, index):
self.tk.call(self._w, 'see', index)
def selection_anchor(self, index):
self.tk.call(self._w, 'selection', 'anchor', index)
def selection_clear(self, first, last=None):
self.tk.call(self._w, 'selection', 'clear', first, last)
def selection_includes(self, index):
return self.getboolean(self.tk.call(self._w, 'selection', 'includes', index))
def selection_set(self, first, last=None):
self.tk.call(self._w, 'selection', 'set', first, last)
def set(self, rc=None, index=None, *args, **kwargs):
"""If rc is specified (either 'row' or 'col') then it is assumes that
args (if given) represents values which will be set into the
subsequent columns (if row is specified) or rows (for col).
If index is not None and args is not given, then it will return the
value(s) for the cell(s) specified.
If kwargs is given, assumes that each key in kwargs is a index in this
table and sets the specified index to the associated value. Table
validation will not be triggered via this method.
Note that the table must have an associated array (defined through the
variable option) in order to this work."""
if not args and index is not None:
if rc:
args = (rc, index)
else:
args = (index,)
return self.tk.call(self._w, 'set', *args)
if rc is None:
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'set', *args)
else:
self.tk.call(self._w, 'set', rc, index, args)
def spans(self, index=None, **kwargs):
"""Manipulate row/col spans.
When called with no arguments, all known spans are returned as a dict.
When called with only the index, the span for that index only is
returned, if any. Otherwise kwargs is assumed to contain keys/values
pairs used to set spans. A span starts at the row,col defined by a key
and continues for the specified number of rows,cols specified by
its value. A span of 0,0 unsets any span on that cell."""
if kwargs:
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'spans', *args)
else:
return self.tk.call(self._w, 'spans', index)
def tag_cell(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'cell', tagname, *args)
def tag_cget(self, tagname, option):
return self.tk.call(self._w, 'tag', 'cget', tagname, '-%s' % option)
def tag_col(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'col', tagname, *args)
def tag_configure(self, tagname, option=None, **kwargs):
"""Query or modify options associated with the tag given by tagname.
If no option is specified, a dict describing all of the available
options for tagname is returned. If option is specified, then the
command returns a list describing the one named option. Lastly, if
kwargs is given then it corresponds to option-value pairs that should
be modified."""
if option is None and not kwargs:
split1 = self.tk.splitlist(self.tk.call(self._w, 'tag', 'configure', tagname))
result = {}
for item in split1:
res = self.tk.splitlist(item)
result[res[0]] = res[1:]
return result
elif option:
return self.tk.call(self._w, 'tag', 'configure', tagname, '-%s' % option)
else:
args = ()
for key, val in kwargs.items():
args += ('-%s' % key, val)
self.tk.call(self._w, 'tag', 'configure', tagname, *args)
def tag_delete(self, tagname):
self.tk.call(self._w, 'tag', 'delete', tagname)
def tag_exists(self, tagname):
return self.getboolean(self.tk.call(self._w, 'tag', 'exists', tagname))
def tag_includes(self, tagname, index):
return self.getboolean(self.tk.call(self._w, 'tag', 'includes', tagname, index))
def tag_lower(self, tagname, belowthis=None):
self.tk.call(self._w, 'tag', 'lower', belowthis)
def tag_names(self, pattern=None):
return self.tk.call(self._w, 'tag', 'names', pattern)
def tag_raise(self, tagname, abovethis=None):
self.tk.call(self._w, 'tag', 'raise', tagname, abovethis)
def tag_row(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'row', tagname, *args)
def validate(self, index):
"""Explicitly validates the specified index based on the current
callback set for the validatecommand option. Return 0 or 1 based on
whether the cell was validated."""
return self.tk.call(self._w, 'validate', index)
@property
def version(self):
"""Return tktable's package version."""
return self.tk.call(self._w, 'version')
def width(self, column=None, **kwargs):
"""If column and kwargs are not given, a dict describing all columns
for which a width has been set is returned.
If column is given, the width of that column is returnd.
If kwargs is given, then it sets the key/value pairs, where key is a
column and value represents the width for the column."""
if column is None and not kwargs:
pairs = self.tk.splitlist(self.tk.call(self._w, 'width'))
return dict(pair.split() for pair in pairs)
elif column is not None:
return int(self.tk.call(self._w, 'width', str(column)))
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'width', *args)
def window_cget(self, index, option):
return self.tk.call(self._w, 'window', 'cget', index, option)
def window_configure(self, index, option=None, **kwargs):
"""Query or modify options associated with the embedded window given
by index. This should also be used to add a new embedded window into
the table.
If no option is specified, a dict describing all of the available
options for index is returned. If option is specified, then the
command returns a list describing the one named option. Lastly, if
kwargs is given then it corresponds to option-value pairs that should
be modified."""
if option is None and not kwargs:
return self.tk.call(self._w, 'window', 'configure', index)
elif option:
return self.tk.call(self._w, 'window', 'configure', index, '-%s' % option)
else:
args = ()
for key, val in kwargs.items():
args += ('-%s' % key, val)
self.tk.call(self._w, 'window', 'configure', index, *args)
def window_delete(self, *indexes):
self.tk.call(self._w, 'window', 'delete', *indexes)
def window_move(self, index_from, index_to):
self.tk.call(self._w, 'window', 'move', index_from, index_to)
def window_names(self, pattern=None):
return self.tk.call(self._w, 'window', 'names', pattern)
def xview(self, index=None):
"""If index is not given a tuple containing two fractions is returned,
each fraction is between 0 and 1. Together they describe the
horizontal span that is visible in the window.
If index is given the view in the window is adjusted so that the
column given by index is displayed at the left edge of the window."""
res = self.tk.call(self._w, 'xview', index)
if index is None:
return self._getdoubles(res)
def xview_moveto(self, fraction):
"""Adjusts the view in the window so that fraction of the total width
of the table text is off-screen to the left. The fraction parameter
must be a fraction between 0 and 1."""
self.tk.call(self._w, 'xview', 'moveto', fraction)
def xview_scroll(self, *L):
# change by frank gao for attach scrollbar 11/11/2010
"""Shift the view in the window left or right according to number and
what. The 'number' parameter must be an integer. The 'what' parameter
must be either units or pages or an abbreviation of one of these.
If 'what' is units, the view adjusts left or right by number cells on
the display; if it is pages then the view adjusts by number screenfuls.
If 'number' is negative then cells farther to the left become visible;
if it is positive then cells farther to the right become visible. """
# self.tk.call(self._w, 'xview', 'scroll', number, what)
op, howMany = L[0], L[1]
if op == 'scroll':
units = L[2]
self.tk.call(self._w, 'xview', 'scroll', howMany, units)
elif op == 'moveto':
self.tk.call(self._w, 'xview', 'moveto', howMany)
def yview(self, index=None):
"""If index is not given a tuple containing two fractions is returned,
each fraction is between 0 and 1. The first element gives the position
of the table element at the top of the window, relative to the table
as a whole. The second element gives the position of the table element
just after the last one in the window, relative to the table as a
whole.
If index is given the view in the window is adjusted so that the
row given by index is displayed at the top of the window."""
res = self.tk.call(self._w, 'yview', index)
if index is None:
return self._getdoubles(res)
def yview_moveto(self, fraction):
"""Adjusts the view in the window so that the element given by
fraction appears at the top of the window. The fraction parameter
must be a fraction between 0 and 1."""
self.tk.call(self._w, 'yview', 'moveto', fraction)
def yview_scroll(self, *L):
# change by frank gao for attach scrollbar 11/11/2010
"""Adjust the view in the window up or down according to number and
what. The 'number' parameter must be an integer. The 'what' parameter
must be either units or pages or an abbreviation of one of these.
If 'what' is units, the view adjusts up or down by number cells; if it
is pages then the view adjusts by number screenfuls.
If 'number' is negative then earlier elements become visible; if it
is positive then later elements become visible. """
# self.tk.call(self._w, 'yview', 'scroll', number, what)
op, howMany = L[0], L[1]
if op == 'scroll':
units = L[2]
self.tk.call(self._w, 'yview', 'scroll', howMany, units)
elif op == 'moveto':
self.tk.call(self._w, 'yview', 'moveto', howMany)
# Sample test taken from tktable cvs, original tktable python wrapper
def sample_test():
try:
from tkinter import Tk, Label, Button
except ImportError:
from Tkinter import Tk, Label, Button
def test_cmd(event):
if event.i == 0:
return '%i, %i' % (event.r, event.c)
else:
return 'set'
def browsecmd(event):
print("event:", event.__dict__)
print("curselection:", test.curselection())
print("active cell index:", test.index('active'))
print("active:", test.index('active', 'row'))
print("anchor:", test.index('anchor', 'row'))
root = Tk()
var = ArrayVar(root)
for y in range(-1, 4):
for x in range(-1, 5):
index = "%i,%i" % (y, x)
var[index] = index
label = Label(root, text="Proof-of-existence test for Tktable")
label.pack(side='top', fill='x')
quit = Button(root, text="QUIT", command=root.destroy)
quit.pack(side='bottom', fill='x')
test = Table(root,
rows=10,
cols=5,
state='disabled',
width=6,
height=6,
titlerows=1,
titlecols=1,
roworigin=-1,
colorigin=-1,
selectmode='browse',
selecttype='row',
rowstretch='unset',
colstretch='last',
browsecmd=browsecmd,
flashmode='on',
variable=var,
usecommand=0,
command=test_cmd)
test.pack(expand=1, fill='both')
test.tag_configure('sel', background='yellow')
test.tag_configure('active', background='blue')
test.tag_configure('title', anchor='w', bg='red', relief='sunken')
import sys
if "-test" in sys.argv:
root.after(1000, lambda: root.destroy())
root.mainloop()
if __name__ == '__main__':
sample_test()
Classes
class ArrayVar
Class for handling Tcl arrays.
An array is actually an associative array in Tcl, so this class supports some dict operations.
class ArrayVar(tkinter.Variable):
"""Class for handling Tcl arrays.
An array is actually an associative array in Tcl, so this class supports
some dict operations.
"""
def __init__(self, master=None, name=None):
# Tkinter.Variable.__init__ is not called on purpose! I don't wanna
# see an ugly _default value in the pretty array.
self._master = _setup_master(master)
self._tk = self._master.tk
if name:
self._name = name
else:
self._name = 'PY_VAR%s' % id(self)
def __del__(self):
if bool(self._tk.call('info', 'exists', self._name)):
self._tk.globalunsetvar(self._name)
def __len__(self):
return int(self._tk.call('array', 'size', str(self)))
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
self.set(**{str(key): value})
def names(self):
return self._tk.call('array', 'names', self._name)
def get(self, key=None):
if key is None:
flatten_pairs = self._tk.call('array', 'get', str(self))
return dict(list(zip(flatten_pairs[::2], flatten_pairs[1::2])))
return self._tk.globalgetvar(str(self), str(key))
def set(self, **kw):
self._tk.call('array', 'set', str(self), tkinter._flatten(list(kw.items())))
def unset(self, pattern=None):
"""Unsets all of the elements in the array. If pattern is given, only
the elements that match pattern are unset. """
self._tk.call('array', 'unset', str(self), pattern)
Ancestors (in MRO)
- ArrayVar
- tkinter.Variable
- builtins.object
Static methods
def __init__(
self, master=None, name=None)
Construct a variable
MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum).
If NAME matches an existing variable and VALUE is omitted then the existing value is retained.
def __init__(self, master=None, name=None):
# Tkinter.Variable.__init__ is not called on purpose! I don't wanna
# see an ugly _default value in the pretty array.
self._master = _setup_master(master)
self._tk = self._master.tk
if name:
self._name = name
else:
self._name = 'PY_VAR%s' % id(self)
def get(
self, key=None)
Return value of variable.
def get(self, key=None):
if key is None:
flatten_pairs = self._tk.call('array', 'get', str(self))
return dict(list(zip(flatten_pairs[::2], flatten_pairs[1::2])))
return self._tk.globalgetvar(str(self), str(key))
def initialize(
self, value)
Set the variable to VALUE.
def set(self, value):
"""Set the variable to VALUE."""
return self._tk.globalsetvar(self._name, value)
def names(
self)
def names(self):
return self._tk.call('array', 'names', self._name)
def set(
self, **kw)
Set the variable to VALUE.
def set(self, **kw):
self._tk.call('array', 'set', str(self), tkinter._flatten(list(kw.items())))
def trace(
self, mode, callback)
Define a trace callback for the variable.
MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when the variable is read, written or undefined.
Return the name of the callback.
def trace_variable(self, mode, callback):
"""Define a trace callback for the variable.
MODE is one of "r", "w", "u" for read, write, undefine.
CALLBACK must be a function which is called when
the variable is read, written or undefined.
Return the name of the callback.
"""
f = CallWrapper(callback, None, self).__call__
cbname = repr(id(f))
try:
callback = callback.__func__
except AttributeError:
pass
try:
cbname = cbname + callback.__name__
except AttributeError:
pass
self._tk.createcommand(cbname, f)
if self._tclCommands is None:
self._tclCommands = []
self._tclCommands.append(cbname)
self._tk.call("trace", "variable", self._name, mode, cbname)
return cbname
def trace_variable(
self, mode, callback)
Define a trace callback for the variable.
MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when the variable is read, written or undefined.
Return the name of the callback.
def trace_variable(self, mode, callback):
"""Define a trace callback for the variable.
MODE is one of "r", "w", "u" for read, write, undefine.
CALLBACK must be a function which is called when
the variable is read, written or undefined.
Return the name of the callback.
"""
f = CallWrapper(callback, None, self).__call__
cbname = repr(id(f))
try:
callback = callback.__func__
except AttributeError:
pass
try:
cbname = cbname + callback.__name__
except AttributeError:
pass
self._tk.createcommand(cbname, f)
if self._tclCommands is None:
self._tclCommands = []
self._tclCommands.append(cbname)
self._tk.call("trace", "variable", self._name, mode, cbname)
return cbname
def trace_vdelete(
self, mode, cbname)
Delete the trace callback for a variable.
MODE is one of "r", "w", "u" for read, write, undefine. CBNAME is the name of the callback returned from trace_variable or trace.
def trace_vdelete(self, mode, cbname):
"""Delete the trace callback for a variable.
MODE is one of "r", "w", "u" for read, write, undefine.
CBNAME is the name of the callback returned from trace_variable or trace.
"""
self._tk.call("trace", "vdelete", self._name, mode, cbname)
self._tk.deletecommand(cbname)
try:
self._tclCommands.remove(cbname)
except ValueError:
pass
def trace_vinfo(
self)
Return all trace callback information.
def trace_vinfo(self):
"""Return all trace callback information."""
return [self._tk.split(x) for x in self._tk.splitlist(
self._tk.call("trace", "vinfo", self._name))]
def unset(
self, pattern=None)
Unsets all of the elements in the array. If pattern is given, only the elements that match pattern are unset.
def unset(self, pattern=None):
"""Unsets all of the elements in the array. If pattern is given, only
the elements that match pattern are unset. """
self._tk.call('array', 'unset', str(self), pattern)
class Table
Create and manipulate tables.
class Table(tkinter.Widget):
"""Create and manipulate tables."""
_switches = ('holddimensions', 'holdselection', 'holdtags', 'holdwindows', 'keeptitles', '-')
_tabsubst_format = ('%c', '%C', '%i', '%r', '%s', '%S', '%W')
_tabsubst_commands = ('browsecommand', 'browsecmd', 'command',
'selectioncommand', 'selcmd', 'validatecommand', 'valcmd')
def __init__(self, master=None, **kw):
master = _setup_master(master)
global _TKTABLE_LOADED
if not _TKTABLE_LOADED:
tktable_lib = os.environ.get('TKTABLE_LIBRARY')
if tktable_lib:
master.tk.eval('global auto_path; lappend auto_path {%s}' % tktable_lib)
try:
master.tk.call('package', 'require', 'Tktable')
except tkinter._tkinter.TclError:
print("\033[93mThe Tcl/Tk extension named 'Tktable' is not installed in your system.\n"
"You need first to install it to use this wrapper library.\n"
"If you're seeing this message, you probably downloaded this module from "
"this Github's repository 'https://github.com/nelson-brochado/tktable'.\033[0m\n")
_TKTABLE_LOADED = True
tkinter.Widget.__init__(self, master, 'table', kw)
def _options(self, cnf, kw=None):
if kw:
cnf = tkinter._cnfmerge((cnf, kw))
else:
cnf = tkinter._cnfmerge(cnf)
res = ()
for k, v in cnf.items():
if isinstance(v, collections.Callable):
if k in self._tabsubst_commands:
v = "%s %s" % (self._register(v, self._tabsubst), ' '.join(self._tabsubst_format))
else:
v = self._register(v)
res += ('-%s' % k, v)
return res
def _tabsubst(self, *args):
if len(args) != len(self._tabsubst_format):
return args
tk = self.tk
c, C, i, r, s, S, W = args
e = tkinter.Event()
e.widget = self
e.c = tk.getint(c)
e.i = tk.getint(i)
e.r = tk.getint(r)
e.C = "%d,%d" % (e.r, e.c)
e.s = s
e.S = S
try:
e.W = self._nametowidget(W)
except KeyError:
e.W = None
return (e,)
def _handle_switches(self, args):
args = args or ()
return tuple(('-%s' % x) for x in args if x in self._switches)
def activate(self, index):
"""Set the active cell to the one indicated by index."""
self.tk.call(self._w, 'activate', index)
def bbox(self, first, last=None):
"""Return the bounding box for the specified cell (range) as a
4-tuple of x, y, width and height in pixels. It clips the box to
the visible portion, if any, otherwise an empty tuple is returned."""
return self._getints(self.tk.call(self._w, 'bbox', first, last)) or ()
def clear(self, option, first=None, last=None):
"""This is a convenience routine to clear certain state information
managed by the table. first and last represent valid table indices.
If neither are specified, then the command operates on the whole
table."""
self.tk.call(self._w, 'clear', option, first, last)
def clear_cache(self, first=None, last=None):
"""Clear the specified section of the cache, if the table has been
keeping one."""
self.clear('cache', first, last)
def clear_sizes(self, first=None, last=None):
"""Clear the specified row and column areas of specific height/width
dimensions. When just one index is specified, for example 2,0, that
is interpreted as row 2 and column 0."""
self.clear('sizes', first, last)
def clear_tags(self, first=None, last=None):
"""Clear the specified area of tags (all row, column and cell tags)."""
self.clear('tags', first, last)
def clear_all(self, first=None, last=None):
"""Perform all of the above clear functions on the specified area."""
self.clear('all', first, last)
def curselection(self, value=None):
"""With no arguments, it returns the sorted indices of the currently
selected cells. Otherwise it sets all the selected cells to the given
value if there is an associated ArrayVar and the state is not
disabled."""
result = self.tk.call(self._w, 'curselection', value)
if value is None:
return result
def curvalue(self, value=None):
"""If no value is given, the value of the cell being edited (indexed
by active) is returned, else it is set to the given value. """
return self.tk.call(self._w, 'curvalue', value)
def delete_active(self, index1, index2=None):
"""Deletes text from the active cell. If only one index is given,
it deletes the character after that index, otherwise it deletes from
the first index to the second. index can be a number, insert or end."""
self.tk.call(self._w, 'delete', 'active', index1, index2)
def delete_cols(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'delete', 'cols', *args)
def delete_rows(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'delete', 'rows', *args)
def get(self, first, last=None):
"""Returns the value of the cells specified by the table indices
first and (optionally) last."""
return self.tk.call(self._w, 'get', first, last)
def height(self, row=None, **kwargs):
"""If row and kwargs are not given, a list describing all rows for
which a width has been set is returned.
If row is given, the height of that row is returnd.
If kwargs is given, then it sets the key/value pairs, where key is a
row and value represents the height for the row."""
if row is None and not kwargs:
pairs = self.tk.splitlist(self.tk.call(self._w, 'height'))
return dict(pair.split() for pair in pairs)
elif row:
return int(self.tk.call(self._w, 'height', str(row)))
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'height', *args)
def hidden(self, *args):
"""When called without args, it returns all the hidden cells (those
cells covered by a spanning cell). If one index is specified, it
returns the spanning cell covering that index, if any. If multiple
indices are specified, it returns 1 if all indices are hidden cells,
0 otherwise."""
return self.tk.call(self._w, 'hidden', *args)
def icursor(self, arg=None):
"""If arg is not specified, return the location of the insertion
cursor in the active cell. Otherwise, set the cursor to that point in
the string.
0 is before the first character, you can also use insert or end for
the current insertion point or the end of the text. If there is no
active cell, or the cell or table is disabled, this will return -1."""
return self.tk.call(self._w, 'icursor', arg)
def index(self, index, rc=None):
"""Return the integer cell coordinate that corresponds to index in the
form row, col. If rc is specified, it must be either 'row' or 'col' so
only the row or column index is returned."""
res = self.tk.call(self._w, 'index', index, rc)
if rc is None:
return res
else:
return int(res)
def insert_active(self, index, value):
"""The value is a text string which is inserted at the index postion
of the active cell. The cursor is then positioned after the new text.
index can be a number, insert or end. """
self.tk.call(self._w, 'insert', 'active', index, value)
def insert_cols(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'insert', 'cols', *args)
def insert_rows(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'insert', 'rows', *args)
# def postscript(self, **kwargs):
# """Skip this command if you are under Windows.
#
# Accepted options:
# colormap, colormode, file, channel, first, fontmap, height,
# last, pageanchor, pageheight, pagewidth, pagex, pagey, rotate,
# width, x, y
# """
# args = ()
# for key, val in kwargs.iteritems():
# args += ('-%s' % key, val)
#
# return self.tk.call(self._w, 'postscript', *args)
def reread(self):
"""Rereads the old contents of the cell back into the editing buffer.
Useful for a key binding when is pressed to abort the edit
(a default binding)."""
self.tk.call(self._w, 'reread')
def scan_mark(self, x, y):
self.tk.call(self._w, 'scan', 'mark', x, y)
def scan_dragto(self, x, y):
self.tk.call(self._w, 'scan', 'dragto', x, y)
def see(self, index):
self.tk.call(self._w, 'see', index)
def selection_anchor(self, index):
self.tk.call(self._w, 'selection', 'anchor', index)
def selection_clear(self, first, last=None):
self.tk.call(self._w, 'selection', 'clear', first, last)
def selection_includes(self, index):
return self.getboolean(self.tk.call(self._w, 'selection', 'includes', index))
def selection_set(self, first, last=None):
self.tk.call(self._w, 'selection', 'set', first, last)
def set(self, rc=None, index=None, *args, **kwargs):
"""If rc is specified (either 'row' or 'col') then it is assumes that
args (if given) represents values which will be set into the
subsequent columns (if row is specified) or rows (for col).
If index is not None and args is not given, then it will return the
value(s) for the cell(s) specified.
If kwargs is given, assumes that each key in kwargs is a index in this
table and sets the specified index to the associated value. Table
validation will not be triggered via this method.
Note that the table must have an associated array (defined through the
variable option) in order to this work."""
if not args and index is not None:
if rc:
args = (rc, index)
else:
args = (index,)
return self.tk.call(self._w, 'set', *args)
if rc is None:
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'set', *args)
else:
self.tk.call(self._w, 'set', rc, index, args)
def spans(self, index=None, **kwargs):
"""Manipulate row/col spans.
When called with no arguments, all known spans are returned as a dict.
When called with only the index, the span for that index only is
returned, if any. Otherwise kwargs is assumed to contain keys/values
pairs used to set spans. A span starts at the row,col defined by a key
and continues for the specified number of rows,cols specified by
its value. A span of 0,0 unsets any span on that cell."""
if kwargs:
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'spans', *args)
else:
return self.tk.call(self._w, 'spans', index)
def tag_cell(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'cell', tagname, *args)
def tag_cget(self, tagname, option):
return self.tk.call(self._w, 'tag', 'cget', tagname, '-%s' % option)
def tag_col(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'col', tagname, *args)
def tag_configure(self, tagname, option=None, **kwargs):
"""Query or modify options associated with the tag given by tagname.
If no option is specified, a dict describing all of the available
options for tagname is returned. If option is specified, then the
command returns a list describing the one named option. Lastly, if
kwargs is given then it corresponds to option-value pairs that should
be modified."""
if option is None and not kwargs:
split1 = self.tk.splitlist(self.tk.call(self._w, 'tag', 'configure', tagname))
result = {}
for item in split1:
res = self.tk.splitlist(item)
result[res[0]] = res[1:]
return result
elif option:
return self.tk.call(self._w, 'tag', 'configure', tagname, '-%s' % option)
else:
args = ()
for key, val in kwargs.items():
args += ('-%s' % key, val)
self.tk.call(self._w, 'tag', 'configure', tagname, *args)
def tag_delete(self, tagname):
self.tk.call(self._w, 'tag', 'delete', tagname)
def tag_exists(self, tagname):
return self.getboolean(self.tk.call(self._w, 'tag', 'exists', tagname))
def tag_includes(self, tagname, index):
return self.getboolean(self.tk.call(self._w, 'tag', 'includes', tagname, index))
def tag_lower(self, tagname, belowthis=None):
self.tk.call(self._w, 'tag', 'lower', belowthis)
def tag_names(self, pattern=None):
return self.tk.call(self._w, 'tag', 'names', pattern)
def tag_raise(self, tagname, abovethis=None):
self.tk.call(self._w, 'tag', 'raise', tagname, abovethis)
def tag_row(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'row', tagname, *args)
def validate(self, index):
"""Explicitly validates the specified index based on the current
callback set for the validatecommand option. Return 0 or 1 based on
whether the cell was validated."""
return self.tk.call(self._w, 'validate', index)
@property
def version(self):
"""Return tktable's package version."""
return self.tk.call(self._w, 'version')
def width(self, column=None, **kwargs):
"""If column and kwargs are not given, a dict describing all columns
for which a width has been set is returned.
If column is given, the width of that column is returnd.
If kwargs is given, then it sets the key/value pairs, where key is a
column and value represents the width for the column."""
if column is None and not kwargs:
pairs = self.tk.splitlist(self.tk.call(self._w, 'width'))
return dict(pair.split() for pair in pairs)
elif column is not None:
return int(self.tk.call(self._w, 'width', str(column)))
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'width', *args)
def window_cget(self, index, option):
return self.tk.call(self._w, 'window', 'cget', index, option)
def window_configure(self, index, option=None, **kwargs):
"""Query or modify options associated with the embedded window given
by index. This should also be used to add a new embedded window into
the table.
If no option is specified, a dict describing all of the available
options for index is returned. If option is specified, then the
command returns a list describing the one named option. Lastly, if
kwargs is given then it corresponds to option-value pairs that should
be modified."""
if option is None and not kwargs:
return self.tk.call(self._w, 'window', 'configure', index)
elif option:
return self.tk.call(self._w, 'window', 'configure', index, '-%s' % option)
else:
args = ()
for key, val in kwargs.items():
args += ('-%s' % key, val)
self.tk.call(self._w, 'window', 'configure', index, *args)
def window_delete(self, *indexes):
self.tk.call(self._w, 'window', 'delete', *indexes)
def window_move(self, index_from, index_to):
self.tk.call(self._w, 'window', 'move', index_from, index_to)
def window_names(self, pattern=None):
return self.tk.call(self._w, 'window', 'names', pattern)
def xview(self, index=None):
"""If index is not given a tuple containing two fractions is returned,
each fraction is between 0 and 1. Together they describe the
horizontal span that is visible in the window.
If index is given the view in the window is adjusted so that the
column given by index is displayed at the left edge of the window."""
res = self.tk.call(self._w, 'xview', index)
if index is None:
return self._getdoubles(res)
def xview_moveto(self, fraction):
"""Adjusts the view in the window so that fraction of the total width
of the table text is off-screen to the left. The fraction parameter
must be a fraction between 0 and 1."""
self.tk.call(self._w, 'xview', 'moveto', fraction)
def xview_scroll(self, *L):
# change by frank gao for attach scrollbar 11/11/2010
"""Shift the view in the window left or right according to number and
what. The 'number' parameter must be an integer. The 'what' parameter
must be either units or pages or an abbreviation of one of these.
If 'what' is units, the view adjusts left or right by number cells on
the display; if it is pages then the view adjusts by number screenfuls.
If 'number' is negative then cells farther to the left become visible;
if it is positive then cells farther to the right become visible. """
# self.tk.call(self._w, 'xview', 'scroll', number, what)
op, howMany = L[0], L[1]
if op == 'scroll':
units = L[2]
self.tk.call(self._w, 'xview', 'scroll', howMany, units)
elif op == 'moveto':
self.tk.call(self._w, 'xview', 'moveto', howMany)
def yview(self, index=None):
"""If index is not given a tuple containing two fractions is returned,
each fraction is between 0 and 1. The first element gives the position
of the table element at the top of the window, relative to the table
as a whole. The second element gives the position of the table element
just after the last one in the window, relative to the table as a
whole.
If index is given the view in the window is adjusted so that the
row given by index is displayed at the top of the window."""
res = self.tk.call(self._w, 'yview', index)
if index is None:
return self._getdoubles(res)
def yview_moveto(self, fraction):
"""Adjusts the view in the window so that the element given by
fraction appears at the top of the window. The fraction parameter
must be a fraction between 0 and 1."""
self.tk.call(self._w, 'yview', 'moveto', fraction)
def yview_scroll(self, *L):
# change by frank gao for attach scrollbar 11/11/2010
"""Adjust the view in the window up or down according to number and
what. The 'number' parameter must be an integer. The 'what' parameter
must be either units or pages or an abbreviation of one of these.
If 'what' is units, the view adjusts up or down by number cells; if it
is pages then the view adjusts by number screenfuls.
If 'number' is negative then earlier elements become visible; if it
is positive then later elements become visible. """
# self.tk.call(self._w, 'yview', 'scroll', number, what)
op, howMany = L[0], L[1]
if op == 'scroll':
units = L[2]
self.tk.call(self._w, 'yview', 'scroll', howMany, units)
elif op == 'moveto':
self.tk.call(self._w, 'yview', 'moveto', howMany)
Ancestors (in MRO)
- Table
- tkinter.Widget
- tkinter.BaseWidget
- tkinter.Misc
- tkinter.Pack
- tkinter.Place
- tkinter.Grid
- builtins.object
Static methods
def __init__(
self, master=None, **kw)
Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.
def __init__(self, master=None, **kw):
master = _setup_master(master)
global _TKTABLE_LOADED
if not _TKTABLE_LOADED:
tktable_lib = os.environ.get('TKTABLE_LIBRARY')
if tktable_lib:
master.tk.eval('global auto_path; lappend auto_path {%s}' % tktable_lib)
try:
master.tk.call('package', 'require', 'Tktable')
except tkinter._tkinter.TclError:
print("\033[93mThe Tcl/Tk extension named 'Tktable' is not installed in your system.\n"
"You need first to install it to use this wrapper library.\n"
"If you're seeing this message, you probably downloaded this module from "
"this Github's repository 'https://github.com/nelson-brochado/tktable'.\033[0m\n")
_TKTABLE_LOADED = True
tkinter.Widget.__init__(self, master, 'table', kw)
def activate(
self, index)
Set the active cell to the one indicated by index.
def activate(self, index):
"""Set the active cell to the one indicated by index."""
self.tk.call(self._w, 'activate', index)
def after(
self, ms, func=None, *args)
Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel.
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
if not func:
# I'd rather use time.sleep(ms*0.001)
self.tk.call('after', ms)
else:
def callit():
try:
func(*args)
finally:
try:
self.deletecommand(name)
except TclError:
pass
callit.__name__ = func.__name__
name = self._register(callit)
return self.tk.call('after', ms, name)
def after_cancel(
self, id)
Cancel scheduling of function identified with ID.
Identifier returned by after or after_idle must be given as first parameter.
def after_cancel(self, id):
"""Cancel scheduling of function identified with ID.
Identifier returned by after or after_idle must be
given as first parameter."""
try:
data = self.tk.call('after', 'info', id)
# In Tk 8.3, splitlist returns: (script, type)
# In Tk 8.4, splitlist may return (script, type) or (script,)
script = self.tk.splitlist(data)[0]
self.deletecommand(script)
except TclError:
pass
self.tk.call('after', 'cancel', id)
def after_idle(
self, func, *args)
Call FUNC once if the Tcl main loop has no event to process.
Return an identifier to cancel the scheduling with after_cancel.
def after_idle(self, func, *args):
"""Call FUNC once if the Tcl main loop has no event to
process.
Return an identifier to cancel the scheduling with
after_cancel."""
return self.after('idle', func, *args)
def anchor(
self, anchor=None)
The anchor value controls how to place the grid within the master when no row/column has any weight.
The default anchor is nw.
def grid_anchor(self, anchor=None): # new in Tk 8.5
"""The anchor value controls how to place the grid within the
master when no row/column has any weight.
The default anchor is nw."""
self.tk.call('grid', 'anchor', self._w, anchor)
def bbox(
self, first, last=None)
Return the bounding box for the specified cell (range) as a 4-tuple of x, y, width and height in pixels. It clips the box to the visible portion, if any, otherwise an empty tuple is returned.
def bbox(self, first, last=None):
"""Return the bounding box for the specified cell (range) as a
4-tuple of x, y, width and height in pixels. It clips the box to
the visible portion, if any, otherwise an empty tuple is returned."""
return self._getints(self.tk.call(self._w, 'bbox', first, last)) or ()
def bell(
self, displayof=0)
Ring a display's bell.
def bell(self, displayof=0):
"""Ring a display's bell."""
self.tk.call(('bell',) + self._displayof(displayof))
def bind(
self, sequence=None, func=None, add=None)
Bind to this widget at event SEQUENCE a call to function FUNC.
SEQUENCE is a string of concatenated event
patterns. An event pattern is of the form
FUNC will be called if the event sequence occurs with an instance of Event as argument. If the return value of FUNC is "break" no further bound function is invoked.
An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function.
Bind will return an identifier to allow deletion of the bound function with unbind without memory leak.
If FUNC or SEQUENCE is omitted the bound function or list of bound events are returned.
def bind(self, sequence=None, func=None, add=None):
"""Bind to this widget at event SEQUENCE a call to function FUNC.
SEQUENCE is a string of concatenated event
patterns. An event pattern is of the form
where MODIFIER is one
of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
B3, Alt, Button4, B4, Double, Button5, B5 Triple,
Mod1, M1. TYPE is one of Activate, Enter, Map,
ButtonPress, Button, Expose, Motion, ButtonRelease
FocusIn, MouseWheel, Circulate, FocusOut, Property,
Colormap, Gravity Reparent, Configure, KeyPress, Key,
Unmap, Deactivate, KeyRelease Visibility, Destroy,
Leave and DETAIL is the button number for ButtonPress,
ButtonRelease and DETAIL is the Keysym for KeyPress and
KeyRelease. Examples are
for pressing Control and mouse button 1 or
for pressing A and the Alt key (KeyPress can be omitted).
An event pattern can also be a virtual event of the form
<> where AString can be arbitrary. This
event can be generated by event_generate.
If events are concatenated they must appear shortly
after each other.
FUNC will be called if the event sequence occurs with an
instance of Event as argument. If the return value of FUNC is
"break" no further bound function is invoked.
An additional boolean parameter ADD specifies whether FUNC will
be called additionally to the other bound function or whether
it will replace the previous function.
Bind will return an identifier to allow deletion of the bound function with
unbind without memory leak.
If FUNC or SEQUENCE is omitted the bound function or list
of bound events are returned."""
return self._bind(('bind', self._w), sequence, func, add)
def bind_all(
self, sequence=None, func=None, add=None)
Bind to all widgets at an event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.
def bind_all(self, sequence=None, func=None, add=None):
"""Bind to all widgets at an event SEQUENCE a call to function FUNC.
An additional boolean parameter ADD specifies whether FUNC will
be called additionally to the other bound function or whether
it will replace the previous function. See bind for the return value."""
return self._bind(('bind', 'all'), sequence, func, add, 0)
def bind_class(
self, className, sequence=None, func=None, add=None)
Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.
def bind_class(self, className, sequence=None, func=None, add=None):
"""Bind to widgets with bindtag CLASSNAME at event
SEQUENCE a call of function FUNC. An additional
boolean parameter ADD specifies whether FUNC will be
called additionally to the other bound function or
whether it will replace the previous function. See bind for
the return value."""
return self._bind(('bind', className), sequence, func, add, 0)
def bindtags(
self, tagList=None)
Set or get the list of bindtags for this widget.
With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are set to this list. The bindtags determine in which order events are processed (see bind).
def cget(
self, key)
Return the resource value for a KEY given as string.
def cget(self, key):
"""Return the resource value for a KEY given as string."""
return self.tk.call(self._w, 'cget', '-' + key)
def clear(
self, option, first=None, last=None)
This is a convenience routine to clear certain state information managed by the table. first and last represent valid table indices. If neither are specified, then the command operates on the whole table.
def clear(self, option, first=None, last=None):
"""This is a convenience routine to clear certain state information
managed by the table. first and last represent valid table indices.
If neither are specified, then the command operates on the whole
table."""
self.tk.call(self._w, 'clear', option, first, last)
def clear_all(
self, first=None, last=None)
Perform all of the above clear functions on the specified area.
def clear_all(self, first=None, last=None):
"""Perform all of the above clear functions on the specified area."""
self.clear('all', first, last)
def clear_cache(
self, first=None, last=None)
Clear the specified section of the cache, if the table has been keeping one.
def clear_cache(self, first=None, last=None):
"""Clear the specified section of the cache, if the table has been
keeping one."""
self.clear('cache', first, last)
def clear_sizes(
self, first=None, last=None)
Clear the specified row and column areas of specific height/width dimensions. When just one index is specified, for example 2,0, that is interpreted as row 2 and column 0.
def clear_sizes(self, first=None, last=None):
"""Clear the specified row and column areas of specific height/width
dimensions. When just one index is specified, for example 2,0, that
is interpreted as row 2 and column 0."""
self.clear('sizes', first, last)
def clear_tags(
self, first=None, last=None)
Clear the specified area of tags (all row, column and cell tags).
def clipboard_append(
self, string, **kw)
Append STRING to the Tk clipboard.
A widget specified at the optional displayof keyword argument specifies the target display. The clipboard can be retrieved with selection_get.
def clipboard_append(self, string, **kw):
"""Append STRING to the Tk clipboard.
A widget specified at the optional displayof keyword
argument specifies the target display. The clipboard
can be retrieved with selection_get."""
if 'displayof' not in kw: kw['displayof'] = self._w
self.tk.call(('clipboard', 'append') + self._options(kw)
+ ('--', string))
def clipboard_clear(
self, **kw)
Clear the data in the Tk clipboard.
A widget specified for the optional displayof keyword argument specifies the target display.
def clipboard_clear(self, **kw):
"""Clear the data in the Tk clipboard.
A widget specified for the optional displayof keyword
argument specifies the target display."""
if 'displayof' not in kw: kw['displayof'] = self._w
self.tk.call(('clipboard', 'clear') + self._options(kw))
def clipboard_get(
self, **kw)
Retrieve data from the clipboard on window's display.
The window keyword defaults to the root window of the Tkinter application.
The type keyword specifies the form in which the data is to be returned and should be an atom name such as STRING or FILE_NAME. Type defaults to STRING, except on X11, where the default is to try UTF8_STRING and fall back to STRING.
This command is equivalent to:
selection_get(CLIPBOARD)
def clipboard_get(self, **kw):
"""Retrieve data from the clipboard on window's display.
The window keyword defaults to the root window of the Tkinter
application.
The type keyword specifies the form in which the data is
to be returned and should be an atom name such as STRING
or FILE_NAME. Type defaults to STRING, except on X11, where the default
is to try UTF8_STRING and fall back to STRING.
This command is equivalent to:
selection_get(CLIPBOARD)
"""
if 'type' not in kw and self._windowingsystem == 'x11':
try:
kw['type'] = 'UTF8_STRING'
return self.tk.call(('clipboard', 'get') + self._options(kw))
except TclError:
del kw['type']
return self.tk.call(('clipboard', 'get') + self._options(kw))
def columnconfigure(
self, index, cnf={}, **kw)
Configure column INDEX of a grid.
Valid resources are minsize (minimum size of the column), weight (how much does additional space propagate to this column) and pad (how much space to let additionally).
def grid_columnconfigure(self, index, cnf={}, **kw):
"""Configure column INDEX of a grid.
Valid resources are minsize (minimum size of the column),
weight (how much does additional space propagate to this column)
and pad (how much space to let additionally)."""
return self._grid_configure('columnconfigure', index, cnf, kw)
def config(
self, cnf=None, **kw)
Configure resources of a widget.
The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys.
def configure(self, cnf=None, **kw):
"""Configure resources of a widget.
The values for resources are specified as keyword
arguments. To get an overview about
the allowed keyword arguments call the method keys.
"""
return self._configure('configure', cnf, kw)
def configure(
self, cnf=None, **kw)
Configure resources of a widget.
The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys.
def configure(self, cnf=None, **kw):
"""Configure resources of a widget.
The values for resources are specified as keyword
arguments. To get an overview about
the allowed keyword arguments call the method keys.
"""
return self._configure('configure', cnf, kw)
def curselection(
self, value=None)
With no arguments, it returns the sorted indices of the currently selected cells. Otherwise it sets all the selected cells to the given value if there is an associated ArrayVar and the state is not disabled.
def curselection(self, value=None):
"""With no arguments, it returns the sorted indices of the currently
selected cells. Otherwise it sets all the selected cells to the given
value if there is an associated ArrayVar and the state is not
disabled."""
result = self.tk.call(self._w, 'curselection', value)
if value is None:
return result
def curvalue(
self, value=None)
If no value is given, the value of the cell being edited (indexed by active) is returned, else it is set to the given value.
def curvalue(self, value=None):
"""If no value is given, the value of the cell being edited (indexed
by active) is returned, else it is set to the given value. """
return self.tk.call(self._w, 'curvalue', value)
def delete_active(
self, index1, index2=None)
Deletes text from the active cell. If only one index is given, it deletes the character after that index, otherwise it deletes from the first index to the second. index can be a number, insert or end.
def delete_active(self, index1, index2=None):
"""Deletes text from the active cell. If only one index is given,
it deletes the character after that index, otherwise it deletes from
the first index to the second. index can be a number, insert or end."""
self.tk.call(self._w, 'delete', 'active', index1, index2)
def delete_cols(
self, index, count=None, switches=None)
def delete_cols(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'delete', 'cols', *args)
def delete_rows(
self, index, count=None, switches=None)
def delete_rows(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'delete', 'rows', *args)
def deletecommand(
self, name)
Internal function.
Delete the Tcl command provided in NAME.
def deletecommand(self, name):
"""Internal function.
Delete the Tcl command provided in NAME."""
#print '- Tkinter: deleted command', name
self.tk.deletecommand(name)
try:
self._tclCommands.remove(name)
except ValueError:
pass
def destroy(
self)
Destroy this and all descendants widgets.
def destroy(self):
"""Destroy this and all descendants widgets."""
for c in list(self.children.values()): c.destroy()
self.tk.call('destroy', self._w)
if self._name in self.master.children:
del self.master.children[self._name]
Misc.destroy(self)
def event_add(
self, virtual, *sequences)
Bind a virtual event VIRTUAL (of the form <
def event_add(self, virtual, *sequences):
"""Bind a virtual event VIRTUAL (of the form <>)
to an event SEQUENCE such that the virtual event is triggered
whenever SEQUENCE occurs."""
args = ('event', 'add', virtual) + sequences
self.tk.call(args)
def event_delete(
self, virtual, *sequences)
Unbind a virtual event VIRTUAL from SEQUENCE.
def event_delete(self, virtual, *sequences):
"""Unbind a virtual event VIRTUAL from SEQUENCE."""
args = ('event', 'delete', virtual) + sequences
self.tk.call(args)
def event_generate(
self, sequence, **kw)
Generate an event SEQUENCE. Additional keyword arguments specify parameter of the event (e.g. x, y, rootx, rooty).
def event_generate(self, sequence, **kw):
"""Generate an event SEQUENCE. Additional
keyword arguments specify parameter of the event
(e.g. x, y, rootx, rooty)."""
args = ('event', 'generate', self._w, sequence)
for k, v in kw.items():
args = args + ('-%s' % k, str(v))
self.tk.call(args)
def event_info(
self, virtual=None)
Return a list of all virtual events or the information about the SEQUENCE bound to the virtual event VIRTUAL.
def event_info(self, virtual=None):
"""Return a list of all virtual events or the information
about the SEQUENCE bound to the virtual event VIRTUAL."""
return self.tk.splitlist(
self.tk.call('event', 'info', virtual))
def focus(
self)
Direct input focus to this widget.
If the application currently does not have the focus this widget will get the focus if the application gets the focus through the window manager.
def focus_set(self):
"""Direct input focus to this widget.
If the application currently does not have the focus
this widget will get the focus if the application gets
the focus through the window manager."""
self.tk.call('focus', self._w)
def focus_displayof(
self)
Return the widget which has currently the focus on the display where this widget is located.
Return None if the application does not have the focus.
def focus_displayof(self):
"""Return the widget which has currently the focus on the
display where this widget is located.
Return None if the application does not have the focus."""
name = self.tk.call('focus', '-displayof', self._w)
if name == 'none' or not name: return None
return self._nametowidget(name)
def focus_force(
self)
Direct input focus to this widget even if the application does not have the focus. Use with caution!
def focus_force(self):
"""Direct input focus to this widget even if the
application does not have the focus. Use with
caution!"""
self.tk.call('focus', '-force', self._w)
def focus_get(
self)
Return the widget which has currently the focus in the application.
Use focus_displayof to allow working with several displays. Return None if application does not have the focus.
def focus_get(self):
"""Return the widget which has currently the focus in the
application.
Use focus_displayof to allow working with several
displays. Return None if application does not have
the focus."""
name = self.tk.call('focus')
if name == 'none' or not name: return None
return self._nametowidget(name)
def focus_lastfor(
self)
Return the widget which would have the focus if top level for this widget gets the focus from the window manager.
def focus_lastfor(self):
"""Return the widget which would have the focus if top level
for this widget gets the focus from the window manager."""
name = self.tk.call('focus', '-lastfor', self._w)
if name == 'none' or not name: return None
return self._nametowidget(name)
def focus_set(
self)
Direct input focus to this widget.
If the application currently does not have the focus this widget will get the focus if the application gets the focus through the window manager.
def focus_set(self):
"""Direct input focus to this widget.
If the application currently does not have the focus
this widget will get the focus if the application gets
the focus through the window manager."""
self.tk.call('focus', self._w)
def forget(
self)
Unmap this widget and do not use it for the packing order.
def pack_forget(self):
"""Unmap this widget and do not use it for the packing order."""
self.tk.call('pack', 'forget', self._w)
def get(
self, first, last=None)
Returns the value of the cells specified by the table indices first and (optionally) last.
def get(self, first, last=None):
"""Returns the value of the cells specified by the table indices
first and (optionally) last."""
return self.tk.call(self._w, 'get', first, last)
def getboolean(
self, s)
Return a boolean value for Tcl boolean values true and false given as parameter.
def getboolean(self, s):
"""Return a boolean value for Tcl boolean values true and false given as parameter."""
try:
return self.tk.getboolean(s)
except TclError:
raise ValueError("invalid literal for getboolean()")
def getdouble(
self, s)
def getdouble(self, s):
try:
return self.tk.getdouble(s)
except TclError as exc:
raise ValueError(str(exc))
def getint(
self, s)
def getint(self, s):
try:
return self.tk.getint(s)
except TclError as exc:
raise ValueError(str(exc))
def getvar(
self, name='PY_VAR')
Return value of Tcl variable NAME.
def getvar(self, name='PY_VAR'):
"""Return value of Tcl variable NAME."""
return self.tk.getvar(name)
def grab_current(
self)
Return widget which has currently the grab in this application or None.
def grab_current(self):
"""Return widget which has currently the grab in this application
or None."""
name = self.tk.call('grab', 'current', self._w)
if not name: return None
return self._nametowidget(name)
def grab_release(
self)
Release grab for this widget if currently set.
def grab_release(self):
"""Release grab for this widget if currently set."""
self.tk.call('grab', 'release', self._w)
def grab_set(
self)
Set grab for this widget.
A grab directs all events to this and descendant widgets in the application.
def grab_set(self):
"""Set grab for this widget.
A grab directs all events to this and descendant
widgets in the application."""
self.tk.call('grab', 'set', self._w)
def grab_set_global(
self)
Set global grab for this widget.
A global grab directs all events to this and descendant widgets on the display. Use with caution - other applications do not get events anymore.
def grab_set_global(self):
"""Set global grab for this widget.
A global grab directs all events to this and
descendant widgets on the display. Use with caution -
other applications do not get events anymore."""
self.tk.call('grab', 'set', '-global', self._w)
def grab_status(
self)
Return None, "local" or "global" if this widget has no, a local or a global grab.
def grab_status(self):
"""Return None, "local" or "global" if this widget has
no, a local or a global grab."""
status = self.tk.call('grab', 'status', self._w)
if status == 'none': status = None
return status
def grid(
self, cnf={}, **kw)
Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction row=number - use cell identified with given row (starting with 0) rowspan=number - this widget will span several rows sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary
def grid_configure(self, cnf={}, **kw):
"""Position a widget in the parent widget in a grid. Use as options:
column=number - use cell identified with given column (starting with 0)
columnspan=number - this widget will span several columns
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
row=number - use cell identified with given row (starting with 0)
rowspan=number - this widget will span several rows
sticky=NSEW - if cell is larger on which sides will this
widget stick to the cell boundary
"""
self.tk.call(
('grid', 'configure', self._w)
+ self._options(cnf, kw))
def grid_anchor(
self, anchor=None)
The anchor value controls how to place the grid within the master when no row/column has any weight.
The default anchor is nw.
def grid_anchor(self, anchor=None): # new in Tk 8.5
"""The anchor value controls how to place the grid within the
master when no row/column has any weight.
The default anchor is nw."""
self.tk.call('grid', 'anchor', self._w, anchor)
def grid_bbox(
self, column=None, row=None, col2=None, row2=None)
Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid.
If COLUMN, ROW is given the bounding box applies from the cell with row and column 0 to the specified cell. If COL2 and ROW2 are given the bounding box starts at that cell.
The returned integers specify the offset of the upper left corner in the master widget and the width and height.
def grid_bbox(self, column=None, row=None, col2=None, row2=None):
"""Return a tuple of integer coordinates for the bounding
box of this widget controlled by the geometry manager grid.
If COLUMN, ROW is given the bounding box applies from
the cell with row and column 0 to the specified
cell. If COL2 and ROW2 are given the bounding box
starts at that cell.
The returned integers specify the offset of the upper left
corner in the master widget and the width and height.
"""
args = ('grid', 'bbox', self._w)
if column is not None and row is not None:
args = args + (column, row)
if col2 is not None and row2 is not None:
args = args + (col2, row2)
return self._getints(self.tk.call(*args)) or None
def grid_columnconfigure(
self, index, cnf={}, **kw)
Configure column INDEX of a grid.
Valid resources are minsize (minimum size of the column), weight (how much does additional space propagate to this column) and pad (how much space to let additionally).
def grid_columnconfigure(self, index, cnf={}, **kw):
"""Configure column INDEX of a grid.
Valid resources are minsize (minimum size of the column),
weight (how much does additional space propagate to this column)
and pad (how much space to let additionally)."""
return self._grid_configure('columnconfigure', index, cnf, kw)
def grid_configure(
self, cnf={}, **kw)
Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction row=number - use cell identified with given row (starting with 0) rowspan=number - this widget will span several rows sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary
def grid_configure(self, cnf={}, **kw):
"""Position a widget in the parent widget in a grid. Use as options:
column=number - use cell identified with given column (starting with 0)
columnspan=number - this widget will span several columns
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
row=number - use cell identified with given row (starting with 0)
rowspan=number - this widget will span several rows
sticky=NSEW - if cell is larger on which sides will this
widget stick to the cell boundary
"""
self.tk.call(
('grid', 'configure', self._w)
+ self._options(cnf, kw))
def grid_forget(
self)
Unmap this widget.
def grid_forget(self):
"""Unmap this widget."""
self.tk.call('grid', 'forget', self._w)
def grid_info(
self)
Return information about the options for positioning this widget in a grid.
def grid_info(self):
"""Return information about the options
for positioning this widget in a grid."""
d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
if 'in' in d:
d['in'] = self.nametowidget(d['in'])
return d
def grid_location(
self, x, y)
Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.
def grid_location(self, x, y):
"""Return a tuple of column and row which identify the cell
at which the pixel at position X and Y inside the master
widget is located."""
return self._getints(
self.tk.call(
'grid', 'location', self._w, x, y)) or None
def grid_propagate(
self, flag=['_noarg_'])
Set or get the status for propagation of geometry information.
A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given, the current setting will be returned.
def grid_propagate(self, flag=_noarg_):
"""Set or get the status for propagation of geometry information.
A boolean argument specifies whether the geometry information
of the slaves will determine the size of this widget. If no argument
is given, the current setting will be returned.
"""
if flag is Misc._noarg_:
return self._getboolean(self.tk.call(
'grid', 'propagate', self._w))
else:
self.tk.call('grid', 'propagate', self._w, flag)
def grid_remove(
self)
Unmap this widget but remember the grid options.
def grid_remove(self):
"""Unmap this widget but remember the grid options."""
self.tk.call('grid', 'remove', self._w)
def grid_rowconfigure(
self, index, cnf={}, **kw)
Configure row INDEX of a grid.
Valid resources are minsize (minimum size of the row), weight (how much does additional space propagate to this row) and pad (how much space to let additionally).
def grid_rowconfigure(self, index, cnf={}, **kw):
"""Configure row INDEX of a grid.
Valid resources are minsize (minimum size of the row),
weight (how much does additional space propagate to this row)
and pad (how much space to let additionally)."""
return self._grid_configure('rowconfigure', index, cnf, kw)
def grid_size(
self)
Return a tuple of the number of column and rows in the grid.
def grid_size(self):
"""Return a tuple of the number of column and rows in the grid."""
return self._getints(
self.tk.call('grid', 'size', self._w)) or None
def grid_slaves(
self, row=None, column=None)
Return a list of all slaves of this widget in its packing order.
def grid_slaves(self, row=None, column=None):
"""Return a list of all slaves of this widget
in its packing order."""
args = ()
if row is not None:
args = args + ('-row', row)
if column is not None:
args = args + ('-column', column)
return [self._nametowidget(x) for x in
self.tk.splitlist(self.tk.call(
('grid', 'slaves', self._w) + args))]
def height(
self, row=None, **kwargs)
If row and kwargs are not given, a list describing all rows for which a width has been set is returned. If row is given, the height of that row is returnd. If kwargs is given, then it sets the key/value pairs, where key is a row and value represents the height for the row.
def height(self, row=None, **kwargs):
"""If row and kwargs are not given, a list describing all rows for
which a width has been set is returned.
If row is given, the height of that row is returnd.
If kwargs is given, then it sets the key/value pairs, where key is a
row and value represents the height for the row."""
if row is None and not kwargs:
pairs = self.tk.splitlist(self.tk.call(self._w, 'height'))
return dict(pair.split() for pair in pairs)
elif row:
return int(self.tk.call(self._w, 'height', str(row)))
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'height', *args)
When called without args, it returns all the hidden cells (those cells covered by a spanning cell). If one index is specified, it returns the spanning cell covering that index, if any. If multiple indices are specified, it returns 1 if all indices are hidden cells, 0 otherwise.
def icursor(
self, arg=None)
If arg is not specified, return the location of the insertion cursor in the active cell. Otherwise, set the cursor to that point in the string.
0 is before the first character, you can also use insert or end for the current insertion point or the end of the text. If there is no active cell, or the cell or table is disabled, this will return -1.
def icursor(self, arg=None):
"""If arg is not specified, return the location of the insertion
cursor in the active cell. Otherwise, set the cursor to that point in
the string.
0 is before the first character, you can also use insert or end for
the current insertion point or the end of the text. If there is no
active cell, or the cell or table is disabled, this will return -1."""
return self.tk.call(self._w, 'icursor', arg)
def image_names(
self)
Return a list of all existing image names.
def image_names(self):
"""Return a list of all existing image names."""
return self.tk.splitlist(self.tk.call('image', 'names'))
def image_types(
self)
Return a list of all available image types (e.g. phote bitmap).
def image_types(self):
"""Return a list of all available image types (e.g. phote bitmap)."""
return self.tk.splitlist(self.tk.call('image', 'types'))
def index(
self, index, rc=None)
Return the integer cell coordinate that corresponds to index in the form row, col. If rc is specified, it must be either 'row' or 'col' so only the row or column index is returned.
def index(self, index, rc=None):
"""Return the integer cell coordinate that corresponds to index in the
form row, col. If rc is specified, it must be either 'row' or 'col' so
only the row or column index is returned."""
res = self.tk.call(self._w, 'index', index, rc)
if rc is None:
return res
else:
return int(res)
def info(
self)
Return information about the packing options for this widget.
def pack_info(self):
"""Return information about the packing options
for this widget."""
d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
if 'in' in d:
d['in'] = self.nametowidget(d['in'])
return d
def insert_active(
self, index, value)
The value is a text string which is inserted at the index postion of the active cell. The cursor is then positioned after the new text. index can be a number, insert or end.
def insert_active(self, index, value):
"""The value is a text string which is inserted at the index postion
of the active cell. The cursor is then positioned after the new text.
index can be a number, insert or end. """
self.tk.call(self._w, 'insert', 'active', index, value)
def insert_cols(
self, index, count=None, switches=None)
def insert_cols(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'insert', 'cols', *args)
def insert_rows(
self, index, count=None, switches=None)
def insert_rows(self, index, count=None, switches=None):
args = self._handle_switches(switches) + (index, count)
self.tk.call(self._w, 'insert', 'rows', *args)
def keys(
self)
Return a list of all resource names of this widget.
def keys(self):
"""Return a list of all resource names of this widget."""
return [x[0][1:] for x in
self.tk.splitlist(self.tk.call(self._w, 'configure'))]
def lift(
self, aboveThis=None)
Raise this widget in the stacking order.
def tkraise(self, aboveThis=None):
"""Raise this widget in the stacking order."""
self.tk.call('raise', self._w, aboveThis)
def location(
self, x, y)
Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.
def grid_location(self, x, y):
"""Return a tuple of column and row which identify the cell
at which the pixel at position X and Y inside the master
widget is located."""
return self._getints(
self.tk.call(
'grid', 'location', self._w, x, y)) or None
def lower(
self, belowThis=None)
Lower this widget in the stacking order.
def lower(self, belowThis=None):
"""Lower this widget in the stacking order."""
self.tk.call('lower', self._w, belowThis)
def mainloop(
self, n=0)
Call the mainloop of Tk.
def mainloop(self, n=0):
"""Call the mainloop of Tk."""
self.tk.mainloop(n)
def nametowidget(
self, name)
Return the Tkinter instance of a widget identified by its Tcl name NAME.
def nametowidget(self, name):
"""Return the Tkinter instance of a widget identified by
its Tcl name NAME."""
name = str(name).split('.')
w = self
if not name[0]:
w = w._root()
name = name[1:]
for n in name:
if not n:
break
w = w.children[n]
return w
def option_add(
self, pattern, value, priority=None)
Set a VALUE (second parameter) for an option PATTERN (first parameter).
An optional third parameter gives the numeric priority (defaults to 80).
def option_add(self, pattern, value, priority = None):
"""Set a VALUE (second parameter) for an option
PATTERN (first parameter).
An optional third parameter gives the numeric priority
(defaults to 80)."""
self.tk.call('option', 'add', pattern, value, priority)
def option_clear(
self)
Clear the option database.
It will be reloaded if option_add is called.
def option_clear(self):
"""Clear the option database.
It will be reloaded if option_add is called."""
self.tk.call('option', 'clear')
def option_get(
self, name, className)
Return the value for an option NAME for this widget with CLASSNAME.
Values with higher priority override lower values.
def option_get(self, name, className):
"""Return the value for an option NAME for this widget
with CLASSNAME.
Values with higher priority override lower values."""
return self.tk.call('option', 'get', self._w, name, className)
def option_readfile(
self, fileName, priority=None)
Read file FILENAME into the option database.
An optional second parameter gives the numeric priority.
def option_readfile(self, fileName, priority = None):
"""Read file FILENAME into the option database.
An optional second parameter gives the numeric
priority."""
self.tk.call('option', 'readfile', fileName, priority)
def pack(
self, cnf={}, **kw)
Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction before=widget - pack it before you will pack widget expand=bool - expand widget if parent size grows fill=NONE or X or Y or BOTH - fill widget if widget grows in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
def pack_configure(self, cnf={}, **kw):
"""Pack a widget in the parent widget. Use as options:
after=widget - pack it after you have packed widget
anchor=NSEW (or subset) - position widget according to
given direction
before=widget - pack it before you will pack widget
expand=bool - expand widget if parent size grows
fill=NONE or X or Y or BOTH - fill widget if widget grows
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
"""
self.tk.call(
('pack', 'configure', self._w)
+ self._options(cnf, kw))
def pack_configure(
self, cnf={}, **kw)
Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction before=widget - pack it before you will pack widget expand=bool - expand widget if parent size grows fill=NONE or X or Y or BOTH - fill widget if widget grows in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
def pack_configure(self, cnf={}, **kw):
"""Pack a widget in the parent widget. Use as options:
after=widget - pack it after you have packed widget
anchor=NSEW (or subset) - position widget according to
given direction
before=widget - pack it before you will pack widget
expand=bool - expand widget if parent size grows
fill=NONE or X or Y or BOTH - fill widget if widget grows
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
"""
self.tk.call(
('pack', 'configure', self._w)
+ self._options(cnf, kw))
def pack_forget(
self)
Unmap this widget and do not use it for the packing order.
def pack_forget(self):
"""Unmap this widget and do not use it for the packing order."""
self.tk.call('pack', 'forget', self._w)
def pack_info(
self)
Return information about the packing options for this widget.
def pack_info(self):
"""Return information about the packing options
for this widget."""
d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
if 'in' in d:
d['in'] = self.nametowidget(d['in'])
return d
def pack_propagate(
self, flag=['_noarg_'])
Set or get the status for propagation of geometry information.
A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned.
def pack_propagate(self, flag=_noarg_):
"""Set or get the status for propagation of geometry information.
A boolean argument specifies whether the geometry information
of the slaves will determine the size of this widget. If no argument
is given the current setting will be returned.
"""
if flag is Misc._noarg_:
return self._getboolean(self.tk.call(
'pack', 'propagate', self._w))
else:
self.tk.call('pack', 'propagate', self._w, flag)
def pack_slaves(
self)
Return a list of all slaves of this widget in its packing order.
def pack_slaves(self):
"""Return a list of all slaves of this widget
in its packing order."""
return [self._nametowidget(x) for x in
self.tk.splitlist(
self.tk.call('pack', 'slaves', self._w))]
def place(
self, cnf={}, **kw)
Place a widget in the parent widget. Use as options: in=master - master relative to which the widget is placed in_=master - see 'in' option description x=amount - locate anchor of this widget at position x of master y=amount - locate anchor of this widget at position y of master relx=amount - locate anchor of this widget between 0.0 and 1.0 relative to width of master (1.0 is right edge) rely=amount - locate anchor of this widget between 0.0 and 1.0 relative to height of master (1.0 is bottom edge) anchor=NSEW (or subset) - position anchor according to given direction width=amount - width of this widget in pixel height=amount - height of this widget in pixel relwidth=amount - width of this widget between 0.0 and 1.0 relative to width of master (1.0 is the same width as the master) relheight=amount - height of this widget between 0.0 and 1.0 relative to height of master (1.0 is the same height as the master) bordermode="inside" or "outside" - whether to take border width of master widget into account
def place_configure(self, cnf={}, **kw):
"""Place a widget in the parent widget. Use as options:
in=master - master relative to which the widget is placed
in_=master - see 'in' option description
x=amount - locate anchor of this widget at position x of master
y=amount - locate anchor of this widget at position y of master
relx=amount - locate anchor of this widget between 0.0 and 1.0
relative to width of master (1.0 is right edge)
rely=amount - locate anchor of this widget between 0.0 and 1.0
relative to height of master (1.0 is bottom edge)
anchor=NSEW (or subset) - position anchor according to given direction
width=amount - width of this widget in pixel
height=amount - height of this widget in pixel
relwidth=amount - width of this widget between 0.0 and 1.0
relative to width of master (1.0 is the same width
as the master)
relheight=amount - height of this widget between 0.0 and 1.0
relative to height of master (1.0 is the same
height as the master)
bordermode="inside" or "outside" - whether to take border width of
master widget into account
"""
self.tk.call(
('place', 'configure', self._w)
+ self._options(cnf, kw))
def place_configure(
self, cnf={}, **kw)
Place a widget in the parent widget. Use as options: in=master - master relative to which the widget is placed in_=master - see 'in' option description x=amount - locate anchor of this widget at position x of master y=amount - locate anchor of this widget at position y of master relx=amount - locate anchor of this widget between 0.0 and 1.0 relative to width of master (1.0 is right edge) rely=amount - locate anchor of this widget between 0.0 and 1.0 relative to height of master (1.0 is bottom edge) anchor=NSEW (or subset) - position anchor according to given direction width=amount - width of this widget in pixel height=amount - height of this widget in pixel relwidth=amount - width of this widget between 0.0 and 1.0 relative to width of master (1.0 is the same width as the master) relheight=amount - height of this widget between 0.0 and 1.0 relative to height of master (1.0 is the same height as the master) bordermode="inside" or "outside" - whether to take border width of master widget into account
def place_configure(self, cnf={}, **kw):
"""Place a widget in the parent widget. Use as options:
in=master - master relative to which the widget is placed
in_=master - see 'in' option description
x=amount - locate anchor of this widget at position x of master
y=amount - locate anchor of this widget at position y of master
relx=amount - locate anchor of this widget between 0.0 and 1.0
relative to width of master (1.0 is right edge)
rely=amount - locate anchor of this widget between 0.0 and 1.0
relative to height of master (1.0 is bottom edge)
anchor=NSEW (or subset) - position anchor according to given direction
width=amount - width of this widget in pixel
height=amount - height of this widget in pixel
relwidth=amount - width of this widget between 0.0 and 1.0
relative to width of master (1.0 is the same width
as the master)
relheight=amount - height of this widget between 0.0 and 1.0
relative to height of master (1.0 is the same
height as the master)
bordermode="inside" or "outside" - whether to take border width of
master widget into account
"""
self.tk.call(
('place', 'configure', self._w)
+ self._options(cnf, kw))
def place_forget(
self)
Unmap this widget.
def place_forget(self):
"""Unmap this widget."""
self.tk.call('place', 'forget', self._w)
def place_info(
self)
Return information about the placing options for this widget.
def place_info(self):
"""Return information about the placing options
for this widget."""
d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
if 'in' in d:
d['in'] = self.nametowidget(d['in'])
return d
def place_slaves(
self)
Return a list of all slaves of this widget in its packing order.
def place_slaves(self):
"""Return a list of all slaves of this widget
in its packing order."""
return [self._nametowidget(x) for x in
self.tk.splitlist(
self.tk.call(
'place', 'slaves', self._w))]
def propagate(
self, flag=['_noarg_'])
Set or get the status for propagation of geometry information.
A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned.
def pack_propagate(self, flag=_noarg_):
"""Set or get the status for propagation of geometry information.
A boolean argument specifies whether the geometry information
of the slaves will determine the size of this widget. If no argument
is given the current setting will be returned.
"""
if flag is Misc._noarg_:
return self._getboolean(self.tk.call(
'pack', 'propagate', self._w))
else:
self.tk.call('pack', 'propagate', self._w, flag)
def quit(
self)
Quit the Tcl interpreter. All widgets will be destroyed.
def quit(self):
"""Quit the Tcl interpreter. All widgets will be destroyed."""
self.tk.quit()
def register(
self, func, subst=None, needcleanup=1)
Return a newly created Tcl function. If this function is called, the Python function FUNC will be executed. An optional function SUBST can be given which will be executed before FUNC.
def _register(self, func, subst=None, needcleanup=1):
"""Return a newly created Tcl function. If this
function is called, the Python function FUNC will
be executed. An optional function SUBST can
be given which will be executed before FUNC."""
f = CallWrapper(func, subst, self).__call__
name = repr(id(f))
try:
func = func.__func__
except AttributeError:
pass
try:
name = name + func.__name__
except AttributeError:
pass
self.tk.createcommand(name, f)
if needcleanup:
if self._tclCommands is None:
self._tclCommands = []
self._tclCommands.append(name)
return name
def reread(
self)
Rereads the old contents of the cell back into the editing buffer.
Useful for a key binding when
def reread(self):
"""Rereads the old contents of the cell back into the editing buffer.
Useful for a key binding when is pressed to abort the edit
(a default binding)."""
self.tk.call(self._w, 'reread')
def rowconfigure(
self, index, cnf={}, **kw)
Configure row INDEX of a grid.
Valid resources are minsize (minimum size of the row), weight (how much does additional space propagate to this row) and pad (how much space to let additionally).
def grid_rowconfigure(self, index, cnf={}, **kw):
"""Configure row INDEX of a grid.
Valid resources are minsize (minimum size of the row),
weight (how much does additional space propagate to this row)
and pad (how much space to let additionally)."""
return self._grid_configure('rowconfigure', index, cnf, kw)
def scan_dragto(
self, x, y)
def scan_dragto(self, x, y):
self.tk.call(self._w, 'scan', 'dragto', x, y)
def scan_mark(
self, x, y)
def scan_mark(self, x, y):
self.tk.call(self._w, 'scan', 'mark', x, y)
def see(
self, index)
def see(self, index):
self.tk.call(self._w, 'see', index)
def selection_anchor(
self, index)
def selection_anchor(self, index):
self.tk.call(self._w, 'selection', 'anchor', index)
def selection_clear(
self, first, last=None)
Clear the current X selection.
def selection_clear(self, first, last=None):
self.tk.call(self._w, 'selection', 'clear', first, last)
def selection_get(
self, **kw)
Return the contents of the current X selection.
A keyword parameter selection specifies the name of the selection and defaults to PRIMARY. A keyword parameter displayof specifies a widget on the display to use. A keyword parameter type specifies the form of data to be fetched, defaulting to STRING except on X11, where UTF8_STRING is tried before STRING.
def selection_get(self, **kw):
"""Return the contents of the current X selection.
A keyword parameter selection specifies the name of
the selection and defaults to PRIMARY. A keyword
parameter displayof specifies a widget on the display
to use. A keyword parameter type specifies the form of data to be
fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
before STRING."""
if 'displayof' not in kw: kw['displayof'] = self._w
if 'type' not in kw and self._windowingsystem == 'x11':
try:
kw['type'] = 'UTF8_STRING'
return self.tk.call(('selection', 'get') + self._options(kw))
except TclError:
del kw['type']
return self.tk.call(('selection', 'get') + self._options(kw))
def selection_handle(
self, command, **kw)
Specify a function COMMAND to call if the X selection owned by this widget is queried by another application.
This function must return the contents of the selection. The function will be called with the arguments OFFSET and LENGTH which allows the chunking of very long selections. The following keyword parameters can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).
def selection_handle(self, command, **kw):
"""Specify a function COMMAND to call if the X
selection owned by this widget is queried by another
application.
This function must return the contents of the
selection. The function will be called with the
arguments OFFSET and LENGTH which allows the chunking
of very long selections. The following keyword
parameters can be provided:
selection - name of the selection (default PRIMARY),
type - type of the selection (e.g. STRING, FILE_NAME)."""
name = self._register(command)
self.tk.call(('selection', 'handle') + self._options(kw)
+ (self._w, name))
def selection_includes(
self, index)
def selection_includes(self, index):
return self.getboolean(self.tk.call(self._w, 'selection', 'includes', index))
def selection_own(
self, **kw)
Become owner of X selection.
A keyword parameter selection specifies the name of the selection (default PRIMARY).
def selection_own(self, **kw):
"""Become owner of X selection.
A keyword parameter selection specifies the name of
the selection (default PRIMARY)."""
self.tk.call(('selection', 'own') +
self._options(kw) + (self._w,))
def selection_own_get(
self, **kw)
Return owner of X selection.
The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).
def selection_own_get(self, **kw):
"""Return owner of X selection.
The following keyword parameter can
be provided:
selection - name of the selection (default PRIMARY),
type - type of the selection (e.g. STRING, FILE_NAME)."""
if 'displayof' not in kw: kw['displayof'] = self._w
name = self.tk.call(('selection', 'own') + self._options(kw))
if not name: return None
return self._nametowidget(name)
def selection_set(
self, first, last=None)
def selection_set(self, first, last=None):
self.tk.call(self._w, 'selection', 'set', first, last)
def send(
self, interp, cmd, *args)
Send Tcl command CMD to different interpreter INTERP to be executed.
def send(self, interp, cmd, *args):
"""Send Tcl command CMD to different interpreter INTERP to be executed."""
return self.tk.call(('send', interp, cmd) + args)
def set(
self, rc=None, index=None, *args, **kwargs)
If rc is specified (either 'row' or 'col') then it is assumes that args (if given) represents values which will be set into the subsequent columns (if row is specified) or rows (for col). If index is not None and args is not given, then it will return the value(s) for the cell(s) specified.
If kwargs is given, assumes that each key in kwargs is a index in this table and sets the specified index to the associated value. Table validation will not be triggered via this method.
Note that the table must have an associated array (defined through the variable option) in order to this work.
def set(self, rc=None, index=None, *args, **kwargs):
"""If rc is specified (either 'row' or 'col') then it is assumes that
args (if given) represents values which will be set into the
subsequent columns (if row is specified) or rows (for col).
If index is not None and args is not given, then it will return the
value(s) for the cell(s) specified.
If kwargs is given, assumes that each key in kwargs is a index in this
table and sets the specified index to the associated value. Table
validation will not be triggered via this method.
Note that the table must have an associated array (defined through the
variable option) in order to this work."""
if not args and index is not None:
if rc:
args = (rc, index)
else:
args = (index,)
return self.tk.call(self._w, 'set', *args)
if rc is None:
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'set', *args)
else:
self.tk.call(self._w, 'set', rc, index, args)
def setvar(
self, name='PY_VAR', value='1')
Set Tcl variable NAME to VALUE.
def setvar(self, name='PY_VAR', value='1'):
"""Set Tcl variable NAME to VALUE."""
self.tk.setvar(name, value)
def size(
self)
Return a tuple of the number of column and rows in the grid.
def grid_size(self):
"""Return a tuple of the number of column and rows in the grid."""
return self._getints(
self.tk.call('grid', 'size', self._w)) or None
def slaves(
self)
Return a list of all slaves of this widget in its packing order.
def pack_slaves(self):
"""Return a list of all slaves of this widget
in its packing order."""
return [self._nametowidget(x) for x in
self.tk.splitlist(
self.tk.call('pack', 'slaves', self._w))]
def spans(
self, index=None, **kwargs)
Manipulate row/col spans.
When called with no arguments, all known spans are returned as a dict. When called with only the index, the span for that index only is returned, if any. Otherwise kwargs is assumed to contain keys/values pairs used to set spans. A span starts at the row,col defined by a key and continues for the specified number of rows,cols specified by its value. A span of 0,0 unsets any span on that cell.
def spans(self, index=None, **kwargs):
"""Manipulate row/col spans.
When called with no arguments, all known spans are returned as a dict.
When called with only the index, the span for that index only is
returned, if any. Otherwise kwargs is assumed to contain keys/values
pairs used to set spans. A span starts at the row,col defined by a key
and continues for the specified number of rows,cols specified by
its value. A span of 0,0 unsets any span on that cell."""
if kwargs:
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'spans', *args)
else:
return self.tk.call(self._w, 'spans', index)
def tag_cell(
self, tagname, *args)
def tag_cell(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'cell', tagname, *args)
def tag_cget(
self, tagname, option)
def tag_cget(self, tagname, option):
return self.tk.call(self._w, 'tag', 'cget', tagname, '-%s' % option)
def tag_col(
self, tagname, *args)
def tag_col(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'col', tagname, *args)
def tag_configure(
self, tagname, option=None, **kwargs)
Query or modify options associated with the tag given by tagname.
If no option is specified, a dict describing all of the available options for tagname is returned. If option is specified, then the command returns a list describing the one named option. Lastly, if kwargs is given then it corresponds to option-value pairs that should be modified.
def tag_configure(self, tagname, option=None, **kwargs):
"""Query or modify options associated with the tag given by tagname.
If no option is specified, a dict describing all of the available
options for tagname is returned. If option is specified, then the
command returns a list describing the one named option. Lastly, if
kwargs is given then it corresponds to option-value pairs that should
be modified."""
if option is None and not kwargs:
split1 = self.tk.splitlist(self.tk.call(self._w, 'tag', 'configure', tagname))
result = {}
for item in split1:
res = self.tk.splitlist(item)
result[res[0]] = res[1:]
return result
elif option:
return self.tk.call(self._w, 'tag', 'configure', tagname, '-%s' % option)
else:
args = ()
for key, val in kwargs.items():
args += ('-%s' % key, val)
self.tk.call(self._w, 'tag', 'configure', tagname, *args)
def tag_delete(
self, tagname)
def tag_delete(self, tagname):
self.tk.call(self._w, 'tag', 'delete', tagname)
def tag_exists(
self, tagname)
def tag_exists(self, tagname):
return self.getboolean(self.tk.call(self._w, 'tag', 'exists', tagname))
def tag_includes(
self, tagname, index)
def tag_includes(self, tagname, index):
return self.getboolean(self.tk.call(self._w, 'tag', 'includes', tagname, index))
def tag_lower(
self, tagname, belowthis=None)
def tag_lower(self, tagname, belowthis=None):
self.tk.call(self._w, 'tag', 'lower', belowthis)
def tag_names(
self, pattern=None)
def tag_names(self, pattern=None):
return self.tk.call(self._w, 'tag', 'names', pattern)
def tag_raise(
self, tagname, abovethis=None)
def tag_raise(self, tagname, abovethis=None):
self.tk.call(self._w, 'tag', 'raise', tagname, abovethis)
def tag_row(
self, tagname, *args)
def tag_row(self, tagname, *args):
return self.tk.call(self._w, 'tag', 'row', tagname, *args)
def tk_bisque(
self)
Change the color scheme to light brown as used in Tk 3.6 and before.
def tk_bisque(self):
"""Change the color scheme to light brown as used in Tk 3.6 and before."""
self.tk.call('tk_bisque')
def tk_focusFollowsMouse(
self)
The widget under mouse will get automatically focus. Can not be disabled easily.
def tk_focusFollowsMouse(self):
"""The widget under mouse will get automatically focus. Can not
be disabled easily."""
self.tk.call('tk_focusFollowsMouse')
def tk_focusNext(
self)
Return the next widget in the focus order which follows widget which has currently the focus.
The focus order first goes to the next child, then to the children of the child recursively and then to the next sibling which is higher in the stacking order. A widget is omitted if it has the takefocus resource set to 0.
def tk_focusNext(self):
"""Return the next widget in the focus order which follows
widget which has currently the focus.
The focus order first goes to the next child, then to
the children of the child recursively and then to the
next sibling which is higher in the stacking order. A
widget is omitted if it has the takefocus resource set
to 0."""
name = self.tk.call('tk_focusNext', self._w)
if not name: return None
return self._nametowidget(name)
def tk_focusPrev(
self)
Return previous widget in the focus order. See tk_focusNext for details.
def tk_focusPrev(self):
"""Return previous widget in the focus order. See tk_focusNext for details."""
name = self.tk.call('tk_focusPrev', self._w)
if not name: return None
return self._nametowidget(name)
Do not use. Needed in Tk 3.6 and earlier.
def tk_setPalette(
self, *args, **kw)
Set a new color scheme for all widget elements.
A single color as argument will cause that all colors of Tk widget elements are derived from this. Alternatively several keyword parameters and its associated colors can be given. The following keywords are valid: activeBackground, foreground, selectColor, activeForeground, highlightBackground, selectBackground, background, highlightColor, selectForeground, disabledForeground, insertBackground, troughColor.
def tk_setPalette(self, *args, **kw):
"""Set a new color scheme for all widget elements.
A single color as argument will cause that all colors of Tk
widget elements are derived from this.
Alternatively several keyword parameters and its associated
colors can be given. The following keywords are valid:
activeBackground, foreground, selectColor,
activeForeground, highlightBackground, selectBackground,
background, highlightColor, selectForeground,
disabledForeground, insertBackground, troughColor."""
self.tk.call(('tk_setPalette',)
+ _flatten(args) + _flatten(list(kw.items())))
def tk_strictMotif(
self, boolean=None)
Set Tcl internal variable, whether the look and feel should adhere to Motif.
A parameter of 1 means adhere to Motif (e.g. no color change if mouse passes over slider). Returns the set value.
def tk_strictMotif(self, boolean=None):
"""Set Tcl internal variable, whether the look and feel
should adhere to Motif.
A parameter of 1 means adhere to Motif (e.g. no color
change if mouse passes over slider).
Returns the set value."""
return self.tk.getboolean(self.tk.call(
'set', 'tk_strictMotif', boolean))
def tkraise(
self, aboveThis=None)
Raise this widget in the stacking order.
def tkraise(self, aboveThis=None):
"""Raise this widget in the stacking order."""
self.tk.call('raise', self._w, aboveThis)
def unbind(
self, sequence, funcid=None)
Unbind for this widget for event SEQUENCE the function identified with FUNCID.
def unbind(self, sequence, funcid=None):
"""Unbind for this widget for event SEQUENCE the
function identified with FUNCID."""
self.tk.call('bind', self._w, sequence, '')
if funcid:
self.deletecommand(funcid)
def unbind_all(
self, sequence)
Unbind for all widgets for event SEQUENCE all functions.
def unbind_all(self, sequence):
"""Unbind for all widgets for event SEQUENCE all functions."""
self.tk.call('bind', 'all' , sequence, '')
def unbind_class(
self, className, sequence)
Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE all functions.
def unbind_class(self, className, sequence):
"""Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
all functions."""
self.tk.call('bind', className , sequence, '')
def update(
self)
Enter event loop until all pending events have been processed by Tcl.
def update(self):
"""Enter event loop until all pending events have been processed by Tcl."""
self.tk.call('update')
def update_idletasks(
self)
Enter event loop until all idle callbacks have been called. This will update the display of windows but not process events caused by the user.
def update_idletasks(self):
"""Enter event loop until all idle callbacks have been called. This
will update the display of windows but not process events caused by
the user."""
self.tk.call('update', 'idletasks')
def validate(
self, index)
Explicitly validates the specified index based on the current callback set for the validatecommand option. Return 0 or 1 based on whether the cell was validated.
def validate(self, index):
"""Explicitly validates the specified index based on the current
callback set for the validatecommand option. Return 0 or 1 based on
whether the cell was validated."""
return self.tk.call(self._w, 'validate', index)
def wait_variable(
self, name='PY_VAR')
Wait until the variable is modified.
A parameter of type IntVar, StringVar, DoubleVar or BooleanVar must be given.
def wait_variable(self, name='PY_VAR'):
"""Wait until the variable is modified.
A parameter of type IntVar, StringVar, DoubleVar or
BooleanVar must be given."""
self.tk.call('tkwait', 'variable', name)
def wait_visibility(
self, window=None)
Wait until the visibility of a WIDGET changes (e.g. it appears).
If no parameter is given self is used.
def wait_visibility(self, window=None):
"""Wait until the visibility of a WIDGET changes
(e.g. it appears).
If no parameter is given self is used."""
if window is None:
window = self
self.tk.call('tkwait', 'visibility', window._w)
def wait_window(
self, window=None)
Wait until a WIDGET is destroyed.
If no parameter is given self is used.
def wait_window(self, window=None):
"""Wait until a WIDGET is destroyed.
If no parameter is given self is used."""
if window is None:
window = self
self.tk.call('tkwait', 'window', window._w)
def waitvar(
self, name='PY_VAR')
Wait until the variable is modified.
A parameter of type IntVar, StringVar, DoubleVar or BooleanVar must be given.
def wait_variable(self, name='PY_VAR'):
"""Wait until the variable is modified.
A parameter of type IntVar, StringVar, DoubleVar or
BooleanVar must be given."""
self.tk.call('tkwait', 'variable', name)
def width(
self, column=None, **kwargs)
If column and kwargs are not given, a dict describing all columns for which a width has been set is returned. If column is given, the width of that column is returnd. If kwargs is given, then it sets the key/value pairs, where key is a column and value represents the width for the column.
def width(self, column=None, **kwargs):
"""If column and kwargs are not given, a dict describing all columns
for which a width has been set is returned.
If column is given, the width of that column is returnd.
If kwargs is given, then it sets the key/value pairs, where key is a
column and value represents the width for the column."""
if column is None and not kwargs:
pairs = self.tk.splitlist(self.tk.call(self._w, 'width'))
return dict(pair.split() for pair in pairs)
elif column is not None:
return int(self.tk.call(self._w, 'width', str(column)))
args = tkinter._flatten(list(kwargs.items()))
self.tk.call(self._w, 'width', *args)
def window_cget(
self, index, option)
def window_cget(self, index, option):
return self.tk.call(self._w, 'window', 'cget', index, option)
def window_configure(
self, index, option=None, **kwargs)
Query or modify options associated with the embedded window given by index. This should also be used to add a new embedded window into the table.
If no option is specified, a dict describing all of the available options for index is returned. If option is specified, then the command returns a list describing the one named option. Lastly, if kwargs is given then it corresponds to option-value pairs that should be modified.
def window_configure(self, index, option=None, **kwargs):
"""Query or modify options associated with the embedded window given
by index. This should also be used to add a new embedded window into
the table.
If no option is specified, a dict describing all of the available
options for index is returned. If option is specified, then the
command returns a list describing the one named option. Lastly, if
kwargs is given then it corresponds to option-value pairs that should
be modified."""
if option is None and not kwargs:
return self.tk.call(self._w, 'window', 'configure', index)
elif option:
return self.tk.call(self._w, 'window', 'configure', index, '-%s' % option)
else:
args = ()
for key, val in kwargs.items():
args += ('-%s' % key, val)
self.tk.call(self._w, 'window', 'configure', index, *args)
def window_delete(
self, *indexes)
def window_delete(self, *indexes):
self.tk.call(self._w, 'window', 'delete', *indexes)
def window_move(
self, index_from, index_to)
def window_move(self, index_from, index_to):
self.tk.call(self._w, 'window', 'move', index_from, index_to)
def window_names(
self, pattern=None)
def window_names(self, pattern=None):
return self.tk.call(self._w, 'window', 'names', pattern)
def winfo_atom(
self, name, displayof=0)
Return integer which represents atom NAME.
def winfo_atom(self, name, displayof=0):
"""Return integer which represents atom NAME."""
args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
return self.tk.getint(self.tk.call(args))
def winfo_atomname(
self, id, displayof=0)
Return name of atom with identifier ID.
def winfo_atomname(self, id, displayof=0):
"""Return name of atom with identifier ID."""
args = ('winfo', 'atomname') \
+ self._displayof(displayof) + (id,)
return self.tk.call(args)
def winfo_cells(
self)
Return number of cells in the colormap for this widget.
def winfo_cells(self):
"""Return number of cells in the colormap for this widget."""
return self.tk.getint(
self.tk.call('winfo', 'cells', self._w))
def winfo_children(
self)
Return a list of all widgets which are children of this widget.
def winfo_children(self):
"""Return a list of all widgets which are children of this widget."""
result = []
for child in self.tk.splitlist(
self.tk.call('winfo', 'children', self._w)):
try:
# Tcl sometimes returns extra windows, e.g. for
# menus; those need to be skipped
result.append(self._nametowidget(child))
except KeyError:
pass
return result
def winfo_class(
self)
Return window class name of this widget.
def winfo_class(self):
"""Return window class name of this widget."""
return self.tk.call('winfo', 'class', self._w)
def winfo_colormapfull(
self)
Return true if at the last color request the colormap was full.
def winfo_colormapfull(self):
"""Return true if at the last color request the colormap was full."""
return self.tk.getboolean(
self.tk.call('winfo', 'colormapfull', self._w))
def winfo_containing(
self, rootX, rootY, displayof=0)
Return the widget which is at the root coordinates ROOTX, ROOTY.
def winfo_containing(self, rootX, rootY, displayof=0):
"""Return the widget which is at the root coordinates ROOTX, ROOTY."""
args = ('winfo', 'containing') \
+ self._displayof(displayof) + (rootX, rootY)
name = self.tk.call(args)
if not name: return None
return self._nametowidget(name)
def winfo_depth(
self)
Return the number of bits per pixel.
def winfo_depth(self):
"""Return the number of bits per pixel."""
return self.tk.getint(self.tk.call('winfo', 'depth', self._w))
def winfo_exists(
self)
Return true if this widget exists.
def winfo_exists(self):
"""Return true if this widget exists."""
return self.tk.getint(
self.tk.call('winfo', 'exists', self._w))
def winfo_fpixels(
self, number)
Return the number of pixels for the given distance NUMBER (e.g. "3c") as float.
def winfo_fpixels(self, number):
"""Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float."""
return self.tk.getdouble(self.tk.call(
'winfo', 'fpixels', self._w, number))
def winfo_geometry(
self)
Return geometry string for this widget in the form "widthxheight+X+Y".
def winfo_geometry(self):
"""Return geometry string for this widget in the form "widthxheight+X+Y"."""
return self.tk.call('winfo', 'geometry', self._w)
def winfo_height(
self)
Return height of this widget.
def winfo_height(self):
"""Return height of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'height', self._w))
def winfo_id(
self)
Return identifier ID for this widget.
def winfo_id(self):
"""Return identifier ID for this widget."""
return self.tk.getint(
self.tk.call('winfo', 'id', self._w))
def winfo_interps(
self, displayof=0)
Return the name of all Tcl interpreters for this display.
def winfo_interps(self, displayof=0):
"""Return the name of all Tcl interpreters for this display."""
args = ('winfo', 'interps') + self._displayof(displayof)
return self.tk.splitlist(self.tk.call(args))
def winfo_ismapped(
self)
Return true if this widget is mapped.
def winfo_ismapped(self):
"""Return true if this widget is mapped."""
return self.tk.getint(
self.tk.call('winfo', 'ismapped', self._w))
def winfo_manager(
self)
Return the window mananger name for this widget.
def winfo_manager(self):
"""Return the window mananger name for this widget."""
return self.tk.call('winfo', 'manager', self._w)
def winfo_name(
self)
Return the name of this widget.
def winfo_name(self):
"""Return the name of this widget."""
return self.tk.call('winfo', 'name', self._w)
def winfo_parent(
self)
Return the name of the parent of this widget.
def winfo_parent(self):
"""Return the name of the parent of this widget."""
return self.tk.call('winfo', 'parent', self._w)
def winfo_pathname(
self, id, displayof=0)
Return the pathname of the widget given by ID.
def winfo_pathname(self, id, displayof=0):
"""Return the pathname of the widget given by ID."""
args = ('winfo', 'pathname') \
+ self._displayof(displayof) + (id,)
return self.tk.call(args)
def winfo_pixels(
self, number)
Rounded integer value of winfo_fpixels.
def winfo_pixels(self, number):
"""Rounded integer value of winfo_fpixels."""
return self.tk.getint(
self.tk.call('winfo', 'pixels', self._w, number))
def winfo_pointerx(
self)
Return the x coordinate of the pointer on the root window.
def winfo_pointerx(self):
"""Return the x coordinate of the pointer on the root window."""
return self.tk.getint(
self.tk.call('winfo', 'pointerx', self._w))
def winfo_pointerxy(
self)
Return a tuple of x and y coordinates of the pointer on the root window.
def winfo_pointerxy(self):
"""Return a tuple of x and y coordinates of the pointer on the root window."""
return self._getints(
self.tk.call('winfo', 'pointerxy', self._w))
def winfo_pointery(
self)
Return the y coordinate of the pointer on the root window.
def winfo_pointery(self):
"""Return the y coordinate of the pointer on the root window."""
return self.tk.getint(
self.tk.call('winfo', 'pointery', self._w))
def winfo_reqheight(
self)
Return requested height of this widget.
def winfo_reqheight(self):
"""Return requested height of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'reqheight', self._w))
def winfo_reqwidth(
self)
Return requested width of this widget.
def winfo_reqwidth(self):
"""Return requested width of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'reqwidth', self._w))
def winfo_rgb(
self, color)
Return tuple of decimal values for red, green, blue for COLOR in this widget.
def winfo_rgb(self, color):
"""Return tuple of decimal values for red, green, blue for
COLOR in this widget."""
return self._getints(
self.tk.call('winfo', 'rgb', self._w, color))
def winfo_rootx(
self)
Return x coordinate of upper left corner of this widget on the root window.
def winfo_rootx(self):
"""Return x coordinate of upper left corner of this widget on the
root window."""
return self.tk.getint(
self.tk.call('winfo', 'rootx', self._w))
def winfo_rooty(
self)
Return y coordinate of upper left corner of this widget on the root window.
def winfo_rooty(self):
"""Return y coordinate of upper left corner of this widget on the
root window."""
return self.tk.getint(
self.tk.call('winfo', 'rooty', self._w))
def winfo_screen(
self)
Return the screen name of this widget.
def winfo_screen(self):
"""Return the screen name of this widget."""
return self.tk.call('winfo', 'screen', self._w)
def winfo_screencells(
self)
Return the number of the cells in the colormap of the screen of this widget.
def winfo_screencells(self):
"""Return the number of the cells in the colormap of the screen
of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'screencells', self._w))
def winfo_screendepth(
self)
Return the number of bits per pixel of the root window of the screen of this widget.
def winfo_screendepth(self):
"""Return the number of bits per pixel of the root window of the
screen of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'screendepth', self._w))
def winfo_screenheight(
self)
Return the number of pixels of the height of the screen of this widget in pixel.
def winfo_screenheight(self):
"""Return the number of pixels of the height of the screen of this widget
in pixel."""
return self.tk.getint(
self.tk.call('winfo', 'screenheight', self._w))
def winfo_screenmmheight(
self)
Return the number of pixels of the height of the screen of this widget in mm.
def winfo_screenmmheight(self):
"""Return the number of pixels of the height of the screen of
this widget in mm."""
return self.tk.getint(
self.tk.call('winfo', 'screenmmheight', self._w))
def winfo_screenmmwidth(
self)
Return the number of pixels of the width of the screen of this widget in mm.
def winfo_screenmmwidth(self):
"""Return the number of pixels of the width of the screen of
this widget in mm."""
return self.tk.getint(
self.tk.call('winfo', 'screenmmwidth', self._w))
def winfo_screenvisual(
self)
Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the default colormodel of this screen.
def winfo_screenvisual(self):
"""Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the default
colormodel of this screen."""
return self.tk.call('winfo', 'screenvisual', self._w)
def winfo_screenwidth(
self)
Return the number of pixels of the width of the screen of this widget in pixel.
def winfo_screenwidth(self):
"""Return the number of pixels of the width of the screen of
this widget in pixel."""
return self.tk.getint(
self.tk.call('winfo', 'screenwidth', self._w))
def winfo_server(
self)
Return information of the X-Server of the screen of this widget in the form "XmajorRminor vendor vendorVersion".
def winfo_server(self):
"""Return information of the X-Server of the screen of this widget in
the form "XmajorRminor vendor vendorVersion"."""
return self.tk.call('winfo', 'server', self._w)
def winfo_toplevel(
self)
Return the toplevel widget of this widget.
def winfo_toplevel(self):
"""Return the toplevel widget of this widget."""
return self._nametowidget(self.tk.call(
'winfo', 'toplevel', self._w))
def winfo_viewable(
self)
Return true if the widget and all its higher ancestors are mapped.
def winfo_viewable(self):
"""Return true if the widget and all its higher ancestors are mapped."""
return self.tk.getint(
self.tk.call('winfo', 'viewable', self._w))
def winfo_visual(
self)
Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the colormodel of this widget.
def winfo_visual(self):
"""Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget."""
return self.tk.call('winfo', 'visual', self._w)
def winfo_visualid(
self)
Return the X identifier for the visual for this widget.
def winfo_visualid(self):
"""Return the X identifier for the visual for this widget."""
return self.tk.call('winfo', 'visualid', self._w)
def winfo_visualsavailable(
self, includeids=0)
Return a list of all visuals available for the screen of this widget.
Each item in the list consists of a visual name (see winfo_visual), a depth and if INCLUDEIDS=1 is given also the X identifier.
def winfo_visualsavailable(self, includeids=0):
"""Return a list of all visuals available for the screen
of this widget.
Each item in the list consists of a visual name (see winfo_visual), a
depth and if INCLUDEIDS=1 is given also the X identifier."""
data = self.tk.split(
self.tk.call('winfo', 'visualsavailable', self._w,
includeids and 'includeids' or None))
if isinstance(data, str):
data = [self.tk.split(data)]
return [self.__winfo_parseitem(x) for x in data]
def winfo_vrootheight(
self)
Return the height of the virtual root window associated with this widget in pixels. If there is no virtual root window return the height of the screen.
def winfo_vrootheight(self):
"""Return the height of the virtual root window associated with this
widget in pixels. If there is no virtual root window return the
height of the screen."""
return self.tk.getint(
self.tk.call('winfo', 'vrootheight', self._w))
def winfo_vrootwidth(
self)
Return the width of the virtual root window associated with this widget in pixel. If there is no virtual root window return the width of the screen.
def winfo_vrootwidth(self):
"""Return the width of the virtual root window associated with this
widget in pixel. If there is no virtual root window return the
width of the screen."""
return self.tk.getint(
self.tk.call('winfo', 'vrootwidth', self._w))
def winfo_vrootx(
self)
Return the x offset of the virtual root relative to the root window of the screen of this widget.
def winfo_vrootx(self):
"""Return the x offset of the virtual root relative to the root
window of the screen of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'vrootx', self._w))
def winfo_vrooty(
self)
Return the y offset of the virtual root relative to the root window of the screen of this widget.
def winfo_vrooty(self):
"""Return the y offset of the virtual root relative to the root
window of the screen of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'vrooty', self._w))
def winfo_width(
self)
Return the width of this widget.
def winfo_width(self):
"""Return the width of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'width', self._w))
def winfo_x(
self)
Return the x coordinate of the upper left corner of this widget in the parent.
def winfo_x(self):
"""Return the x coordinate of the upper left corner of this widget
in the parent."""
return self.tk.getint(
self.tk.call('winfo', 'x', self._w))
def winfo_y(
self)
Return the y coordinate of the upper left corner of this widget in the parent.
def winfo_y(self):