Python Tkinter each control property in full

Source: Internet
Author: User

1.Button button. Similar tags, but provides additional features such as mouse over, press, release, and keyboard actions/Events

2.Canvas Canvas. Provides drawing functionality (lines, ellipses, polygons, rectangles), which can contain graphics or bitmaps

3.Checkbutton selection button. A set of boxes where you can select any of them (like a checkbox in HTML)

4.Entry text box. Single-line text field for collecting keyboard input (like text in HTML)

5.Frame frame. A pure container containing other components

6.Label label. Use to display text or pictures

7.Listbox list box. A list of options from which the user can select

8.Menu menu. Click the menu button to pop up a list of options from which the user can select

9.Menubutton menu button. Components to include menus (drop-down, cascade, etc.)

10.Message message box. Similar to labels, but can display multiple lines of text

11.Radiobutton radio button. A set of buttons in which only one can be "pressed" (similar to radio in HTML)

12.Scale progress bar. Linear slider component, which sets the starting and ending values, showing the exact value of the current position

13.Scrollbar scroll bar. Provides scrolling functionality for its supported components (text fields, canvases, list boxes, text boxes)

14.Text text field. Multiline text area, which can be used to collect (or display) user-entered text (like textarea in HTML)

15.Toplevel top. A similar framework, but provides a separate window container.


The Tkinter supports 15 core widgets, the list of 15 core widget classes as follows:

window parts and descriptions:

Button:
A simple button to execute a command or other operation.

Canvas:
Organize graphics. This component can be used to draw charts and graphs, create graphical editors, and implement custom widgets.

Checkbutton:
Represents a variable that has two different values. Clicking on this button will toggle between the two values.

Entry:
The text input field.

Frame:
A container window part. Frames can have borders and backgrounds, and frames are used to organize other widgets when an application or dialog (dialog) layout is created.

Label:
Displays a text or image.

Listbox:
Displays a list of alternative scenarios. A listbox can be configured to get RadioButton or checklist behavior.

Menu:
Menu bar. Used to implement drop-down and pop-up menus.

Menubutton:
menu button. Used to implement a drop-down menu.

Message:
Displays a text. Like a label widget, but can automatically adjust the text to a given width or ratio.

Radiobutton:
Represents a variable, which can have one of several values. Clicking on it sets the value for this variable and clears the other RadioButton associated with the same variable.

Scale :
Allows you to set a numeric value by using the slider.

Scrollbar:
The standard scroll bar for working with canvas, entry, ListBox, and text widgets.

Text:
Formatted text display. Allows you to display and edit text in different styles and properties. Both inline images and windows are supported.

toplevel:
A container widget that is displayed as a separate, topmost window.

Note that the window part class is not graded in Tkinter; all widgets are brothers in the tree.

All of these widgets provide additional methods for misc and Geometry management methods, configuration management methods, and parts defined by themselves. In addition, the TopLevel class also provides a window management interface. This means that a typical window part class provides approximately 150 methods.

Button Window part

The button widget is a standard Tkinter widget for implementing various buttons. Buttons can contain text or images, and you can associate a button with a Python function or method. When this button is pressed, Tkinter automatically calls the associated function or method.

A button can display only one font, but this text can span lines. In addition, one of the letters in this text can be underlined, for example, to indicate a shortcut key. By default, the TAB key is used to move the focus to a button part.

first, then when to use the button parts?

In short, the button widget is used to let the user say "perform this task for me Now", and usually we use the text or image displayed on the button to prompt. Buttons are typically used in toolbars or in application windows, and are used to receive or ignore data entered in a dialog box.

For a match between the button and the input data, refer to the Checkbutton and RadioButton parts.

two, style

Normal buttons are easy to create, specifying only the contents of the button (text, bitmap, image) and a callback function when the button is pressed:
b = button (Master, text= "OK", Command=self.ok)

A button without a callback function is useless and does nothing when you press the button. You may want to implement such a button when developing an application, such as a tester that does not interfere with your beta version:
b = button (Master, text= "Help", state=disabled)

