Nota

¡Ayúdanos a traducir la documentación oficial de Python al Español! Puedes encontrar más información en Como contribuir. Ayuda a acercar Python a más personas de habla hispana.

tkinter.tix — Ampliación de widgets para Tk

Código fuente: Lib/tkinter/tix.py

Obsoleto desde la versión 3.6: Esta ampliación de Tk no está mantenida y no debe ser usada en nuevo código. Use tkinter.ttk en su lugar.


El módulo tkinter.tix (Tk Interface Extension en inglés) proporciona un conjunto abundante de widgets adicionales. Aunque la biblioteca estándar Tk tiene muchos widgets útiles, están lejos de ser completos. La biblioteca tkinter.tix proporciona la mayoría de los widgets comúnmente necesarios que no están en el estándar Tk: HList, ComboBox, Control (alias SpinBox) y una selección de widgets desplazables. tkinter.tix también incluye muchos más widgets que son generalmente útiles en un rango amplio de aplicaciones: NoteBook, FileEntry, PanedWindow, etc; hay más de 40 de ellos.

Con todos estos nuevos widgets, puedes introducir nuevas técnicas de interacción en aplicaciones, creando interfaces de usuario más útiles y más intuitivas. Puedes diseñar tu aplicación al escoger los widgets más apropiados que combinen con las necesidades especiales de tu aplicación y usuarios.

Ver también

Tix Homepage

La página de inicio de Tix. Incluye enlaces a documentación adicional y descargas.

Tix Man Pages

Versión en línea de las páginas del manual y material de referencia.

Tix Programming Guide

Versión en línea del material de referencia del programador.

Tix Development Applications

Aplicaciones de Tix para el desarrollo de programas de Tix y Tkinter. Las aplicaciones de Tide (por Tix Integrated Development Environment en sus siglas de inglés) trabajan bajo Tk o Tkinter, e incluyen TixInspect, un inspector para modificar y depurar aplicaciones Tix/Tk/Tkinter remotamente.

Usando Tix

class tkinter.tix.Tk(screenName=None, baseName=None, className='Tix')

Un widget de alto nivel de Tix que representa generalmente la ventana principal de una aplicación. Tiene un intérprete Tcl asociado.

Las clases en el módulo tkinter.tix heredan de la clases en tkinter. El primero importa el segundo, por lo que para usar tkinter.tix con Tkinter, todo lo que necesitas hacer es importar un módulo. En general, puedes importar tkinter.tix, y reemplazar las invocaciones de alto nivel a tkinter.Tk con tix.Tk:

from tkinter import tix
from tkinter.constants import *
root = tix.Tk()

Para usar tkinter.tix, debes tener los widgets Tix instalados, usualmente junto a tu instalación de los widgets Tk. Para probar tu instalación, intenta lo siguiente:

from tkinter import tix
root = tix.Tk()
root.tk.eval('package require Tix')

Widgets de Tix

Tix introduces over 40 widget classes to the tkinter repertoire.

Widgets Básicos

class tkinter.tix.Balloon

A Balloon that pops up over a widget to provide help. When the user moves the cursor inside a widget to which a Balloon widget has been bound, a small pop-up window with a descriptive message will be shown on the screen.

class tkinter.tix.ButtonBox

The ButtonBox widget creates a box of buttons, such as is commonly used for Ok Cancel.

class tkinter.tix.ComboBox

The ComboBox widget is similar to the combo box control in MS Windows. The user can select a choice by either typing in the entry subwidget or selecting from the listbox subwidget.

class tkinter.tix.Control

The Control widget is also known as the SpinBox widget. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits.

class tkinter.tix.LabelEntry

The LabelEntry widget packages an entry widget and a label into one mega widget. It can be used to simplify the creation of «entry-form» type of interface.

class tkinter.tix.LabelFrame

The LabelFrame widget packages a frame widget and a label into one mega widget. To create widgets inside a LabelFrame widget, one creates the new widgets relative to the frame subwidget and manage them inside the frame subwidget.

class tkinter.tix.Meter

The Meter widget can be used to show the progress of a background job which may take a long time to execute.

class tkinter.tix.OptionMenu

