This is probably the most complete collection of tkinter control properties

坏嘻嘻
Release: 2018-09-17 09:15:29
Original
13937 people have browsed it

This article brings you a complete list of tkinter control properties, which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1.Button button. Similar to labels, but provides additional functions, such as mouse over, press, release and keyboard operations/events
2. Canvas canvas. Provides drawing functions (line, ellipse, polygon, rectangle); can contain graphics or bitmaps
3.Checkbutton selection button. A set of boxes, any one of which can be selected (similar to checkbox in HTML)
4.Entry text box. Single-line text field, used to collect keyboard input (similar to text in HTML)
5. Frame. Pure container containing other components
6.Label label. Used to display text or pictures
7.Listbox list box. A list of options from which the user can choose
8.Menu menu. After clicking the menu button, a list of options pops up, from which the user can choose
9.Menubutton menu button. Components used to contain menus (drop-down, cascading, etc.)
10. Message message box. Similar to a label, but can display multiple lines of text
11.Radiobutton radio button. A set of buttons, only one of which can be "pressed" (similar to radio in HTML)
12.Scale progress bar. The linear "slider" component can set the start value and end value, and will display the precise value of the current position
13.Scrollbar scroll bar. Provide scrolling function for the components it supports (text field, canvas, list box, text box)
14.Text text field. Multi-line text area, which can be used to collect (or display) text entered by the user (similar to textarea in HTML)
15.Toplevel. Similar to a frame, but provides an independent window container.
Tkinter supports 15 core widgets. The list of these 15 core widget classes is as follows:
Widgets and descriptions:
Button:
A simple button used to execute a command or other operation.
Canvas:
Organization graphics. This widget can be used to draw charts and graphs, create graphic editors, and implement custom widgets.
Checkbutton:
Represents a variable, which has two different values. Clicking this button will toggle between these two values.
Entry:
Text input field.
Frame:
A container widget. Frames can have borders and backgrounds and are used to organize other widgets when creating an application or dialog layout.
Label:
Display a text or image.
Listbox:
Displays a list of alternatives. The listbox can be configured to behave like a radiobutton or checklist.
Menu:
Menu bar. Used to implement drop-down and pop-up menus.
Menubutton:
Menu button. Used to implement drop-down menus.
Message:
Display a text. Similar to the label widget, but automatically adjusts the text to a given width or ratio.
Radiobutton:
Represents a variable, which can have one of multiple values. Clicking it will set the value for this variable and clear other radiobuttons related to this same variable.
Scale:
Allows you to set a numeric value via a slider.
Scrollbar:
A standard scroll bar for use with canvas, entry, listbox, and text widgets.
Text:
Formatted text display. Allows you to display and edit text with different styles and properties. Both inline images and windows are supported.
Toplevel:
A container widget, displayed as a separate, topmost window.
Note that widget classes are not hierarchical in Tkinter; all widget classes are brothers in the tree.
All these widgets provide Misc and geometry management methods, configuration management methods and other methods defined by the widget itself. In addition, the Toplevel class also provides window management interface. This means that a typical widget class provides about 150 methods.
Button widget
The Button widget is a standard Tkinter widget used to implement various buttons. Buttons can contain text or images, and you can associate buttons with a Python function or method. When this button is pressed, Tkinter automatically calls the associated function or method
The button can only display one font, but the text can span lines. Additionally, a letter in this text can be underlined, for example to indicate a shortcut key. By default, the Tab key moves focus to a button widget.
1. So when should you use button components?
In short, the button component is used to let the user say "Perform this task for me now". Usually we use text or images displayed on the button to prompt. Buttons are typically used in toolbars or application windows, and are used to accept or ignore data entered in dialog boxes.
Regarding the coordination of buttons and input data, you can refer to the Checkbutton and Radiobutton components.
2. Style
Ordinary buttons are easy to create, just specify the content 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. It does nothing when you press the button. You may want to implement this kind of button when developing an application, for example so as not to disturb your beta testers:
b = Button(master, text="Help", state=DISABLED)
if You don't specify a size, the button will be just the right size to hold its content. You can use the padx and pady options to increase the spacing between the content and the button border. You can also set the button's size explicitly using the height and width options. If you are displaying text in a button, these options will define the size of the button in the units of the text. If you display an image instead, the button's dimensions will be in pixels (or other screen units). You can actually even define the size of the text button in pixel units, but this can have unexpected results. The following is an example code for specifying the 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 can be used). You can use the multiline or wraplength options to make the button resize its text. When adjusting text, use anchor, justify, or 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)
In order to make a normal button look recessed, for example, you want to achieve For some type of toolbox, 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 more A good solution is to use a Checkbutton or Radiobutton with the value of the indicatoron option set to false:
b = Checkbutton(master, image=bold, variable=var, indicatoron=0)
3. Method
Button Widgets support the standard Tkinter widget interface, plus the following methods:
flash(): Frequently redraw the button to switch between active and normal styles.
invoke(): Call associated with the button command.
The following methods are related to you implementing your own button binding:
tkButtonDown(), tkButtonEnter(), tkButtonInvoke(), tkButtonLeave(), tkButtonUp()
These methods can be used in customization In event binding, all these methods receive 0 or more formal parameters.
4. 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 N, NE, E, SE, S, SW, W, NW, or CENTER One of these values. The default value is CENTER.
background (bg), foreground (fg)
Type: Color;
Description: The color of the button. The default value is platform-specific.
bitmap
Type: Bitmap;
Description: The bitmap displayed in the widget. 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 appended bitmaps are only valid on Macintosh: document, stationery, edition, application, accessory, folder, pfolder, trash, floppy, ramdisk, cdrom, preferences, querydoc, stop, note, and caution.
You also Bitmaps can be loaded from an XBM file. Just add a prefix @ before the XBM file name, such as "@sample.xbm".
borderwidth (bd)
Type: Integer;
Description: The width of the button border. Default values ​​are platform-specific. But usually 1 or 2 pixels
command
Type: callback;
Description: A function or method called when the button is pressed. The callback can be a function, method or other callable Python object
cursor
Type: Cursor;
Description: The cursor displayed when the mouse moves to the button.
default
Type: Constant;
Description: If set, the button is the default button. Note that this syntax has changed in Tk 8.0b2.
disabledforeground
Type: Color;
Description: The color when the button is disabled.
font
Type: font;
Description: The font used by the button. Buttons can only contain text in one font.
Highlightbackground, highlightcolor
Type: Color;
Description: Controls the color of the highlight 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 highlight border where the focus is. The default value is usually 1 or 2 pixels.
image
Type: Image;
Description: The image displayed in the component. If specified, the text and bitmap options are ignored.
justify
Type: Constant;
Description: Define how to align multiple lines of text. Possible values ​​are: LEFT, RIGHT, or CENTER.
padx, pady
Type: distance;
Description: Specify the distance between the text or image and the button border.
relief
Type: constant;
Description: Decoration of the border. Usually buttons are recessed when pressed and raised otherwise. Other 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: Flag;
Description: Indicates that the user can move the focus to this button with the Tab key. The default value is an empty string, which means that if the button has a key binding, it can gain focus through the bound key.
text
Type: String;
Description: The text displayed in the button. Text can be multiple lines. If the bitmaps or image options are used, the text option is ignored.
textvariable
Type: variable;
Description: Tk variable related to the button (usually a string variable). If the value of this variable changes, the text on the button is updated accordingly.
underline
Type: Integer;
Description: Which character is underlined in the text label. The default value is -1, which means no characters are underlined.
width, height
Type: distance;
Description: The size of the button. If the button displays text, the dimensions use the text's units. If the button displays an image, the size is in pixels (or screen units). If the size is not specified, it will be calculated based on the button's content.
wraplength
Type: distance;
Description: Determines when the text of a button is adjusted to multiple lines. It is measured in units of the screen. Not adjusted by default.
Mixins
The Tkinter module provides classes corresponding to various widget types in Tk and a certain number of mixins and other helper classes (a mixin is a class designed to interact with other classes using polymorphic inheritance combined). When you use Tkinter, you will not have direct access to mixin classes.
1. Implement mixins
Through the root window and widget classes, the Misc class is used as a mixin. It provides a large number of Tk and window related services that are available to all Tkinter core widget users. This is done through delegates; the widget simply requests the appropriate internal object directly.
The Wm class is used as a mixin through the root window and top-level widget classes. It provides window management services through delegation.
Use delegates to simplify your application code like this: Once you have a widget, you can access all parts of Tkinter using the methods of this widget instance.
2. Geometry and mixins
Grid, Pack, and Place classes are used as mixins through widget classes. They also provide support for accessing different geometry management through delegation.
The following is a list and description of Geometry Mixins:
Manager and description:
Grid: The grid geometry manager allows you to create a table-like layout by organizing widgets in a two-dimensional grid.
Pack: The pack geometry manager creates a layout by packing widgets into a parent widget in a frame. To use this geometry manager with a widget, we use the pack method on the widget to integrate it.
Place: The place geometry manager lets you explicitly place a widget at a given location. To use this geometry manager, use the place method.
3. Widget configuration management
The Widget class uses geometry mixins to mix the Misc class, and adds configuration management through the cget and configure methods, or through a local dictionary interface.
Configuration of widgets
To configure the appearance of a widget, it is better to use options rather than method calls. Typical options include text, color, size, command, etc. For processing options, all core widgets implement the same configuration interface:
Configuration interface
widgetclass(master, option=value, ...) => widget
Description:
Create this window An instance of the widget that is a child of the given master and uses the given options. All options have default values, so in simple cases you only need to specify the master. You can not specify a master if you want; Tkinter will then use the most recently created root window as the 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. Option names and return values ​​are both strings. To get the name option, use str(widget) instead.
configure(option=value, ...), config(option=value, ...)
Description:
Set one or more options (given as keyword arguments).
Note that the names of some options are the same as reserved words in Python (class, from, etc.). To use these as keyword arguments, just add an underscore (class_, from_) after the option names. Note that you cannot use this method to set the name option; the name option can only be set when the widget is created.
For convenience, the widget also implements a partial dictionary interface. The __setitem__ method maps configure, and the __getitem__ method maps cget. You can set and query options using the following syntax:
value = widget[option]
widget[option] = value
Note that each assignment results in a call to Tk. If you wish to change multiple options, it is a good idea to call (config or configure) individually to change them.
The following dictionary method also applies to widgets:
keys() => list
Description:
Returns a list of all 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).
Backward Compatibility
Keyword parameters were introduced in Python 1.3. Previously, raw Python dictionaries were used to pass options to the window constructor and configure methods. The original code is similar to the following:
self.button = Button(frame, {"text": "QUIT", "fg": "red", "command": frame.quit})
self.button.pack ({"side": LEFT})
The keyword argument syntax is more elegant and less error-prone. But for compatibility with existing code, Tkinter still supports the old syntax. You should not use the old syntax in new programs, 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 under future versions. A common way 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 arguments (it must include self because we are calling an unconstrained method), and an optional, dictionary providing keyword arguments.
Style Color of Widgets
All Tkinter standard widgets provide a set of styling options, which allow you to modify the appearance of these widgets such as color, font and other visual appearance.
Color
Most widgets allow you to specify the color of the widget and text. This can be done using the background and foreground options. To specify a color, you can use a color name or a red, green, and blue color combination.
1. Color name
Tkinter includes a color database that maps color names to corresponding RGB values. This database includes common names such as Red, Green, Blue, Yellow, and LightBlue, as well as exotic names such as Moccasin, PeachPuff, etc. On X window systems, color names are defined by the X server. You can find a file called xrgb.txt, which contains a list of color names and corresponding RGB values. On Windows and Macintosh systems, color tables are built into Tk.
Under Windows, you can use 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 Macintosh, the following system colors are valid:
SystemButtonFace, SystemButtonFrame, SystemButtonText, SystemHighlight, SystemHighlightText, SystemMenu, SystemMenuActive, SystemMenuActiveText, SystemMenuDisabled, SystemMenuText, SystemWindowBody.
Color names are case-insensitive. Many color nouns and words are valid with or without cases between them. For example, "lightblue", "light blue", and
"Light Blue" are all the same color.
2. RGB format
If you need to explicitly specify the color name, you can use a string in the following format:
#RRGGBB
RR, GG, BB are the red, green and blue values ​​​​respectively hexadecimal representation. The following example demonstrates how to convert a color triplet into a Tk color format:
tk_rgb = "# x x x" % (128, 192, 200)
Tk also supports Use forms such as "#RGB" and "rrrrggggbbbb" to specify values ​​between 16 and 65536 degrees respectively.
You can use the widget's winfo_rgb method to convert a string representing a color (name or RGB format) into a triplet:
rgb = widget.winfo_rgb("red")
red, green, blue = rgb[0]/256, rgb[1]/256, rgb[2]/256
Note that winfo_rgb returns a 16-bit RGB value, ranging from 0 to 65535. To map them to the more general range of 0~255, you have to divide each value by 256 (or shift them 8 bits to the right).

The above is the detailed content of This is probably the most complete collection of tkinter control properties. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template