If you do not specify a size, the size of the button will just fit the contents of it. You can use the PADX and Pady options to increase the spacing between the content and the button border. You can also use the height and width options to explicitly set the size of the button. If you display text in a button, these options define the size of the button in units of text. If you display the image on behalf of, then the size of the button will be pixels (or other screen units). You can actually even use pixel units to define the size of a text button, but this can lead to unexpected results. Here is a sample code for the specified size:
f = Frame (Master, height=32, width=32)
F.pack_propagate (0) # don ' t shrink
b = button (f, text= "sure!")
B.pack (Fill=both, expand=1)


The button can display multiple lines of text (but only one font). You can use the multiline or Wraplength option to make the button adjust the text itself. When adjusting the text, use Anchor,justify, or you can add the PADX option to get the format you want. An example is as follows:
B = Button (master, Text=longtext, Anchor=w, Justify=left, padx=2)

To make a normal button look like a recessed one, for example you want to implement some kind of tool box, you can simply change the value of relief from "raised" to "SUNKEN:
b.config (Relief=sunken)

You may also want to change the background. Note: A probably better solution is to use a Checkbutton or RadioButton with the value of its Indicatoron option set to False:
B = Checkbutton (master, Image=bold, Variable=var, indicatoron=0)

third, the method

The button widget supports the standard Tkinter window part interface, plus the following method:

Flash ():Redraw the buttons frequently so that they switch between active and normal styles.

Invoke ():Invokes the command associated with the button.

The following methods are related to the implementation of your own button bindings:

Tkbuttondown (), Tkbuttonenter (), Tkbuttoninvoke (), Tkbuttonleave (), Tkbuttonup ()
These methods can be used in custom event bindings, all of which receive 0 or more formal parameters.

Iv. Options

The button widget supports the following options:

Activebackground, Activeforeground
Type: color;
Description: The color used when the button is activated.

Anchor
Type: constant;
Description: Controls the position of the content on the button. Use one of these values for N, NE, E, SE, S, SW, W, NW, or center. The default value is center.

background (BG), foreground (FG)
Type: color;
Description: The color of the button. The default value is related to a specific platform.

Bitmap
Type: bitmap;
Description: The bitmap that is displayed in the window part. If the image option is specified, this option is ignored. The following bitmaps are valid on all platforms: Error, gray75, gray50, gray25, Gray12, Hourglass, info, questhead, question, and warning.

The attached bitmap is valid only on the Macintosh: Document, Stationery, edition, application, accessory, folder, Pfolder, Trash, Floppy, RAMDisk, C Drom, Preferences, Querydoc, stop, note, and caution.

You can also load bitmaps from a XBM file. You only need to prefix the XBM file name with a @, such as "@sample. XBM".

BorderWidth (BD)
Type: integer;
Description: The width of the button border. The default value is related to a specific platform. But it's usually 1 or 2 pixels.

Command
Type: callback;
Description: A function or method that is called when the button is pressed. The callback can be a function, method, or other callable Python object.

cursor
Type: cursor;
Description: The cursor that is displayed when the mouse moves over the button.

default
Type: constant;
Note: If set, the button is the default button. Note that this syntax has changed in TK 8.0b2.

Disabledforeground
Type: color;
Description: Color When the button is not valid.

Font
Type: font;
Description: The font used by the button. The button can contain only one font of text.

Highlightbackground, HighlightColor
Type: color;
Description: Controls the color of the highlighted border where the focus is. When the widget gets focus, the border is the color specified by HighlightColor. Otherwise the border is the color specified by Highlightbackground. The default value is determined by the system.

highlightthickness
Type: distance;
Description: Controls the width of the highlighted border where the focus is. The default value is usually 1 or 2 pixels.

Image
Type: image;
Description: The image displayed in the part. If specified, the text and bitmap options are ignored.

Justify
Type: constant;
Description: Defines how multiple lines of text are aligned. The values are: left, right, or CENTER.