The OptionMenu creates a menu button of options.

class tkinter.tix.PopupMenu

The PopupMenu widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate.

class tkinter.tix.Select

The Select widget is a container of button subwidgets. It can be used to provide radio-box or check-box style of selection options for the user.

class tkinter.tix.StdButtonBox

The StdButtonBox widget is a group of standard buttons for Motif-like dialog boxes.

Selectores de Archivos

class tkinter.tix.DirList

The DirList widget displays a list view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory.

class tkinter.tix.DirTree

The DirTree widget displays a tree view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory.

class tkinter.tix.DirSelectDialog

The DirSelectDialog widget presents the directories in the file system in a dialog window. The user can use this dialog window to navigate through the file system to select the desired directory.

class tkinter.tix.DirSelectBox

El widget DirSelectBox es similar al cuadro de selección de directorio estándar de Motif(TM). Es generalmente usado para que el usuario escoja un directorio. DirSelectBox guarda los directorios seleccionados recientemente en un widget de cuadro combinado para que puedan ser seleccionados rápidamente de nuevo.

class tkinter.tix.ExFileSelectBox

The ExFileSelectBox widget is usually embedded in a tixExFileSelectDialog widget. It provides a convenient method for the user to select files. The style of the ExFileSelectBox widget is very similar to the standard file dialog on MS Windows 3.1.

class tkinter.tix.FileSelectBox

The FileSelectBox is similar to the standard Motif(TM) file-selection box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again.

class tkinter.tix.FileEntry

The FileEntry widget can be used to input a filename. The user can type in the filename manually. Alternatively, the user can press the button widget that sits next to the entry, which will bring up a file selection dialog.

ListBox jerárquico

class tkinter.tix.HList

The HList widget can be used to display any data that have a hierarchical structure, for example, file system directory trees. The list entries are indented and connected by branch lines according to their places in the hierarchy.

class tkinter.tix.CheckList

The CheckList widget displays a list of items to be selected by the user. CheckList acts similarly to the Tk checkbutton or radiobutton widgets, except it is capable of handling many more items than checkbuttons or radiobuttons.

class tkinter.tix.Tree

The Tree widget can be used to display hierarchical data in a tree form. The user can adjust the view of the tree by opening or closing parts of the tree.

ListBox Tabular

class tkinter.tix.TList

The TList widget can be used to display data in a tabular format. The list entries of a TList widget are similar to the entries in the Tk listbox widget. The main differences are (1) the TList widget can display the list entries in a two dimensional format and (2) you can use graphical images as well as multiple colors and fonts for the list entries.

Gestores de Widgets

class tkinter.tix.PanedWindow

The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally. The user changes the sizes of the panes by dragging the resize handle between two panes.

class tkinter.tix.ListNoteBook

The ListNoteBook widget is very similar to the TixNoteBook widget: it can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages (windows). At one time only one of these pages can be shown. The user can navigate through these pages by choosing the name of the desired page in the hlist subwidget.

class tkinter.tix.NoteBook

The NoteBook widget can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages. At one time only one of these pages can be shown. The user can navigate through these pages by choosing the visual «tabs» at the top of the NoteBook widget.

Tipos de Imágenes

El módulo tkinter.tix añade:

  • pixmap capabilities to all tkinter.tix and tkinter widgets to create color images from XPM files.

  • Compound image types can be used to create images that consists of multiple horizontal lines; each line is composed of a series of items (texts, bitmaps, images or spaces) arranged from left to right. For example, a compound image can be used to display a bitmap and a text string simultaneously in a Tk Button widget.

Widgets Varios

class tkinter.tix.InputOnly

The InputOnly widgets are to accept inputs from the user, which can be done with the bind command (Unix only).

Gestor de Geometría de Formulario

Además, tkinter.tix mejora a tkinter al proporcionar:

class tkinter.tix.Form

The Form geometry manager based on attachment rules for all Tk widgets.

Comandos Tix

class tkinter.tix.tixCommand

The tix commands provide access to miscellaneous elements of Tix’s internal state and the Tix application context. Most of the information manipulated by these methods pertains to the application as a whole, or to a screen or display, rather than to a particular window.

