Wednesday, January 16, 2019

Tkinter Widgets

A widget is a graphical object that is available from the Tkinter library. It is a kind of graphical building block. The widgets are implemented as classes in Tkinter. Each widget therefore has a constructor, a destructor, its own set of properties and methods, and so on. While most other GUI toolkits have a very complex widget hierarchy, Tkinter’s hierarchy is extremely simple. All widgets (like Button, Checkbutton, etc.) are derived from the Widget class. All widget subclasses occupy the same level in the hierarchy tree.

Widget classes

There are many different widget classes built into tkinter which are as follows:


  • A Frame is a container widget which is placed inside a window, which can have its own border and background – it is used to group related widgets together in an application’s layout.
  • Toplevel is a container widget which is displayed as a separate window.
  • Canvas is a widget for drawing graphics. In advanced usage, it can also be used to create custom widgets – because we can draw anything we like inside it, and make it interactive.
  • Text displays formatted text, which can be editable and can have embedded images.
  • A Button usually maps directly onto a user action – when the user clicks on a button, something should happen.
  • A Label is a simple widget which displays a short piece of text or an image, but usually isn’t interactive.
  • A Message is similar to a Label, but is designed for longer bodies of text which need to be wrapped.
  • A Scrollbar allows the user to scroll through content which is too large to be visible all at once.
  • Checkbutton, Radiobutton, Listbox, Entry and Scale are different kinds of input widgets – they allow the user to enter information into the program.
  • Menu and Menubutton are used to create pull-down menus.
Let's explore these widgets in the following sections.

1. Toplevel - The Toplevel is technically not a widget, although this is more or less transparent to the user.

2. Button - The Button widget is a rectangular widget that is able to display text. This text can
occupy several lines (if the text itself contains newlines or if wrapping occurs). Moreover,
this text can have an underlined character (usually indicating a keyboard shortcut).
Buttons are usually used to execute an action when they are clicked, so they offer the
command option which associates a callback with the event corresponding to a mouse
click with the left mouse button on the widget.

The Button widget provides the following options and methods:

a. default - Specifies one of three states (DISABLED, NORMAL,ACTIVE) which determines if the button should be drawn with the style used for default buttons.

b. flash() - Redraws the button several times, alternating between active and normal appearance.
c. invoke() -  Invokes the callback associated with the button widget.

3. Checkbutton - The Checkbutton displays some text (or image) along with a small square called indicator. The indicator is drawn differently depending on the state of the checkbutton (selected or not). The Checkbutton widget supports the following option:

a. indicatoron -  Specifies whether the indicator should be drawn or not. If false, the Checkbutton acts like a toggle button.

b. offvalue -  Specifies the value to store in the variable associated with the Checkbutton when it is not selected.

c. onvalue -  Specifies the value to store in the variable associated with the Checkbutton when it is selected.

d. selectcolor - Specifies the background color to use for the widget whenever it is selected. This color applies to the indicator only if indicatoron is TRUE. It applies to the whole widget when this option is turned off.

e. variable - Specifies the name of a Tkinter variable that is to be assigned the values specified by the onvalue and offvalue options.

The Checkbutton widget defines the following methods:

a. deselect() - Deselects the checkbutton and stores the value specified by the offvalue option to its associated variable.

b. flash() - Redraws the button several times, alternating between active and normal colors.

c. invoke() - Simulates a click on the widget (toggles the state, updates the variable and invokes the callback associated with the checkbutton, if any).

d. select() - Selects the checkbutton and stores the value specified by the onvalue option to its associated variable.

e. toggle() - Similar to invoke(), but does not invoke the callback associated with the checkbutton.

4. Entry - The Entry widget allows users to type and edit a single line of text. A portion of this
text can be selected. The Entry widget provides the following options:

a. show - Controls how to display the contents of the widget. If non-empty, the widget will replace characters to be displayed by the first character of the specified string. To get a password entry widget, use ”*”.

The Entry widget defines the following methods:

a. delete(index), delete(from,to) - Delete the character at index, or within the given range.
Use delete(0, END) to delete all text in the widget.

b. get() - Returns the current contents of the widget.