PADX, Pady
Type: distance;
Description: Specifies the spacing between text or image and button borders.

Relief
Type: constant;
Description: The decoration of the border. Usually the button is depressed when pressed, otherwise convex. Additional possible values are groove, RIDGE, and FLAT.

State
Type: constant;
Description: The state of the button: NORMAL, active, or DISABLED. The default value is normal.

TakeFocus
Type: logo;
Description: Indicates that the user can tab to move the focus to this button. The default value is an empty string, meaning that if the button is bound by a key, it can get focus by the key that is bound.

text
Type: string;
Description: The text that appears in the button. The text can be multiple lines. If the bitmaps or image option is used, the text option is ignored.

textvariable
Type: variable;
Description: The TK variable associated with the button (usually a string variable). If the value of this variable changes, then the text on the button is updated accordingly.

Underline
Type: integer;
Description: In the text label, which word multibyte underline. The default value is-1, meaning no word multibyte underline.

width, height
Type: distance;
Description: The size of the button. If the button displays text, the dimension uses the units of the text. If the button displays an image, the dimensions are in pixels (or units of the screen). If the dimension is not specified, it is calculated based on the contents of the button.

Wraplength
Type: distance;
Description: Determines when the text of a button is resized to multiple lines. It is in units of the screen. The default is not adjusted.

Mixins

The Tkinter module provides classes corresponding to various types of widgets in TK and a number of mixin and other helper classes (Mixin is a class that is designed to use polymorphic inheritance in conjunction with other classes). When you use Tkinter, you will not be accessing the Mixin class directly.

first, the implementation of Mixins

The Misc class is used as a mixin through the root window and widget classes. It provides a large number of TK and windowing related services that are valid for all Tkinter core widget users. These are done through a delegate, and the widget simply requests the appropriate internal object.

The WM class is used as a mixin through the root window and the top-level window part class. It provides a window management service by delegating it.

Use delegates to simplify your application code like this: Once you have a widget, you can access all the parts of Tkinter using the method of the instance of the widget.

ii. Geometry (geometry) and mixins

Grid,pack,place These classes are used as mixins through the window part class. Through delegates, they also provide support for accessing different geometry management.
The following is a list and description of geometry mixins:
Manager and Description:

The Grid:grid Geometry Manager allows you to create a table-like layout by organizing widgets in a two-dimensional grid.
The Pack:pack Geometry Manager creates a layout by wrapping the widgets into a parent part in a single frame. To use this geometry manager for widgets, we use the pack method on this widget to integrate.
The Place:place Geometry Manager lets you explicitly place a widget at a given location. To use this geometry manager, you need to use the place method.

third, the window parts configuration management
The Widget class uses the geometry mixins to mix misc classes and to increase configuration management through the Cget and configure methods, or through a local dictionary interface. 

Configuration of window Parts

To configure the appearance of a widget, you use options better than the method call. Typical options include text, color, size, command, and so on. For the processing option, all the core widgets perform the same configuration interface:

Configuring Interfaces

Widgetclass (Master, option=value, ...) = Widgets
Description
Create an instance of this widget as a child of the given master, and use the given options. All options have default values, so in a simple case you just need to specify this master. If you want to, you can also not specify Master;tkinter this will use the most recently created root window as master. Note that this name option can only be set when the widget is created.

cget (option) = String
Description
Returns the current value of an option. Both the name and the return value of the option are strings. To get the name option, use the str (widget) instead.

Configure (Option=value, ...), config (Option=value, ...)
Description
Sets one or more options (given as a keyword parameter).
Note that some options have the same name as the reserved words in Python (class,from, etc.). To use these as keyword parameters, you only need to add a dash (class_,from_) after these option names. Note You cannot use this method to set the name option; The name option can only be set when the window part is created.

For convenience, the widget also implements a local dictionary interface. The __setitem__ method maps the Configure, and the __getitem__ method maps the Cget. You can use the following syntax to set and query options:
Value = Widget[option]
Widget[option] = value
Note that each assignment results in a call to Tk. If you want to change multiple options, it is a good idea to call (config or configure) separately to change them.

