17.2. Widget FundamentalsTkinter supplies many kinds of widgets, and most of them have several things in common. All widgets are instances of classes that inherit from class Widget. Class Widget itself is abstract; that is, you never instantiate Widget itself. You only instantiate concrete subclasses corresponding to specific kinds of widgets. Class Widget's functionality is common to all the widgets you instantiate. To instantiate any kind of widget, call the widget's class. The first argument is the parent window of the widget, also known as the widget's master. If you omit this positional argument, the widget's master is the application's main window. All other arguments are in named form: option=value. To set or change options on an existing widget w, call w.config(option=value). To get an option of w call w.cget('option'), which returns the option's value. Each widget w is a mapping, so you can also get an option as w['option'], and set or change it with w['option']=value. 17.2.1. Common Widget OptionsMany widgets accept some common options. Some options affect a widget's colors, while others affect lengths (normally in pixels), and there are various other kinds. This section details the most commonly used options. 17.2.1.1. Color optionsTkinter represents colors with strings. The string can be a color name, such as 'red' or 'orange', or it may be of the form '#RRGGBB', where each R, G, and B are hexadecimal digits that represent a color by the values of red, green, and blue components on a scale of 0 to 255. Don't worry if your screen can't display millions of different colors, as implied by this scheme: Tkinter maps any requested color to the closest color that your screen can display. The common color options are:
17.2.1.2. Length optionsTkinter normally expresses a length as an integer number of pixels; other units of measure are possible, but rarely used. The common length options are:
17.2.1.3. Options expressing numbers of charactersSome options indicate a widget's requested layout not in pixels but rather as a number of characters, using average width or height of the widget's fonts:
17.2.1.4. Other common optionsOther options accepted by many kinds of widgets are a mixed bag that deals with both behavior and looks:
17.2.2. Common Widget MethodsA widget w supplies many methods. Besides event-related methods (covered in "Event-Related Methods" on page 448), commonly used widget methods are the following.
w supplies many other methods whose names start with winfo_, but the two above are the most often called, typically after calling w.update_idletasks. They let you ascertain a widget's dimensions after the user has resized a window, causing the layout manager to rearrange the widgets' layout. 17.2.3. Tkinter Variable ObjectsThe Tkinter module supplies classes whose instances represent variables. Each class deals with a specific data type: DoubleVar for float, IntVar for int, StringVar for str. Instantiate any of these classes without arguments to obtain an instance x, also known in Tkinter as a variable object, set to 0 or ''. x.set(datum) sets x's value to the given value; x.get( ) returns x's current value. You can pass x as the textvariable or variable configuration option for a widget. Once you do this, the widget's text changes to track any change to x's value, and, for some kinds of widgets, x's value tracks changes to the widget. A Tkinter variable can control more than one widget. Tkinter variables let you control widgets more transparently, and sometimes more conveniently, than explicitly querying and setting widget properties. The following example shows how to use a StringVar to connect an Entry widget and a Label widget automatically: import Tkinter root = Tkinter.Tk( ) tv = Tkinter.StringVar( ) Tkinter.Label(textvariable=tv).pack( ) Tkinter.Entry(textvariable=tv).pack( ) tv.set('Welcome!') Tkinter.Button(text="Exit", command=root.quit).pack( ) Tkinter.mainloop( ) print 'Final value is', tv.get( ) As you edit the Entry, you'll see the Label change automatically. This example instantiates the Tkinter main window explicitly, binds it to name root, and then sets as the Button's command the bound method root.quit, which quits Tkinter's main loop but does not terminate the Python application. Thus, the example ends with a print statement to show on standard output the final value of variable object tv. 17.2.4. Tkinter ImagesThe Tkinter class PhotoImage handles Graphical Interchange Format (GIF) and Portable PixMap (PPM) images. Call PhotoImage with a named argument file=path to load image data from the file at the given path and get an instance x. You can set x as the image configuration option for one or more widgets. The widgets display the image rather than text. For image-processing functionality on many image formats (including JPEG, PNG, and TIFF), use PIL, the Python Imaging Library (http://www.pythonware.com/products/pil/), which is designed to work with Tkinter. I do not cover PIL further in this book. Tkinter also supplies class BitmapImage, whose instances are usable wherever instances of PhotoImage are. BitmapImage supports some file formats known as "bitmaps." I do not cover BitmapImage further in this book. Being set as the image configuration option of a widget is not enough to keep instances of PhotoImage and BitmapImage alive. Hold such instances in a Python container object, such as a list or dictionary, so that the instances are not garbage-collected. The following example shows how to display some GIF images: import os import Tkinter root = Tkinter.Tk( ) L = Tkinter.Listbox(selectmode=Tkinter.SINGLE) gifsdict = {} dirpath = 'imgs' for gifname in os.listdir(dirpath): if not gifname[0].isdigit( ): continue gifpath = os.path.join(dirpath, gifname) gif = Tkinter.PhotoImage(file=gifpath) gifsdict[gifname] = gif L.insert(Tkinter.END, gifname) L.pack( ) img = Tkinter.Label( ) img.pack( ) def list_entry_clicked(*ignore): imgname = L.get(L.curselection( )[0]) img.config(image=gifsdict[imgname]) L.bind('<ButtonRelease-1>', list_entry_clicked) root.mainloop( ) Assuming you have in some directory ('imgs' in the example) several GIF files whose filenames start with digits, the example loads the images into memory, shows the names in a Listbox instance, and shows in a Label instance the GIF whose file you click on. For simplicity, the example does not give the Listbox widget a Scrollbar (we'll see how to equip a Listbox with a Scrollbar in "Scrollbar" on page 419). ![]() |