c. insert(index, text) - Inserts text at the given index. Use insert(INSERT, text) to insert text at the cursor, insert(END, text) to append text to the widget.

5. Frame - The Frame widget is a rectangular container for other widgets. It is primarily used as
a geometry master since it allows to group widgets. 

All Tkinter widgets have access to the specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place.

The pack() Method − This geometry manager organizes widgets in blocks before placing them in the parent widget.

The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.

The place() Method − This geometry manager organizes widgets by placing them in a specific position in the parent widget.

Frame can have an unvisible border which is useful to space widgets. It can also have a visible border with a 3D effect, or no border at all. The Frame widget does not provide any methods except the standardWidget methods. The Frame widget provides the following options:

a. cursor - Specifies the mouse cursor to be used when the cursor is within the frame.

b. takefocus - Specifies whether the user should be able to move the focus to this widget by using the tabulation key (Tab).

c. width, height - Specifies the size of the widget.

6. Label - The Label widget is used to display text. It can only display text in a single font at a time. The text can span more than one line. In addition, one character in the text can be underlined, usually indicating a keyboard shortcut. The Label widget does not provide any methods except the standard Widget methods. The Label widget provides the following options:

a. anchor - Specifies how the text should be placed in a widget. Use one of N, NE, E, SE, S, SW, W, NW, W, NW,CENTER.

b. bitmap - Specifies the bitmap to be displayed by the widget. If the image option is given, this option is ignored.

c. image - Specifies the image to be displayed by the widget. If specified, this takes precedence over the text and bitmap options.

d. justify - Defines how to align multiple lines of text relative to each others. Use LEFT, RIGHT, or CENTER. Differs from anchor in that justify specifies how to align multiple lines of text relative to each other.

e. text - Specifies the text to be displayed by the widget.

f. textvariable - Specifies the name of a variable that contains the text to be displayed by the widget. If the contents of the variable is modified, the widget will be updated accordingly.

7. Listbox - The Listbox widget displays a list of strings. Each string is displayed on a separate line. It allows to insert, modify or delete strings from the list. The listbox can only contain text items, and all items must have the same font and colour. Depending on the widget configuration, the user can choose one or more alternatives from the list. The Listbox widget provides the following options:

a. selectmode - Specifies the selection mode. One of SINGLE,BROWSE, MULTIPLE, or EXTENDED. Default is BROWSE. Use MULTIPLE to get checklist behavior, EXTENDED if the user usually selects one item, but sometimes would like to select one or more ranges of items.

b. xscrollcommand, yscrollcommand - Used to connect a listbox to a scrollbar. These options should be set to the set methods of the corresponding scrollbars.

The Listbox widget defines the following methods:

a. delete(index),delete(first, last) - Deletes one or more items. Use delete(0, END) to delete all items in the list.

b. get(index) - Gets one or more items from the list. This function returns the string corresponding to the given index (or the strings in the given index range). Use get(0, END) to get a list of all items in the list. Use ACTIVE to get the selected (active) item(s).

c. insert(index, items) - Inserts one or more items at given index (index 0 is before the first item). Use END to append items to the list. Use ACTIVE to insert items before the selected (active) item.

d. size( ) - Returns the number of items in the list.

8 . Menu - The Menu widget is used to implement toplevel, pulldown, and popup menus. The Menu widget provides the following options:

a. postcommand - If specified, this callback is called whenever Tkinter is about to display this menu. If you have dynamic menus, use this callback to update their contents.

b. tearoff - If set, menu entry 0 will be a “tearoff entry”, which is usually a dashed separator line. If the user selects this entry, Tkinter creates a small Toplevel with a copy of this menu.

c. tearoffcommand - If specified, this callback is called when this menu is teared off.

d. title - Specifies the title of menu.

The Menu widget defines the following methods:

a. add(type, options. . . ) - Appends an entry of the given type to the menu. The type argument can be one of “command”, “cascade” (submenu), “checkbutton”, “radiobutton”, or “separator”.

b. insert(index, type, options. . . ) - Same as add and friends, but inserts the new item at the given index.