The following dictionary methods also apply to widgets:
keys () = List
Description
Returns a list of all the options that can be set in the widget. The name option is not included in this list (it cannot be queried or modified through the dictionary interface).

backwards compatibility

Keyword parameters are introduced at Python1.3. Previously, the options were passed to the window constructor and the Configure method using the original Python dictionary. The original code looks like this:
Self.button = button (frame, {"text": "QUIT", "FG": "Red", "command": Frame.quit})
Self.button.pack ({"Side": Left})


The keyword parameter syntax is more elegant and less prone to errors. But in order to be compatible with the existing code, Tkinter still supports the old syntax. In the new program you should not use the old syntax, even if it is attractive in some cases. For example, if you create a custom widget that needs to pass configuration options along its parent class, your code might look like this:
def __init__ (self, Master, **kw):
Canvas.__init__ (self, master, kw)
# kw is a dictionary
The above code works well under the current version of Tkinter, but it may not work in a future release. A common approach is to use the Apply function:
def __init__ (self, Master, **kw):
Apply (canvas.__init__, (self, Master), kw)

This apply function uses a function (an unconstrained method), a tuple with parameters (it must include self, because we call an unconstrained method), an optional dictionary that provides the keyword arguments.

the color of the style of the widget

all Tkinter standard widgets provide a set of styling options that allow you to modify the appearance of these widgets, such as colors, fonts, and other visual appearances.

Color

Most widgets allow you to specify the color of widgets and text, which can be used with the background and foreground options. To specify a color, you can use a color name or a combination of red, green, and blue colors.

1, the color name
Tkinter includes a color database that maps the color name to the corresponding RGB value. This database includes the usual names such as red, green, blue, yellow,  and LightBlue, and can also be used outside such as Moccasin,peachpuff and so on. On X window systems, the color name is defined by X server. You can find a file named Xrgb.txt that contains a list of color names and corresponding RGB values. On Windows and Macintosh systems, the color name table is built in TK.

Under Windows, you can use the Windows system colors (users can change these colors through the control Panel):
Systemactiveborder, Systemactivecaption, Systemappworkspace, Systembackground,
Systembuttonface, Systembuttonhighlight, Systembuttonshadow, Systembuttontext,
Systemcaptiontext, Systemdisabledtext, Systemhighlight, Systemhighlighttext,
Systeminactiveborder, Systeminactivecaption, Systeminactivecaptiontext, Systemmenu,
Systemmenutext, Systemscrollbar, Systemwindow, Systemwindowframe, Systemwindowtext.


On the Macintosh, the following system colors are valid:
Systembuttonface, Systembuttonframe, Systembuttontext, Systemhighlight, Systemhighlighttext, SystemMenu, Systemmenuactive, Systemmenuactivetext, systemmenudisabled, Systemmenutext, Systemwindowbody.

The color name is case insensitive. Many color nouns and words have no lattice between them. such as "LightBlue", "Light blue", and
"Light Blue" is the same color.

2. RGB format

If you want to explicitly specify a color name, you can use a string in the following format:
#RRGGBB
RR, GG, BB are hexadecimal representations of red,green and blue values, respectively. The following example shows how to convert a color ternary group to a

A TK color format:
Tk_rgb = "#%02x%02x%02x"% (128, 192, 200)

TK also supports the use of shapes such as "#RGB" and "rrrrggggbbbb" to specify values between 16 and 65536 degrees respectively.

You can use the Winfo_rgb method of the widget to convert a string representing a color (first name or RGB format) to a ternary group:
RGB = Widget.winfo_rgb ("Red")
Red, green, blue = rgb[0]/256, rgb[1]/256, rgb[2]/256
Note Winfo_rgb returns a 16-bit RGB value, ranging between 0~65535. To map them to a more general 0~255 range, you must divide each value by 256 (or move them 8 bits to the right). 

Python Tkinter each control property in full

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.