Para ver las configuraciones actuales, el uso común es:

from tkinter import tix
root = tix.Tk()
print(root.tix_configure())
tixCommand.tix_configure(cnf=None, **kw)

Consulta o modifica las opciones de configuración del contexto de la aplicación Tix. Si no se especifica ninguna opción, retorna un diccionario con todas las opciones disponibles. Si la opción es especificada sin ningún valor, entonces el método retorna una lista describiendo la opción nombrada (esta lista será idéntica a la sublista correspondiente de los valores retornados si no se especifica ninguna opción). Si uno o más pares opción-valor son especificados, entonces el método modifica las opciones dadas para tener los valores dados; en este caso el método retorna una cadena de caracteres vacía. La opción puede ser cualquiera de las opciones de configuración.

tixCommand.tix_cget(option)

Retorna el valor actual de la opción de configuración dada por option. La opción puede ser cualquiera de las opciones configurables.

tixCommand.tix_getbitmap(name)

Localiza un archivo bitmap con el nombre name.xpm o name en uno de los directorios bitmap (véase el método tix_addbitmapdir()). Al usar tix_getbitmap(), puedes evitar codificar directamente los nombres de ruta de los archivos bitmap en tu aplicación. Cuando tiene éxito, retorna el nombre de ruta completo del archivo bitmap, prefijado con el carácter @. El valor retornado puede ser usado para configurar la opción bitmap de los widgets de Tk y Tix.

tixCommand.tix_addbitmapdir(directory)

Tix mantiene una lista de directorios bajo los cuales los métodos tix_getimage() y tix_getbitmap() buscarán archivos de imágenes. El directorio de bitmap estándar es $TIX_LIBRARY/bitmaps. El método tix_addbitmapdir() añade directory a la lista. Al usar este método, los archivos de imagen de una aplicación pueden ser localizados usando el método tix_getimage() o tix_getbitmap().

tixCommand.tix_filedialog([dlgclass])

Retorna el diálogo de selección de archivo que puede ser compartido entre diferentes invocaciones de esta aplicación. Este método creará una widget de diálogo de selección de archivos cuando es invocado la primera vez. Este diálogo será retornado por las subsiguientes invocaciones de tix_filedialog(). Un parámetro dlgclass opcional puede ser pasado como cadena para especificar qué tipo de widget de selección de diálogo es deseado. Las opciones posibles son tix, FileSelectDialog, o tixExFileSelectDialog.

tixCommand.tix_getimage(self, name)

Localiza un archivo de imagen con el nombre name.xpm, name.xbm o name.ppm en uno de los directorios de bitmap (véase el método tix_addbitmapdir() arriba). Si existe más de un archivo con el mismo nombre (pero con diferentes extensiones), entonces el tipo de imagen es escogido de acuerdo a la profundidad del monitor X: las imágenes xbm son escogidas en monitores monocromos e imágenes de color son escogidas en monitores de color. Al usar tex_getimage(), puedes evitar codificar de forma directa los nombres de ruta de los archivos de imagen en tu aplicación. Cuando tiene éxito, este método retorna el nombre de la imagen recién creada, que puede ser usada para configurar la opción image de los widgets Tk y Tix.

tixCommand.tix_option_get(name)

Obtiene las opciones mantenidas por el mecanismo de esquema de Tix.

tixCommand.tix_resetoptions(newScheme, newFontSet[, newScmPrio])

Reinicia el esquema y conjunto de fuentes de la aplicación Tix a newScheme y newFontSet, respectivamente. Afecta sólo a los widgets creados después de esta invocación. Por lo tanto, es mejor invocar al método resetoptions antes de la creación de cualquier widget en una aplicación Tix.

Se le puede dar el parámetro opcional newScmPrio para reiniciar el nivel de prioridad de las opciones de Tk definidas por los esquemas de Tix.

Debido a la manera en que Tk gestiona la opción de la base de datos X, después de que Tix se haya importado e inicializado, no es posible reiniciar el esquema de colores y conjunto de fuentes usando el método tix_config() método. En vez de eso, se debe usar el método tix_resetoptions().