c. entryconfig(index, options. . . ) - Reconfigures the given menu entry. Only the given options are changed.

d. delete(index) - Deletes one or more menu entries.

9. Message - The Message widget is used to display multiple lines of text. It is very similar to a plain
label, but can adjust its width to maintain a given aspect ratio. The Label widget does not provide any methods except the standard Widget methods. The Message widget provides the following option:

a. aspect - Specifies a non-negative integer describing the aspect ratio of the widget. This integer is taken to be the value of 100 * width / height. Default is 150, i.e. width:height = 1.5:1.

10. OptionMenu - OptionMenu inherits from Menubutton. It is used to display a drop-down list of options. It only defines a constructor of the form:

OptionMenu(master, variable, value, *values)

where master is the master widget of this OptionMenu, variable is a Tkinter Variable value and *values are the values displayed by the Option- Menu. The documentation states that value will be the default variable, but it is not the case. The only point in having a separate value argument is to ensure that at least one value is to be displayed. To set the default value (or any value at any point of the execution), use variable.set(value).

11. Radiobutton - The Radiobutton widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a callback with each button to be executed when the button is pressed. Each group of Radiobutton widgets should be associated with a single variable. Each button then represents a single value for that variable. The Radiobutton widget provides the following options:

a. indicatoron - Specifies whether the indicator should be drawn or not. If false, the Radiobutton behaves like a toggle Button.

b. selectcolor - Specifies a background color to use when the widget is selected. If “indicatoron” is true, then the color applies to the indicator, otherwise it applies to the background of the widget.

c. value - Specifies the value to store in the variable when this button is selected 

d. variable - Specifies a Tkinter Variable that holds the value for the currently selected Radiobutton

The Radiobutton widget defines the following methods:

a. select() - Selects the Radiobutton and stores its value in its Tkinter variable.

b. deselect() - Deselects the Radiobutton. The value of its associated variable cannot be used (variable.get() will throw an exception).

c. invoke() - Simulates a mouse click on the Radiobutton. Same as select() but also executes the callback, if there is one.

12. Scale - The Scale widget is used to display a slider which allows the user to select a value
within a specified range. The Scale widget provides the following options:

a. digits - Specifies the number of significant digits used when converting a value to a string. If negative, Tkinter ensures that every possible slider position will be converted to a different string while using the minimum number of digits.

b. from , to - Specifies the range of values for the Scale label Specifies a string to be displayed by the Scale.

c. length - Specifies the width or height of the Scale, in screen pixels, depending on its orientation.
orient Defines the orientation of the scale. One of HORIZONTAL or VERTICAL.

d. resolution - If greater than zero, then all Scale values will be rounded to multiples of this value. If less than zero, no rouding occurs. Default is 1 (scale takes integer values only).

e. showvalue - Specifies whether the scale should display its current value. Default is TRUE.

f. sliderlength - Specifies the length of the slider, in screen units. Default is 30.

g. sliderrelier - Specifies the relief used to draw the slider.

h. tickinterval - Specifies the spacing between tick marks displayed by the Scale. If it is 0, no tick marks are displayed.

i. troughcolor - Specifies the color used to fill the trough area.

j. variable - Specifies a Tkinter variable to hold the value of the scale.

The Scale widget defines the following methods:

a. coords(value=None) - Returns the coordinates of a point along the center of the trough that corresponds to value. The current value of the scale is used if value is not specified.

get() - Gets the current scale value. Tkinter returns an integer if possible, otherwise a floating point value is returned.

identity(x, y) - Returns a string describing which part of the Scale is situated at the location (x, y). TROUGH1 indicates a position above or on the left of the slider, TROUGH2 a position down or right of the slider, SLIDER a position on the SLIDER, and an empty string a position outside the Scale.

set() - Sets the scale value.

13. Scrollbar - The Scrollbar widget is a typical scrollbar, with arrows at both ends and a slider portion in the middle. Unlike typical scrollbars, its color can be modified.

The Scrollbar widget provides the following options:

a. activebackground - The color of the slider and arrowheads when the mouse is over them.

b. bg - The color of the slider and arrowheads when the mouse is not over them.

c. bd - The width of the 3-d borders around the entire perimeter of the trough, and also the width of the 3-d effects on the arrowheads and slider. Default is no border around the trough, and a 2-pixel border around the arrowheads and slider.

d. command - A procedure to be called whenever the scrollbar is moved.

e. cursor - The cursor that appears when the mouse is over the scrollbar.

f. elementborderwidth - The width of the borders around the arrowheads and slider. The default is elementborderwidth=-1, which means to use the value of the borderwidth option.

g. highlightbackground - The color of the focus highlight when the scrollbar does not have focus.

h. highlightcolor - The color of the focus highlight when the scrollbar has the focus.

i. highlightthickness - The thickness of the focus highlight. Default is 1. Set to 0 to suppress display of the focus highlight.

j. jump - This option controls what happens when a user drags the slider. Normally (jump=0), every small drag of the slider causes the command callback to be called. If you set this option to 1, the callback isn't called until the user releases the mouse button.

k. orient - Set orient=HORIZONTAL for a horizontal scrollbar, orient=VERTICAL for a vertical one.

l. repeatdelay - This option controls how long button 1 has to be held down in the trough before the slider starts moving in that direction repeatedly. Default is repeatdelay=300, and the units are milliseconds.

m. repeatinterval - repeats interval

n. takefocus - Normally, you can tab the focus through a scrollbar widget. Set takefocus=0 if you don't want this behavior.

o. troughcolor - The color of the trough.

q. width - Width of the scrollbar (its y dimension if horizontal, and its x dimension if vertical). Default is 16.

Scrollbar objects have these methods:

a.  get() - Returns two numbers (a, b) describing the current position of the slider. The a value gives the position of the left or top edge of the slider, for horizontal and vertical scrollbars respectively; the b value gives the position of the right or bottom edge.

b. set ( first, last ) - To connect a scrollbar to another widget w, set w's xscrollcommand or yscrollcommand to the scrollbar's set() method. The arguments have the same meaning as the values returned by the get() method.

14. Text - Text widgets provide advanced capabilities that allow you to edit a multiline text and format the way it has to be displayed, such as changing its color and font.

We can also use elegant structures like tabs and marks to locate specific sections of the text, and apply changes to those areas. Moreover, you can embed windows and images in the text because this widget was designed to handle both plain and formatted text.


The Text widget provides the following options:

1. bg - The default background color of the text widget.

2. bd - The width of the border around the text widget. Default is 2 pixels.

3. cursor - The cursor that will appear when the mouse is over the text widget.

4. exportselection - Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection=0 if you don't want that behavior.

5. font - The default font for text inserted into the widget.

6. fg - The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.

7. height - The height of the widget in lines (not pixels!), measured according to the current font size.

8. highlightbackground - The color of the focus highlight when the text widget does not have focus.

9. highlightcolor - The color of the focus highlight when the text widget has the focus.

10. highlightthickness - The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight.

11. insertbackground - The color of the insertion cursor. Default is black.

12. insertborderwidth - Size of the 3-D border around the insertion cursor. Default is 0.

13. insertofftime - The number of milliseconds the insertion cursor is off during its blink cycle. Set this option to zero to suppress blinking. Default is 300.

14. insertontime - The number of milliseconds the insertion cursor is on during its blink cycle. Default is 600.

15. insertwidth - Width of the insertion cursor (its height is determined by the tallest item in its line). Default is 2 pixels.

16. padx - The size of the internal padding added to the left and right of the text area. Default is one pixel.

17. pady - The size of the internal padding added above and below the text area. Default is one pixel.

18. relief - The 3-D appearance of the text widget. Default is relief=SUNKEN.

19. selectbackground - The background color to use displaying selected text.

20. selectborderwidth - The width of the border to use around selected text.

21. spacing1 - This option specifies how much extra vertical space is put above each line of text. If a line wraps, this space is added only before the first line it occupies on the display. Default is 0.

22. spacing2 - This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0.

23. spacing3 - This option specifies how much extra vertical space is added below each line of text. If a line wraps, this space is added only after the last line it occupies on the display. Default is 0.

24. state - Normally, text widgets respond to keyboard and mouse events; set state=NORMAL to get this behavior. If you set state=DISABLED, the text widget will not respond, and you won't be able to modify its contents programmatically either.

25. tabs - This option controls how tab characters position text.

26. width - The width of the widget in characters (not pixels!), measured according to the current font size.

27. wrap - This option controls the display of lines that are too wide. Set wrap=WORD and it will break the line after the last word that will fit. With the default behavior, wrap=CHAR, any line that gets too long will be broken at any character.

28. xscrollcommand - To make the text widget horizontally scrollable, set this option to the set() method of the horizontal scrollbar.

29. yscrollcommand - To make the text widget vertically scrollable, set this option to the set() method of the vertical scrollbar.

The Scrollbar widget defines the following methods:

a. delete(startindex [,endindex]) - This method deletes a specific character or a range of text.

b. get(startindex [,endindex]) - This method returns a specific character or a range of text.

c. index(index) - Returns the absolute value of an index based on the given index.

d. insert(index [,string]...) - This method inserts strings at the specified index location.

e. see(index) - This method returns true if the text located at the index position is visible.

Text widgets support three distinct helper structures: Marks, Tags, and Indexes −

Marks are used to bookmark positions between two characters within a given text. Tags are used to associate names to regions of text which makes easy the task of modifying the display settings of specific text areas. Tags are also used to bind event callbacks to specific ranges of text.

15. Canvas - The canvas widget provides the basic graphics facilities for Tkinter, and so more advanced functions. Drawing on the canvas is done by creating various items on it. It is important to note at this stage that items are not widgets, even though they are similar in many ways. Each item on a canvas is enclosed by a bounding box, which is defined using 2 points: the top-left corner and the bottom-right corner of the box. Tkinter uses two coordinate systems simultaneously: the canvas coordinate system and the window coordinate system. Both systems express positions relative to the top-left corner, with X-coordinates increasing to the right and Y-coordinates increasing downwards. However, the origin for the two systems is different. The window system expresses the coordinates by placing the origin at the top-left corner of the visible portion of the canvas, while the canvas system places its origin at the top-corner of the canvas widget, even it is not visible. The difference is important when handling mouse events bound to the canvas since the event object receives its coordinates in the window system.

The canvas widget provides the necessary methods to convert coordinates to the canvas system, through calls to the canvasx( ) and canvasy( ) methods. The Tkinter canvas supports the following standard items (more can also be added):

1. Arc: arc, chord, pieslice
2. Bitmap: builtin or read from an XBM file
3. Image: a BitmapImage or PhotoImage instance
4. Line
5. Oval: circle or ellipse
6. Polygon
7. Resctangle
8. Text
9. Window: used to place other widgets on the canvas (makes the canvas widget act like a geometry manager)

Apart from their bounding box, all canvas items can be referenced using their unique item ID, which is assigned at the time they are created, and is returned by any of the item constructors. Tkinter also provides a usefull way of working with items: the tags. A number of strings, called tags, can be associated with a canvas item, and more than one item can have the same tag. Items can then be referenced using those tags. Canvas items can also be bound to events, using the tag bind( ) method. The Canvas widget provides the following options:

a. closeenough - Specifies a float defining how close to an item the mouse cursor has to be before it is considered to be over it (a higher value means that the item will selected more readily). Default is 1.0.

b. confine - If TRUE (default), it is not allowed to set the canvas view outside of the region defined by “scrollregion”.

c. scrollregion - Defines the region that is considered to be the boundary of all items in the canvas. It is used for scrolling purposes, in order to limit the scroll actions to a definite area.

d. xscrollcommand, yscrollcommand - Specifies the function used to interact with a scrollbar.

e. xscrollincrement, yscrollincrement - Specifies the increment for horizontal and vertical scrolling, respectively.

The Canvas widget defines the following methods:

  1. create arc(bbox, options) - Creates an arc canvas item and returns its item ID.
  2. create bitmap(position, options) - Creates a bitmap canvas item and returns its item ID.
  3. create image(position, options) - Creates an image canvas item and returns its item ID.
  4. create line(coords, options) - Creates a line canvas item and returns its item ID.
  5. create oval(bbox, options) - Creates an oval canvas item and returns its item ID.
  6. create polygon(coords, options) - Creates a polygon canvas item and returns its item ID.
  7. create rectangle(coords, options)- Creates a rectangle canvas item and returns its item ID.
  8. create text(position, options) - Creates a text canvas item and returns its item ID.
  9. create window(position, options) - Places a Tkinter widget in a canvas window item and returns its item ID.
  10. delete(items) - Deletes all matching items, if any.
  11. itemcget(item, option) - Returns the current value for an option from a canvas item.
  12. itemconfig(item, options), itemconfigure(item, options) - Modifies one or more options for all matching items.
  13. coords(item) - Returns a tuple containing the coordinates for the item.
  14. coords(items, x0, y0, x1, y1, . . . , xn, yn) - Changes the coordinates for all matching items.
  15. bbox(items), bbox( ) - Returns the bounding box for the given items. If the specifier is omitted, the bounding box for all items are returned.
  16. canvasx(screenx), canvasy(screeny) - Converts a window coordinate to a canvas coordinate.
  17. tag bind(item, sequence, callback), tag bind(item, sequence, callback, "+") - Adds an event binding to all matching items. Using the “+” option, it adds the binding to the previous ones, otherwise all previous bindings are replaced.
  18. tag unbind(item, sequence) - Removes the binding, if any, for the given event sequence on all the matching items.
  19. type(item) - Returns the type of the given item as a string (one of “arc”, “bitmap”, “image”, “line”, “oval”, “polygon”, “rectangle”, “text”, “window”).
  20. lift(item),tkraise(item)/ lower(item) - Moves the given item to the top / bottom of the canvas stack. If multiple items match, they are all moved while preserving their relative order.
  21. move(item, dx, dy) - Moves all matching items dx canvas units to the right, and dy canvas units downwards. Negative coordinates specify a displacement in the other direction.
  22. scale(item, xscale, yscale, xoffset, yoffset) Scales matching items according to the given scale factors. The coordinates for each item are first moved by -offset, then multiplied with the scale factor, and then moved back again.
  23. addtag above(newtag, item) - Adds newtag to the item just above the given item in the stacking order.
  24. addtag all(newtag) - Adds newtag to all items on the canvas. This is a shortcut for addtag withtag(newtag, ALL).
  25. addtag below(newtag, item) - Adds newtag to the item just below the given item, in the stacking order.
  26. addtag closest(newtag, x, y) - Adds newtag to the item closest to the given coordinate.
  27. addtag enclosed(newtag, x1, y1, x2, y2) - Adds newtag to all items completely enclosed by the given rectangle.
  28. addtag overlapping(newtag, x1, y1, x2, y2) - Adds newtag to all items enclosed by or touching the given rectangle.
  29. addtag withtag(newtag, tag) - Adds newtag to all items having the given tag.
  30. dtag(item, tag) - Removes the given tag from all matching items. If the tag is omitted, all tags are removed from the matching items. It is not an error to give a specifier that doesn’t match any items.
  31. gettags(item) - Returns all tags associated with the item, in a tuple.
  32. find above(tag, item) - Finds the item just above the given item in the stacking order.
  33. find all(tag) - Finds all items on the canvas. This is a shortcut for find withtag(tag, ALL).
  34. find below(tag, item) - Finds the item just below the given item, in the stacking order.
  35. find closest(tag, x, y) - Finds the item closest to the given coordinate.
  36. find enclosed(tag, x1, y1, x2, y2) - Finds all items completely enclosed by the given rectangle.
  37. find overlapping(tag, x1, y1, x2, y2) - Finds all items enclosed by or touching the given rectangle.
  38. find withtag(tag, tag) - Finds all items having the given tag.
  39. postscript(options) - Generates a postscript representation of the canvas items. Images and widgets are not included in the output.
Just like widgets, canvas items also have a number of options. All items can, for example, have their fill color and their border color changed, or set to transparent.

Here I am ending today's discussion. Till we meet next keep practicing and learning Python as Python is easy to learn!
Share:

0 comments:

Post a Comment