id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
5,000 | save coding time and provide nice native look-and-feel "smartand reusable quit button let' put some of these canned dialogs to better use example - implements an attachable quit button that uses standard dialogs to verify the quit request because it' classit can be attached and reused in any application that needs verifying quit button because it uses standard dialogsit looks as it should on each gui platform example - pp \gui\tour\quitter py "" quit button that verifies exit requeststo reuseattach an instance to other guisand re-pack as desired ""from tkinter import from tkinter messagebox import askokcancel get widget classes get canned std dialog class quitter(frame)subclass our gui def __init__(selfparent=none)constructor method frame __init__(selfparentself pack(widget button(selftext='quit'command=self quitwidget pack(side=leftexpand=yesfill=bothdef quit(self)ans askokcancel('verify exit'"really quit?"if ansframe quit(selfif __name__ ='__main__'quitter(mainloop(this module is mostly meant to be used elsewherebut it puts up the button it implements when run standalone figure - shows the quit button itself in the upper leftand the askokcancel verification dialog that pops up when quit is pressed figure - quitterwith askokcancel dialog dialogs |
5,001 | button is attached (reallythe mainloop callbut to really understand how such springloaded button can be usefulwe need to move on and study client gui in the next section dialog demo launcher bar so farwe've seen handful of standard dialogsbut there are quite few more instead of just throwing these up in dull screenshotsthoughlet' write python demo script to generate them on demand here' one way to do it first of allin example - we write module to define table that maps demo name to standard dialog call (and we use lambda to wrap the call if we need to pass extra arguments to the dialog functionexample - pp \gui\tour\dialogtable py define name:callback demos table from tkinter filedialog import askopenfilename get standard dialogs from tkinter colorchooser import askcolor they live in lib\tkinter from tkinter messagebox import askquestionshowerror from tkinter simpledialog import askfloat demos 'open'askopenfilename'color'askcolor'query'lambdaaskquestion('warning''you typed "rm *"\nconfirm?')'error'lambdashowerror('error!'"he' deadjim")'input'lambdaaskfloat('entry''enter credit card number' put this table in module so that it might be reused as the basis of other demo scripts later (dialogs are more fun than printing to stdoutnextwe'll write python scriptshown in example - which simply generates buttons for all of this table' entries-use its keys as button labels and its values as button callback handlers example - pp \gui\tour\demodlg py "create bar of simple buttons that launch dialog demosfrom tkinter import from dialogtable import demos from quitter import quitter get base widget set button callback handlers attach quit object to me class demo(frame)def __init__(selfparent=none**options)frame __init__(selfparent**optionsself pack(label(selftext="basic demos"pack(for (keyvaluein demos items()button(selftext=keycommand=valuepack(side=topfill=bothquitter(selfpack(side=topfill=both tkinter tourpart |
5,002 | this script creates the window shown in figure - when run as standalone programit' bar of demo buttons that simply route control back to the values of the table in the module dialogtable when pressed figure - demodlg main window notice that because this script is driven by the contents of the dialogtable module' dictionarywe can change the set of demo buttons displayed by changing just dialogtable (we don' need to change any executable code in demodlgalso note that the quit button here is an attached instance of the quitter class of the prior section whose frame is repacked to stretch like the other buttons as needed here--it' at least one bit of code that you never have to write again this script' class also takes care to pass any **options constructor configuration keyword arguments on to its frame superclass though not used herethis allows callers to pass in configuration options at creation time (demo( = ))instead of configuring after the fact config( = )this isn' strictly requiredbut it makes the demo class work just like normal tkinter frame widget (which is what subclassing makes itafter allwe'll see how this can be used to good effect later we've already seen some of the dialogs triggered by this demo bar window' other buttonsso 'll just step through the new ones here pressing the main window' query buttonfor examplegenerates the standard pop up in figure - this askquestion dialog looks like the askyesno we saw earlierbut actually it returns either string "yesor "no(askyesno and askokcancel return true or false instead-trivial but truepressing the demo bar' input button generates the standard ask float dialog box shown in figure - dialogs |
5,003 | figure - demodlg inputaskfloat dialog this dialog automatically checks the input for valid floating-point syntax before it returnsand it is representative of collection of single-value input dialogs (askinteger and askstring prompt for integer and string inputstooit returns the input as floating-point number object (not as stringwhen the ok button or enter key is pressedor the python none object if the user clicks cancel its two relatives return the input as integer and string objects instead when the demo bar' open button is pressedwe get the standard file open dialog made by calling askopenfilename and captured in figure - this is windows ' look-and-feelit can look radically different on macslinuxand older versions of windowsbut appropriately so similar dialog for selecting save-as filename is produced by calling asksaveasfile name (see the text widget section in for first exampleboth file dialogs let the user navigate through the filesystem to select subject filenamewhich is returned with its full directory pathname when open is pressedan empty string comes back if cancel is pressed instead both also have additional protocols not demonstrated by this examplethey can be passed filetypes keyword argument-- set of name patterns used to select fileswhich appear in the pull-down list near the bottom of the dialog tkinter tourpart |
5,004 | they can be passed an initialdir (start directory)initialfile (for "file name")title (for the dialog window)defaultextension (appended if the selection has none)and parent (to appear as an embedded child instead of pop-up dialogthey can be made to remember the last directory selected by using exported objects instead of these function calls-- hook we'll make use of in later longer-lived examples another common dialog call in the tkinter filedialog moduleaskdirectorycan be used to pop up dialog that allows users to choose directory rather than file it presents tree view that users can navigate to pick the desired directoryand it accepts keyword arguments including initialdir and title the corresponding directory object remembers the last directory selected and starts there the next time the dialog is shown we'll use most of these interfaces later in the bookespecially for the file dialogs in the pyedit example in but feel free to flip ahead for more details now the directory selection dialog will show up in the pyphoto example in and the pymailgui example in againskip ahead for code and screenshots finallythe demo bar' color button triggers standard askcolor callwhich generates the standard color selection dialog shown in figure - dialogs |
5,005 | if you press its ok buttonit returns data structure that identifies the selected colorwhich can be used in all color contexts in tkinter it includes rgb values and hexadecimal color string ( (( )'# ')more on how this tuple can be useful in moment if you press cancelthe script gets back tuple containing two nones (nones of the python varietythat isprinting dialog results and passing callback data with lambdas the dialog demo launcher bar displays standard dialogs and can be made to display others by simply changing the dialogtable module it imports as codedthoughit really shows only dialogsit would also be nice to see their return values so that we know how to use them in scripts example - adds printing of standard dialog results to the stdout standard output stream example - pp \gui\tour\demodlg-print py ""similarbut show return values of dialog callsthe lambda saves data from the local scope to be passed to the handler (button press handlers normally get no argumentsand enclosing scope references don' work for loop variablesand works just like nested def statementdef func(key=key)self printit(key"" tkinter tourpart |
5,006 | from dialogtable import demos from quitter import quitter get base widget set button callback handlers attach quit object to me class demo(frame)def __init__(selfparent=none)frame __init__(selfparentself pack(label(selftext="basic demos"pack(for key in demosfunc (lambda key=keyself printit(key)button(selftext=keycommand=funcpack(side=topfill=bothquitter(selfpack(side=topfill=bothdef printit(selfname)print(name'returns =>'demos[name]()fetchcallprint if __name__ ='__main__'demo(mainloop(this script builds the same main button-bar windowbut notice that the callback handler is an anonymous function made with lambda nownot direct reference to dialog calls in the imported dialogtable dictionaryuse enclosing scope lookup func (lambda key=keyself printit(key)we talked about this in the prior tutorialbut this is the first time we've actually used lambda like thisso let' get the facts straight because button-press callbacks are run with no argumentsif we need to pass extra data to the handlerit must be wrapped in an object that remembers that extra data and passes it alongby deferring the call to the actual handler herea button press runs the function generated by the lambdaan indirect call layer that retains information from the enclosing scope the net effect is that the real handlerprintitreceives an extra required name argument giving the demo associated with the button pressedeven though this argument wasn' passed back from tkinter itself in effectthe lambda remembers and passes on state information noticethoughthat this lambda function' body references both self and key in the enclosing method' local scope in all recent pythonsthe reference to self just works because of the enclosing function scope lookup rulesbut we need to pass key in explicitly with default argument or else it will be the same in all the generated lambda functions--the value it has after the last loop iteration as we learned in enclosing scope references are resolved when the nested function is calledbut defaults are resolved when the nested function is created because self won' change after the function is madewe can rely on the scope lookup rules for that namebut not for loop variables like key dialogs |
5,007 | scopes explicitlyusing either of these two techniquesuse simple defaults func (lambda self=selfname=keyself printit(name)use bound method default func (lambda handler=self printitname=keyhandler(name)todaywe can get away with the simpler enclosing -scope reference technique for selfthough we still need default for the key loop variable (and you may still see the default forms in older python codenote that the parentheses around the lambdas are not required herei add them as personal style preference just to set the lambda off from its surrounding code (your mileage may varyalso notice that the lambda does the same work as nested def statement herein practicethoughthe lambda could appear within the call to button itself because it is an expression and it need not be assigned to name the following two forms are equivalentfor (keyvaluein demos items()func (lambda key=keyself printit(key)can be nested button(for (keyvaluein demos items()def func(key=key)self printit(keybut def statement cannot you can also use callable class object here that retains state as instance attributes (see the tutorial' __call__ example in for hintsbut as rule of thumbif you want lambda' result to use any names from the enclosing scope when later calledeither simply name them and let python save their values for future useor pass them in with defaults to save the values they have at lambda function creation time the latter scheme is required only if the variable used may change before the callback occurs when runthis script creates the same window (figure - but also prints dialog return values to standard outputhere is the output after clicking all the demo buttons in the main window and picking both cancel/no and then ok/yes buttons in each dialogc:\pp \gui\tourpython demodlg-print py color returns =(nonenonecolor returns =(( )'# ff'query returns =no query returns =yes input returns =none input returns = open returns =open returns = :/users/mark/stuff/books/ /pp /dev/examples/pp /launcher py error returns =ok now that 've shown you these dialog resultsi want to next show you how one of them can actually be useful tkinter tourpart |
5,008 | the standard color selection dialog isn' just another pretty face--scripts can pass the hexadecimal color string it returns to the bg and fg widget color configuration options we met earlier that isbg and fg accept both color name ( blueand an ask color hex rgb result string that starts with ( the # ff in the last output line of the prior sectionthis adds another dimension of customization to tkinter guisinstead of hardcoding colors in your gui productsyou can provide button that pops up color selectors that let users choose color preferences on the fly simply pass the color string to widget config methods in callback handlersas in example - example - pp \gui\tour\setcolor py from tkinter import from tkinter colorchooser import askcolor def setbgcolor()(triplehexstraskcolor(if hexstrprint(hexstrpush config(bg=hexstrroot tk(push button(roottext='set background color'command=setbgcolorpush config(height= font=('times' 'bold')push pack(expand=yesfill=bothroot mainloop(this script creates the window in figure - when launched (its button' background is sort of greenbut you'll have to trust me on thispressing the button pops up the color selection dialog shown earlierthe color you pick in that dialog becomes the background color of this button after you press ok figure - setcolor main window dialogs |
5,009 | your computer to experiment with available color settingsc:\pp \gui\tourpython setcolor py # # # df other standard dialog calls we've seen most of the standard dialogs and we'll use these pop ups in examples throughout the rest of this book but for more details on other calls and options availableeither consult other tkinter documentation or browse the source code of the modules used at the top of the dialogtable module in example - all are simple python files installed in the tkinter subdirectory of the python source library on your machine ( in :\python \lib on windowsand keep this demo bar example filed away for future referencewe'll reuse it later in the tour for callback actions when we meet other button-like widgets the old-style dialog module in older python codeyou may see dialogs occasionally coded with the standard tkinter dialog module this is bit dated nowand it uses an windows look-and-feelbut just in case you run across such code in your python maintenance excursionsexample - gives you feel for the interface example - pp \gui\tour\dlg-old py from tkinter import from tkinter dialog import dialog class olddialogdemo(frame)def __init__(selfmaster=none)frame __init__(selfmasterpack config(selfsame as self pack(button(selftext='pop 'command=self dialog pack(button(selftext='pop 'command=self dialog pack(def dialog (self)ans dialog(selftitle text 'popup fun!''an example of popup-dialog 'boxusing older "dialog py'bitmap 'questhead'default strings ('yes''no''cancel')if ans num = self dialog (def dialog (self)dialog(selftitle text bitmap 'hal- '" ' afraid can' let you do thatdave "'hourglass' tkinter tourpart |
5,010 | if __name__ ='__main__'olddialogdemo(mainloop(if you supply dialog tuple of button labels and messageyou get back the index of the button pressed (the leftmost is index zerodialog windows are modalthe rest of the application' windows are disabled until the dialog receives response from the user when you press the pop button in the main window created by this scriptthe second dialog pops upas shown in figure - figure - old-style dialog this is running on windowsand as you can seeit is nothing like what you would expect on that platform for question dialog in factthis dialog generates an windows look-and-feelregardless of the underlying platform because of both dialog' appearance and the extra complexity required to program ityou are probably better off using the standard dialog calls of the prior section instead custom dialogs the dialogs we've seen so far have standard appearance and interaction they are fine for many purposesbut often we need something bit more custom for exampleforms that request multiple field inputs ( nameageshoe sizearen' directly addressed by the common dialog library we could pop up one single-input dialog in turn for each requested fieldbut that isn' exactly user friendly custom dialogs support arbitrary interfacesbut they are also the most complicated to program even sothere' not much to it--simply create pop-up window as toplevel with attached widgetsand arrange callback handler to fetch user inputs entered in the dialog (if anyand to destroy the window to make such custom dialog modalwe also need to wait for reply by giving the window input focusmaking other windows inactiveand waiting for an event example - illustrates the basics example - pp \gui\tour\dlg-custom py import sys from tkinter import makemodal (len(sys argv dialogs |
5,011 | win toplevel(make new window label(wintext='hard drive reformatted!'pack(add few widgets button(wintext='ok'command=win destroypack(set destroy callback if makemodalwin focus_set(take over input focuswin grab_set(disable other windows while ' openwin wait_window(and wait here until win destroyed print('dialog exit'else returns right away root tk(button(roottext='popup'command=dialogpack(root mainloop(this script is set up to create pop-up dialog window in either modal or nonmodal modedepending on its makemodal global variable if it is run with no command-line argumentsit picks nonmodal stylecaptured in figure - figure - nonmodal custom dialogs at work the window in the upper right is the root window herepressing its "popupbutton creates new pop-up dialog window because dialogs are nonmodal in this modethe root window remains active after dialog is popped up in factnonmodal dialogs never block other windowsso you can keep pressing the root' button to generate as many copies of the pop-up window as will fit on your screen any or all of the pop ups can be killed by pressing their ok buttonswithout killing other windows in this display making custom dialogs modal nowwhen the script is run with command-line argument ( python dlg-custom py )it makes its pop ups modal instead because modal dialogs grab all of the interface' attentionthe main window becomes inactive in this mode until the pop up is killedyou can' even click on it to reactivate it while the dialog is tkinter tourpart |
5,012 | at onceas shown in figure - figure - modal custom dialog at work in factthe call to the dialog function in this script doesn' return until the dialog window on the left is dismissed by pressing its ok button the net effect is that modal dialogs impose function call-like model on an otherwise event-driven programming modeluser inputs can be processed right awaynot in callback handler triggered at some arbitrary point in the future forcing such linear control flow on gui takes bit of extra workthough the secret to locking other windows and waiting for reply boils down to three lines of codewhich are general pattern repeated in most custom modal dialogs win focus_set(makes the window take over the application' input focusas if it had been clicked with the mouse to make it the active window this method is also known by the synonym focusand it' also common to set the focus on an input widget within the dialog ( an entryrather than on the entire window win grab_set(disables all other windows in the application until this one is destroyed the user cannot interact with other windows in the program while grab is set win wait_window(pauses the caller until the win widget is destroyedbut keeps the main eventprocessing loop (mainloopactive during the pause that means that the gui at large remains active during the waitits windows redraw themselves if covered and uncoveredfor example when the window is destroyed with the destroy methodit is erased from the screenthe application grab is automatically releasedand this method call finally returns because the script waits for window destroy eventit must also arrange for callback handler to destroy the window in response to interaction with widgets in the dialog window (the only window activethis example' dialog is simply informationalso its ok button calls the window' destroy method in user-input dialogswe might instead install an enter key-press callback handler that fetches data typed into an entry widget and then calls destroy (see later in this dialogs |
5,013 | modal dialogs are typically implemented by waiting for newly created pop-up window' destroy eventas in this example but other schemes are viable too for exampleit' possible to create dialog windows ahead of timeand show and hide them as needed with the top-level window' deiconify and withdraw methods (see the alarm scripts near the end of for detailsgiven that window creation speed is generally fast enough as to appear instantaneous todaythis is much less common than making and destroying window from scratch on each interaction it' also possible to implement modal state by waiting for tkinter variable to change its valueinstead of waiting for window to be destroyed see this later discussion of tkinter variables (which are class objectsnot normal python variablesand the wait_variable method discussed near the end of for more details this scheme allows long-lived dialog box' callback handler to signal state change to waiting main programwithout having to destroy the dialog box finallyif you call the mainloop method recursivelythe call won' return until the widget quit method has been invoked the quit method terminates mainloop calland so normally ends gui program but it will simply exit recursive mainloop level if one is active because of thismodal dialogs can also be written without wait method calls if you are careful for instanceexample - works the same way as the modal mode of dlg-custom example - pp \gui\tour\dlg-recursive py from tkinter import def dialog()win toplevel(label(wintext='hard drive reformatted!'pack(button(wintext='ok'command=win quitpack(win protocol('wm_delete_window'win quitwin focus_set(win grab_set(win mainloop(win destroy(print('dialog exit'make new window add few widgets set quit callback quit on wm close tootake over input focusdisable other windows while ' openand start nested event loop to wait root tk(button(roottext='popup'command=dialogpack(root mainloop(if you go this routebe sure to call quit rather than destroy in dialog callback handlers (destroy doesn' terminate the mainloop level)and be sure to use protocol to make the window border close button call quit too (or else it won' end the recursive mainloop level call and may generate odd error messages when your program finally exitsbecause of this extra complexityyou're probably better off using wait_window or wait_variablenot recursive mainloop calls tkinter tourpart |
5,014 | when we meet entryand again when we study the grid manager in for more custom dialog examplessee shellgui ()pymailgui ()pycalc ()and the nonmodal form py (herewe're moving on to learn more about events that will prove to be useful currency at later tour destinations binding events we met the bind widget method in the prior when we used it to catch button presses in the tutorial because bind is commonly used in conjunction with other widgets ( to catch return key presses for input boxes)we're going to make stop early in the tour here as well example - illustrates more bind event protocols example - pp \gui\tour\bind py from tkinter import def showposevent(event)print('widget=% =% =% (event widgetevent xevent )def showallevent(event)print(eventfor attr in dir(event)if not attr startswith('__')print(attr'=>'getattr(eventattr)def onkeypress(event)print('got key press:'event chardef onarrowkey(event)print('got up arrow key press'def onreturnkey(event)print('got return key press'def onleftclick(event)print('got left mouse button click:'end='showposevent(eventdef onrightclick(event)print('got right mouse button click:'end='showposevent(eventdef onmiddleclick(event)print('got middle mouse button click:'end='showposevent(eventshowallevent(eventdef onleftdrag(event)print('got left mouse button drag:'end='showposevent(eventbinding events |
5,015 | print('got double left mouse click'end='showposevent(eventtkroot quit(tkroot tk(labelfont ('courier' 'bold'widget label(tkroottext='hello bind world'widget config(bg='red'font=labelfontwidget config(height= width= widget pack(expand=yesfill=bothfamilysizestyle red backgroundlarge font initial sizelines,chars widget bind(''onleftclickwidget bind(''onrightclickwidget bind(''onmiddleclickwidget bind(''ondoubleleftclickwidget bind(''onleftdragmouse button clicks widget bind(''widget bind(''widget bind(''widget focus(tkroot title('click me'tkroot mainloop(all keyboard presses arrow button pressed return/enter key pressed or bind keypress to tkroot onkeypressonarrowkeyonreturnkeymiddle=both on some mice click left twice click left and move most of this file consists of callback handler functions triggered when bound events occur as we learned in this type of callback receives an event object argument that gives details about the event that fired technicallythis argument is an instance of the tkinter event classand its details are attributesmost of the callbacks simply trace events by displaying relevant event attributes when runthis script makes the window shown in figure - it' mostly intended just as surface for clicking and pressing event triggers figure - bind window for the clicking the black-and-white medium of the book you're holding won' really do justice to this script when run liveit uses the configuration options shown earlier to make the tkinter tourpart |
5,016 | word for it (or run this on your ownbut the main point of this example is to demonstrate other kinds of event binding protocols at work we saw script that intercepted left and double-left mouse clicks with the widget bind method in using event names and the script here demonstrates other kinds of events that are commonly caught with bindto catch the press of single key on the keyboardregister handler for the event identifierthis is lower-level way to input data in gui programs than the entry widget covered in the next section the key pressed is returned in ascii string form in the event object passed to the callback handler (event charother attributes in the event structure identify the key pressed in lower-level detail key presses can be intercepted by the top-level root window widget or by widget that has been assigned keyboard focus with the focus method used by this script this script also catches mouse motion while button is held downthe registered event handler is called every time the mouse is moved while the left button is pressed and receives the current / coordinates of the mouse pointer in its event argument (event xevent ysuch information can be used to implement object movesdrag-and-droppixel-level paintingand so on ( see the pydraw examples in this script also catches right and middle mouse button clicks (known as buttons and to make the middle button click work on two-button mousetry clicking both buttons at the same timeif that doesn' workcheck your mouse setting in your properties interface (the control panel on windowsto catch more specific kinds of key pressesthis script registers for the returnenter and up-arrow key press eventsthese events would otherwise be routed to the general handler and require event analysis here is what shows up in the stdout output stream after left clickright clickleft click and draga few key pressesa return and up-arrow pressand final double-left click to exit when you press the left mouse button and drag it around on the displayyou'll get lots of drag event messagesone is printed for every move during the drag (and one python callback is run for each) :\pp \gui\tourpython bind py got left mouse button clickwidget = = got right mouse button clickwidget = = got left mouse button clickwidget = = got left mouse button dragwidget = = got left mouse button dragwidget = = binding events |
5,017 | got left mouse button dragwidget = = got left mouse button dragwidget = = got key presss got key pressp got key pressa got key pressm got key press got key pressgot key press got key pressgot return key press got up arrow key press got left mouse button clickwidget = = got double left mouse click widget = = for mouse-related eventscallbacks print the and coordinates of the mouse pointerin the event object passed in coordinates are usually measured in pixels from the upper-left corner ( , )but are relative to the widget being clicked here' what is printed for leftmiddleand double-left click notice that the middle-click callback dumps the entire argument--all of the event object' attributes (less internal names that begin with "__which includes the __doc__ stringand default operator overloading methods inherited from the implied object superclass in python xdifferent event types set different event attributesmost key presses put something in charfor instancec:\pp \gui\tourpython bind py got left mouse button clickwidget = = got middle mouse button clickwidget = = char =?delta = height =?keycode =?keysym =?keysym_num =?num = send_event =false serial = state = time = type = widget = width =? = x_root = = y_root = got left mouse button clickwidget = = got double left mouse click widget = = tkinter tourpart |
5,018 | besides those illustrated in this examplea tkinter script can register to catch additional kinds of bindable events for examplefires when button is released is run when the button first goes downis triggered when mouse pointer is moved and handlers intercept mouse entry and exit in window' display area (useful for automatically highlighting widgetis invoked when the window is resizedrepositionedand so on ( the event object' width and height give the new window sizewe'll make use of this to resize the display on window resizes in the pyclock example of is invoked when the window widget is destroyed (and differs from the protocol mechanism for window manager close button pressessince this interacts with widget quit and destroy methodsi'll say more about the event later in this section and are run as the widget gains and loses focus and are run when window is opened and iconified and catch other special key presses and catch other arrow key presses this is not complete listand event names can be written with somewhat sophisticated syntax of their own for instancemodifiers can be added to event identifiers to make them even more specificfor instancemeans moving the mouse with the left button pressedand refers to pressing the "akey only synonyms can be used for some common event namesfor instance<button press- >and mean left mouse button pressand and mean the "akey all forms are case sensitiveuse not virtual event identifiers can be defined within double bracket pairs ( <<paste text>>to refer to selection of one or more event sequences in the interest of spacethoughwe'll defer to other tk and tkinter reference sources for an exhaustive list of details on this front alternativelychanging some of the settings in the example script and rerunning can help clarify some event behaviortoothis is pythonafter all more on events and the quit and destroy methods before we move onone event merits few extra wordsthe event (whose name is case significantis run when widget is being destroyedas result of both binding events |
5,019 | if you bind this on windowit will be triggered once for each widget in the windowthe callback' event argument widget attribute gives the widget being destroyedand you can check this to detect particular widget' destruction if you bind this on specific widget insteadit will be triggered once for that widget' destruction only it' important to know that widget is in "half deadstate (tk' terminologywhen this event is triggered--it still existsbut most operations on it fail because of thatthe event is not intended for gui activity in generalfor instancechecking text widget' changed state or fetching its content in handler can both fail with exceptions in additionthis event' handler cannot cancel the destruction in general and resume the guiif you wish to intercept and verify or suppress window closes when user clicks on window' buttonuse wm_delete_window in top-level windowsprotocol methods as described earlier in this you should also know that running tkinter widget' quit method does not trigger any events on exitand even leads to fatal python error on program exit in if any event handlers are registered because of thisprograms that bind this event for non-gui window exit actions should usually call destroy instead of quit to closeand rely on the fact that program exits when the last remaining or only tk root window (default or explicitis destroyed as described earlier this precludes using quit for immediate shutdownsthough you can still run sys exit for brute-force exits script can also perform program exit actions in code run after the mainloop call returnsbut the gui is gone completely at this pointand this code is not associated with any particular widget watch for more on this event when we study the pyedit example program in at the risk of spoiling the end of this storywe'll find it unusable for verifying changed text saves message and entry the message and entry widgets allow for display and input of simple text both are essentially functional subsets of the text widget we'll meet latertext can do everything message and entry canbut not vice versa message the message widget is simply place to display text although the standard showinfo dialog we met earlier is perhaps better way to display pop-up messagesmessage splits up long strings automatically and flexibly and can be embedded inside container widgets any time you need to add some read-only text to display moreoverthis widget sports more than dozen configuration options that let you customize its appearance example - and figure - illustrate message basicsand demonstrates how message reacts to horizontal stretching with fill and expandsee for more on resizing and tk or tkinter references for other options message supports tkinter tourpart |
5,020 | from tkinter import msg message(text="oh by the waywhich one' pink?"msg config(bg='pink'font=('times' 'italic')msg pack(fill=xexpand=yesmainloop(figure - message widget at work entry the entry widget is simplesingle-line text input field it is typically used for input fields in form-like dialogs and anywhere else you need the user to type value into field of larger display entry also supports advanced concepts such as scrollingkey bindings for editingand text selectionsbut it' simple to use in practice example - builds the input window shown in figure - example - pp \gui\tour\entry py from tkinter import from quitter import quitter def fetch()print('input ="% "ent get()get text root tk(ent entry(rootent insert( 'type words here'ent pack(side=topfill=xset text grow horiz ent focus(ent bind(''(lambda eventfetch())btn button(roottext='fetch'command=fetchbtn pack(side=leftquitter(rootpack(side=rightroot mainloop(save click on enter key and on button message and entry |
5,021 | on startupthe entry script fills the input field in this gui with the text "type words hereby calling the widget' insert method because both the fetch button and the enter key are set to trigger the script' fetch callback functioneither user event gets and displays the current text in the input fieldusing the widget' get methodc:\pp \gui\tourpython entry py input ="type words hereinput ="have cigarwe met the event earlier when we studied bindunlike button pressesthese lower-level callbacks get an event argumentso the script uses lambda wrapper to ignore it this script also packs the entry field with fill= to make it expand horizontally with the window (try it out)and it calls the widget focus method to give the entry field input focus when the window first appears manually setting the focus like this saves the user from having to click the input field before typing our smart quit button we wrote earlier is attached here again as well (it verifies exitprogramming entry widgets generally speakingthe values typed into and displayed by entry widgets are set and fetched with either tied "variableobjects (described later in this or entry widget method calls such as this oneent insert( 'some text'value ent get(set value fetch value ( stringthe first parameter to the insert method gives the position where the text is to be inserted here" means the front because offsets start at zeroand integer and string ' mean the same thing (tkinter method arguments are always converted to strings if neededif the entry widget might already contain textyou also generally need to delete its contents before setting it to new valueor else new text will simply be added to the text already presentent delete( endent insert( 'some text'firstdelete from start to end then set value the name end here is preassigned tkinter constant denoting the end of the widgetwe'll revisit it in when we meet the full-blown and multiple-line text widget (entry' more powerful cousinsince the widget is empty after the deletionthis statement sequence is equivalent to the prior one tkinter tourpart |
5,022 | ent insert(end'some text'delete from start to end add at end of empty text either wayif you don' delete the text firstnew text that is inserted is simply added if you want to see howtry changing the fetch function in example - to look like this--an "xis added at the beginning and end of the input field on each button or key pressdef fetch()print('input ="% "ent get()ent insert(end' 'ent insert( ' 'get text to clearent delete(' 'endnew text simply added in later exampleswe'll also see the entry widget' state='disabledoptionwhich makes it read onlyas well as its show='*optionwhich makes it display each character as (useful for password-type inputstry this out on your own by changing and running this script for quick look entry supports other options we'll skip heretoosee later examples and other resources for additional details laying out input forms as mentionedentry widgets are often used to get field values in form-like displays we're going to create such displays often in this bookbut to show you how this works in simpler termsexample - combines labelsentriesand frames to achieve the multiple-input display captured in figure - example - pp \gui\tour\entry py ""use entry widgets directly lay out by rows with fixed-width labelsthis and grid are best for forms ""from tkinter import from quitter import quitter fields 'name''job''paydef fetch(entries)for entry in entriesprint('input ="% "entry get()def makeform(rootfields)entries [for field in fieldsrow frame(rootlab label(rowwidth= text=fieldent entry(rowrow pack(side=topfill=xlab pack(side=leftent pack(side=rightexpand=yesfill=xentries append(entreturn entries get text make new row add labelentry pack row on top grow horizontal message and entry |
5,023 | root tk(ents makeform(rootfieldsroot bind(''(lambda eventfetch(ents))button(roottext='fetch'command(lambdafetch(ents))pack(side=leftquitter(rootpack(side=rightroot mainloop(figure - entry (and entry form displays the input fields here are just simple entry widgets the script builds an explicit list of these widgets to be used to fetch their values later every time you press this window' fetch buttonit grabs the current values in all the input fields and prints them to the standard output streamc:\pp \gui\tourpython entry py input ="bobinput ="technical writerinput ="jackyou get the same field dump if you press the enter key anytime this window has the focus on your screenthis event has been bound to the whole root window this timenot to single input field most of the art in form layout has to do with arranging widgets in hierarchy this script builds each label/entry row as new frame attached to the window' current topfixed-width labels are attached to the left of their rowand entries to the right because each row is distinct frameits contents are insulated from other packing going on in this window the script also arranges for just the entry fields to grow vertically on resizeas in figure - going modal again later on this tourwe'll see how to make similar form layouts with the grid geometry managerwhere we arrange by row and column numbers instead of frames but now that we have handle on form layoutlet' see how to apply the modal dialog techniques we met earlier to more complex input display tkinter tourpart |
5,024 | example - uses the prior example' makeform and fetch functions to generate form and prints its contentsmuch as before herethoughthe input fields are attached to new toplevel pop-up window created on demandand an ok button is added to the new window to trigger window destroy event that erases the pop up as we learned earlierthe wait_window call pauses until the destroy happens example - pp \gui\tour\entry -modal py make form dialog modalmust fetch before destroy with entries from tkinter import from entry import makeformfetchfields def show(entriespopup)fetch(entriespopup destroy(must fetch before window destroyedfails with msgs if stmt order is reversed def ask()popup toplevel(show form in modal dialog window ents makeform(popupfieldsbutton(popuptext='ok'command=(lambdashow(entspopup))pack(popup grab_set(popup focus_set(popup wait_window(wait for destroy here root tk(button(roottext='dialog'command=askpack(root mainloop(when you run this codepressing the button in this program' main window creates the blocking form input dialog in figure - as expected but subtle danger is lurking in this modal dialog codebecause it fetches user inputs from entry widgets embedded in the popped-up displayit must fetch those inputs before destroying the pop-up window in the ok press callback handler it turns out that destroy call really does destroy all the child widgets of the window destroyedtrying to fetch values from destroyed entry not only doesn' workbut also generates traceback with error messages in the console window try reversing the statement order in the show function to see for yourself message and entry |
5,025 | to avoid this problemwe can either be careful to fetch before destroyingor use tkinter variablesthe subject of the next section tkinter "variablesand form layout alternatives entry widgets (among otherssupport the notion of an associated variable--changing the associated variable changes the text displayed in the entryand changing the text in the entry changes the value of the variable these aren' normal python variable namesthough variables tied to widgets are instances of variable classes in the tkinter module library these classes are named stringvarintvardoublevarand boolean varyou pick one based on the context in which it is to be used for examplea string var class instance can be associated with an entry fieldas demonstrated in example - example - pp \gui\tour\entry py ""use stringvar variables lay out by columnsthis might not align horizontally everywhere (see entry ""from tkinter import from quitter import quitter fields 'name''job''paydef fetch(variables)for variable in variablesprint('input ="% "variable get() tkinter tourpart get from var |
5,026 | form frame(rootleft frame(formrite frame(formform pack(fill=xleft pack(side=leftrite pack(side=rightexpand=yesfill=xvariables [for field in fieldslab label(leftwidth= text=fieldent entry(ritelab pack(side=topent pack(side=topfill=xvar stringvar(ent config(textvariable=varvar set('enter here'variables append(varreturn variables make outer frame make two columns grow horizontal add to columns grow horizontal link field to var if __name__ ='__main__'root tk(vars makeform(rootfieldsbutton(roottext='fetch'command=(lambdafetch(vars))pack(side=leftquitter(rootpack(side=rightroot bind(''(lambda eventfetch(vars))root mainloop(except for the fact that this script initializes input fields with the string 'enter here'it makes window virtually identical in appearance and function to that created by the script entry (see figures - and - for illustration purposesthe window is laid out differently--as frame containing two nested subframes used to build the left and right columns of the form area--but the end result is the same when it is displayed on screen (for some guis on some platformsat leastsee the note at the end of this section for discussion of why layout by rows instead of columns is generally preferredthe main thing to notice herethoughis the use of stringvar variables instead of using list of entry widgets to fetch input valuesthis version keeps list of stringvar objects that have been associated with the entry widgetslike thisent entry(ritevar stringvar(ent config(textvariable=varlink field to var once you've tied variables in this waychanging and fetching the variable' valuevar set('text here'value var get(message and entry |
5,027 | object get method returns as string for stringvaran integer for intvarand floatingpoint number for doublevar of coursewe've already seen that it' easy to set and fetch text in entry fields directlywithout adding extra code to use variables sowhy the bother about variable objectsfor one thingit clears up that nasty fetch-after-destroy peril we met in the prior section because stringvars live on after the entry widgets they are tied to have been destroyedit' ok to fetch input values from them long after modal dialog has been dismissedas shown in example - example - pp \gui\tour\entry -modal py can fetch values after destroy with stringvars from tkinter import from entry import makeformfetchfields def show(variablespopup)popup destroy(fetch(variablesorder doesn' matter here variables live on after window destroyed def ask()popup toplevel(show form in modal dialog window vars makeform(popupfieldsbutton(popuptext='ok'command=(lambdashow(varspopup))pack(popup grab_set(popup focus_set(popup wait_window(wait for destroy here root tk(button(roottext='dialog'command=askpack(root mainloop(this version is the same as the original (shown in example - and figure - )but show now destroys the pop up before inputs are fetched through stringvars in the list created by makeform in other wordsvariables are bit more robust in some contexts because they are not part of real display tree for examplethey are also commonly associated with check buttonsradio boxesand scales in order to provide access to current settings and link multiple widgets together almost coincidentallythat' the topic of the next section historic anecdotein now-defunct tkinter release shipped with python you could also set and fetch variable values by calling them like functionswith and without an argument ( var(valueand var()todayyou call variable set and get methods instead for unknown reasonsthe function call form stopped working years agobut you may still see it in older python code (and in first editions of at least one 'reilly python bookif fix made in the name of aesthetics breaks working codeis it really fix tkinter tourpart |
5,028 | fixed-width labels (entry )and by column frames (entry in we'll see third form techniquelayouts using the grid geometry manager of thesegriddingand the rows with fixed-width labels of entry tend to work best across all platforms laying out by column frames as in entry works only on platforms where the height of each label exactly matches the height of each entry field because the two are not associated directlythey might not line up properly on some platforms when tried running some forms that looked fine on windows xp on linux machinelabels and their corresponding entries did not line up horizontally even the simple window produced by entry looks slightly askew on closer inspection it only appears the same as entry on some platforms because of the small number of inputs and size defaults on my windows netbookthe labels and entries start to become horizontally mismatched if you add or additional inputs to entry ' fields tuple if you care about portabilitylay out your forms either with the packed row frames and fixed/maximum-width labels of entry or by gridding widgets by row and column numbers instead of packing them we'll see more on such forms in the next and in we'll write form-construction tool that hides the layout details from its clients altogether (including its use case client in checkbuttonradiobuttonand scale this section introduces three widget typesthe checkbutton ( multiple-choice input widget)the radiobutton ( single-choice device)and the scale (sometimes known as "slider"all are variations on theme and are somewhat related to simple buttonsso we'll explore them as group here to make these widgets more fun to play withwe'll reuse the dialogtable module shown in example - to provide callbacks for widget selections (callbacks pop up dialog boxesalong the waywe'll also use the tkinter variables we just met to communicate with these widgetsstate settings checkbuttons the checkbutton and radiobutton widgets are designed to be associated with tkinter variablesclicking the button changes the value of the variableand setting the variable changes the state of the button to which it is linked in facttkinter variables are central to the operation of these widgetsa collection of checkbuttons implements multiple-choice interface by assigning each button variable of its own collection of radiobuttons imposes mutually exclusive single-choice model by giving each button unique value and the same tkinter variable checkbuttonradiobuttonand scale |
5,029 | lets you register callback to be run immediately on button-press eventsmuch like normal button widgets but by associating tkinter variable with the variable optionyou can also fetch or change widget state at any time by fetching or changing the value of the widget' associated variable since it' bit simplerlet' start with the tkinter checkbutton example - creates the set of five captured in figure - to make this more usefulit also adds button that dumps the current state of all checkbuttons and attaches an instance of the verifying quitter button we built earlier in the tour figure - democheck in action example - pp \gui\tour\democheck py "create bar of check buttons that run dialog demosfrom tkinter import from dialogtable import demos from quitter import quitter get base widget set get canned dialogs attach quitter object to "meclass demo(frame)def __init__(selfparent=none**options)frame __init__(selfparent**optionsself pack(self tools(label(selftext="check demos"pack(self vars [for key in demosvar intvar(checkbutton(selftext=keyvariable=varcommand=demos[key]pack(side=leftself vars append(vardef report(self)for var in self varsprint(var get()end='print(def tools(self)frm frame(selffrm pack(side=right tkinter tourpart current toggle settings or |
5,030 | quitter(frmpack(fill=xif __name__ ='__main__'demo(mainloop(in terms of program codecheck buttons resemble normal buttonsthey are even packed within container widget operationallythoughthey are bit different as you can probably tell from this figure (and can better tell by running this live) check button works as toggle--pressing one changes its state from off to on (from deselected to selected)or from on to off again when check button is selectedit has checked displayand its associated intvar variable has value of when deselectedits display is empty and its intvar has value of to simulate an enclosing applicationthe state button in this display triggers the script' report method to display the current values of all five toggles on the stdout stream here is the output after few clicksc:\pp \gui\tourpython democheck py reallythese are the values of the five tkinter variables associated with the checkbuttons with variable optionsbut they give the buttonsvalues when queried this script associates intvar variables with each checkbutton in this displaysince they are or binary indicators stringvars will work heretooalthough their get methods would return strings ' or ' (not integersand their initial state would be an empty string (not the integer this widget' command option lets you register callback to be run each time the button is pressed to illustratethis script registers standard dialog demo call as handler for each of the checkbuttons--pressing button changes the toggle' state but also pops up one of the dialog windows we visited earlier in this tour (regardless of its new stateinterestinglyyou can sometimes run the report method interactivelytoo--when working as follows in shell windowwidgets pop up as lines are typed and are fully activeeven without calling mainloop (though this may not work in some interfaces like idle if you must call mainloop to display your gui) :\pp \gui\tourpython from democheck import demo demo( report( report( report( checkbuttonradiobuttonand scale |
5,031 | when first studied check buttonsmy initial reaction waswhy do we need tkinter variables here at all when we can register button-press callbackslinked variables may seem superfluous at first glancebut they simplify some gui chores instead of asking you to accept this blindlythoughlet me explain why keep in mind that checkbutton' command callback will be run on every presswhether the press toggles the check button to selected or deselected state because of thatif you want to run an action immediately when check button is pressedyou will generally want to check the button' current value in the callback handler because there is no check button "getmethod for fetching valuesyou usually need to interrogate an associated variable to see if the button is on or off moreoversome guis simply let users set check buttons without running command callbacks at all and fetch button settings at some later point in the program in such scenariovariables serve to automatically keep track of button settings the demo check script' report method represents this latter approach of courseyou could manually keep track of each button' state in press callback handlerstoo example - keeps its own list of state toggles and updates it manually on command press callbacks example - pp \gui\tour\demo-check-manual py check buttonsthe hard way (without variablesfrom tkinter import states [def onpress( )states[inot states[ichange object not name keep track of states changes false->truetrue->false root tk(for in range( )chk checkbutton(roottext=str( )command=(lambda =ionpress( )chk pack(side=leftstates append(falseroot mainloop(print(statesshow all states on exit the lambda here passes along the pressed button' index in the states list otherwisewe would need separate callback function for each button here againwe need to use default argument to pass the loop variable into the lambdaor the loop variable will be its value on the last loop iteration for all of the generated functions (each press would update the tenth item in the listsee for background details on thiswhen runthis script makes the -check button display in figure - tkinter tourpart |
5,032 | manually maintained state toggles are updated on every button press and are printed when the gui exits (technicallywhen the mainloop call returns)it' list of boolean state valueswhich could also be integers or if we cared to exactly imitate the originalc:\pp \gui\tourpython demo-check-manual py [falsefalsetruefalsetruefalsefalsefalsetruefalsethis worksand it isn' too horribly difficult to manage manually but linked tkinter variables make this task noticeably easierespecially if you don' need to process check button states until some time in the future this is illustrated in example - example - pp \gui\tour\demo-check-auto py check buttonsthe easy way from tkinter import root tk(states [for in range( )var intvar(chk checkbutton(roottext=str( )variable=varchk pack(side=leftstates append(varroot mainloop(let tkinter keep track print([var get(for var in states]show all states on exit (or map/lambdathis looks and works the same waybut there is no command button-press callback handler at allbecause toggle state is tracked by tkinter automaticallyc:\pp \gui\tourpython demo-check-auto py [ the point here is that you don' necessarily have to link variables with check buttonsbut your gui life will be simpler if you do the list comprehension at the very end of this scriptby the wayis equivalent to the following unbound method and lambdabound-method map call formsprint(list(map(intvar getstates))print(list(map(lambda varvar get()states))though comprehensions are common in python todaythe form that seems clearest to you may very well depend upon your shoe size checkbuttonradiobuttonand scale |
5,033 | radio buttons are toggles toobut they are generally used in groupsjust like the mechanical station selector pushbuttons on radios of times gone bypressing one radio button widget in group automatically deselects the one pressed last in other wordsat mostonly one can be selected at one time in tkinterassociating all radio buttons in group with unique values and the same variable guarantees thatat mostonly one can ever be selected at given time like check buttons and normal buttonsradio buttons support command option for registering callback to handle presses immediately like check buttonsradio buttons also have variable attribute for associating single-selection buttons in group and fetching the current selection at arbitrary times in additionradio buttons have value attribute that lets you tell tkinter what value the button' associated variable should have when the button is selected because more than one radio button is associated with the same variableyou need to be explicit about each button' value (it' not just or toggle scenarioexample - demonstrates radio button basics example - pp \gui\tour\demoradio py "create group of radio buttons that launch dialog demosfrom tkinter import from dialogtable import demos from quitter import quitter get base widget set button callback handlers attach quit object to "meclass demo(frame)def __init__(selfparent=none**options)frame __init__(selfparent**optionsself pack(label(selftext="radio demos"pack(side=topself var stringvar(for key in demosradiobutton(selftext=keycommand=self onpressvariable=self varvalue=keypack(anchor=nwself var set(keyselect last to start button(selftext='state'command=self reportpack(fill=xquitter(selfpack(fill=xdef onpress(self)pick self var get(print('you pressed'pickprint('result:'demos[pick]()def report(self)print(self var get()if __name__ ='__main__'demo(mainloop( tkinter tourpart |
5,034 | radio buttons triggers its command handlerpops up one of the standard dialog boxes we met earlierand automatically deselects the button previously pressed like check buttonsradio buttons are packedthis script packs them to the top to arrange them verticallyand then anchors each on the northwest corner of its allocated space so that they align well figure - demoradio in action like the check button demo scriptthis one also puts up state button to run the class' report method and to show the current radio state (the button selectedunlike the check button demothis script also prints the return values of dialog demo calls that are run as its buttons are pressed here is what the stdout stream looks like after few presses and state dumpsstates are shown in boldc:\pp \gui\tourpython demoradio py you pressed input result input you pressed open resultc:/pp thed/examples/pp /gui/tour/demoradio py open you pressed query resultyes query radio buttons and variables sowhy variables herefor one thingradio buttons also have no "getwidget method to fetch the selection in the future more importantlyin radio button groupsthe value and variable settings turn out to be the whole basis of single-choice behavior in checkbuttonradiobuttonand scale |
5,035 | with the same tkinter variable and have distinct value settings to truly understand whythoughyou need to know bit more about how radio buttons and variables do their stuff we've already seen that changing widget changes its associated tkinter variableand vice versa but it' also true that changing variable in any way automatically changes every widget it is associated with in the world of radio buttonspressing button sets shared variablewhich in turn impacts other buttons associated with that variable assuming that all radio buttons have distinct valuesthis works as you expect it to work when button press changes the shared variable to the pressed button' valueall other buttons are deselectedsimply because the variable has been changed to value not their own this is true both when the user selects button and changes the shared variable' value implicitlybut also when the variable' value is set manually by script for instancewhen example - sets the shared variable to the last of the demo' names initially (with self var set)it selects that demo' button and deselects all the others in the processthis wayonly one is selected at first if the variable was instead set to string that is not any demo' name ( ')all buttons would be deselected at startup this ripple effect is bit subtlebut it might help to know that within group of radio buttons sharing the same variableif you assign set of buttons the same valuethe entire set will be selected if any one of them is pressed consider example - which creates figure - for instance all buttons start out deselected this time (by initializing the shared variable to none of their values)but because radio buttons and have value (the remainder of division by )all are selected if any are selected figure - radio buttons gone badexample - pp \gui\tour\demo-radio-multi py see what happens when some buttons have same value from tkinter import root tk(var stringvar(for in range( )rad radiobutton(roottext=str( )variable=varvalue=str( )rad pack(side=leftvar set('deselect all initially root mainloop( tkinter tourpart |
5,036 | are cleared (they don' have the value " "that' not normally what you want--radio buttons are usually single-choice group (check buttons handle multiple-choice inputsif you want them to work as expectedbe sure to give each radio button the same variable but unique value across the entire group in the demoradio scriptfor instancethe name of the demo provides naturally unique value for each button radio buttons without variables strictly speakingwe could get by without tkinter variables heretoo example - for instanceimplements single-selection model without variablesby manually selecting and deselecting widgets in the groupin callback handler of its own on each press eventit issues deselect calls for every widget object in the group and select for the one pressed example - pp \gui\tour\demo-radio-manual py ""radio buttonsthe hard way (without variablesnote that deselect for radio buttons simply sets the button' associated value to null stringso we either need to still give buttons unique valuesor use checkbuttons here instead""from tkinter import state 'buttons [def onpress( )global state state for btn in buttonsbtn deselect(buttons[iselect(root tk(for in range( )rad radiobutton(roottext=str( )value=str( )command=(lambda =ionpress( )rad pack(side=leftbuttons append(radonpress( root mainloop(print(stateselect first initially show state on exit this works it creates -radio button window that looks just like the one in figure - but implements single-choice radio-style interfacewith current state available in global python variable printed on script exit by associating tkinter variables and unique valuesthoughyou can let tkinter do all this work for youas shown in example - checkbuttonradiobuttonand scale |
5,037 | radio buttonsthe easy way from tkinter import root tk(intvars work too var intvar( select to start for in range( )rad radiobutton(roottext=str( )value=ivariable=varrad pack(side=leftroot mainloop(print(var get()show state on exit this works the same waybut it is lot less to type and debug notice that this script associates the buttons with an intvarthe integer type sibling of stringvarand initializes it to zero (which is also its default)as long as button values are uniqueintegers work fine for radio buttons too hold onto your variablesone minor word of cautionyou should generally hold onto the tkinter variable object used to link radio buttons for as long as the radio buttons are displayed assign it to module global variablestore it in long-lived data structureor save it as an attribute of long-lived class instance object as done by demoradio just make sure you retain reference to it somehow you normally will in order to fetch its state anyhowso it' unlikely that you'll ever care about what ' about to tell you but in the current tkintervariable classes have __del__ destructor that automatically unsets generated tk variable when the python object is reclaimed ( garbage collectedthe upshot is that all of your radio buttons may be deselected if the variable object is collectedat least until the next press resets the tk variable to new value example - shows one way to trigger this example - pp \gui\tour\demo-radio-clear py hold on to your radio variables (an obscure thingindeedfrom tkinter import root tk(def radio ()local vars are temporary #global tmp making it global fixes the problem tmp intvar(for in range( )rad radiobutton(roottext=str( )value=ivariable=tmprad pack(side=lefttmp set( select th button radio (root mainloop( tkinter tourpart |
5,038 | referenced by local tmp is reclaimed on function exitthe tk variable is unsetand the setting is lost (all buttons come up unselectedthese radio buttons work finethoughonce you start pressing thembecause that resets the internal tk variable uncommenting the global statement here makes start out setas expected this phenomenon seems to have grown even worse in python xnot only is " not selected initiallybut moving the mouse cursor over the unselected buttons seems to select many at random until one is pressed (in we also need to initialize string var shared by radio buttons as we did in this section' earlier examplesor else its empty string default selects all of them!of coursethis is an atypical example--as codedthere is no way to know which button is pressedbecause the variable isn' saved (and command isn' setit makes little sense to use group of radio buttons at all if you cannot query its value later in factthis is so obscure that 'll just refer you to demo-radio-clear py in the book' examples distribution for an example that works hard to trigger this oddity in other ways you probably won' carebut you can' say that didn' warn you if you ever do scales (slidersscales (sometimes called "sliders"are used to select among range of numeric values moving the scale' position with mouse drags or clicks moves the widget' value among range of integers and triggers python callbacks if registered like check buttons and radio buttonsscales have both command option for registering an event-driven callback handler to be run right away when the scale is movedand variable option for associating tkinter variable that allows the scale' position to be fetched and set at arbitrary times you can process scale settings when they are madeor let the user pick setting for later use in additionscales have third processing option--get and set methods that scripts may call to access scale values directly without associating variables because scale command movement callbacks also get the current scale setting value as an argumentit' often enough just to provide callback for this widgetwithout resorting to either linked variables or get/set method calls to illustrate the basicsexample - makes two scales--one horizontal and one vertical--and links them with an associated variable to keep them in sync example - pp \gui\tour\demoscale py "create two linked scales used to launch dialog demosfrom tkinter import from dialogtable import demos from quitter import quitter get base widget set button callback handlers attach quit frame to me checkbuttonradiobuttonand scale |
5,039 | def __init__(selfparent=none**options)frame __init__(selfparent**optionsself pack(label(selftext="scale demos"pack(self var intvar(scale(selflabel='pick demo number'command=self onmovecatch moves variable=self varreflects position from_= to=len(demos)- pack(scale(selflabel='pick demo number'command=self onmovecatch moves variable=self varreflects position from_= to=len(demos)- length= tickinterval= showvalue=yesorient='horizontal'pack(quitter(selfpack(side=rightbutton(selftext="run demo"command=self onrunpack(side=leftbutton(selftext="state"command=self reportpack(side=rightdef onmove(selfvalue)print('in onmove'valuedef onrun(self)pos self var get(print('you picked'posdemo list(demos values())[posprint(demo()map from position to value ( viewor demoslist(demos keys())[pos](def report(self)print(self var get()if __name__ ='__main__'print(list(demos keys())demo(mainloop(besides value access and callback registrationscales have options tailored to the notion of range of selectable valuesmost of which are demonstrated in this example' codethe label option provides text that appears along with the scalelength specifies an initial size in pixelsand orient specifies an axis the from_ and to options set the scale range' minimum and maximum values (note that from is python reserved wordbut from_ is notthe tickinterval option sets the number of units between marks drawn at regular intervals next to the scale (the default means no marks are drawnthe resolution option provides the number of units that the scale' value jumps on each drag or left mouse click event (defaults to the showvalue option can be used to show or hide the scale' current value next to its slider bar (the default showvalue=yes means it is drawn tkinter tourpart |
5,040 | see how these ideas translate in practicefigure - shows the window you get if you run this script live on windows (you get similar one on unix and mac machinesfigure - demoscale in action for illustration purposesthis window' state button shows the scalescurrent valuesand "run demoruns standard dialog call as beforeusing the integer value of the scales to index the demos table the script also registers command handler that fires every time either of the scales is moved and prints their new positions here is set of messages sent to stdout after few movesdemo runs (italic)and state requests (bold) :\pp \gui\tourpython demoscale py ['color''query''input''open''error'in onmove in onmove in onmove in onmove you picked in onmove you picked :/users/mark/stuff/books/ /pp /dev/examples/pp /launcher py scales and variables as you can probably tellscales offer variety of ways to process their selectionsimmediately in move callbacksor later by fetching current positions with variables or scale method calls in facttkinter variables aren' needed to program scales at all-checkbuttonradiobuttonand scale |
5,041 | on demandas in the simpler scale example in example - example - pp \gui\tour\demo-scale-simple py from tkinter import root tk(scl scale(rootfrom_=- to= tickinterval= resolution= scl pack(expand=yesfill=ydef report()print(scl get()button(roottext='state'command=reportpack(side=rightroot mainloop(figure - shows two instances of this program running on windows--one stretched and one not (the scales are packed to grow vertically on resizesits scale displays range from - to uses the resolution option to adjust the current position up or down by on every moveand sets the tickinterval option to show values next to the scale in increments of when you press the state button in this script' windowit calls the scale' get method to display the current settingwithout variables or callbacks of any kindc:\pp \gui\tourpython demo-scale-simple py - figure - simple scale without variables franklythe only reason tkinter variables are used in the demoscale script at all is to synchronize scales to make the demo interestingthis script associates the same tkinter tkinter tourpart |
5,042 | changes its variablebut changing variable also changes all the widgets it is associated with in the world of slidersmoving the slide updates that variablewhich in turn might update other widgets associated with the same variable because this script links one variable with two scalesit keeps them automatically in syncmoving one scale moves the othertoobecause the shared variable is changed in the process and so updates the other scale as side effect linking scales like this may or may not be typical of your applications (and borders on deep magic)but it' powerful tool once you get your mind around it by linking multiple widgets on display with tkinter variablesyou can keep them automatically in syncwithout making manual adjustments in callback handlers on the other handthe synchronization could be implemented without shared variable at all by calling one scale' set method from move callback handler of the other 'll leave such manual mutation as suggested exercisethough one person' deep magic might be another' useful hack running gui code three ways now that we've built handful of similar demo launcher programslet' write few top-level scripts to combine them because the demos were coded as both reusable classes and scriptsthey can be deployed as attached frame componentsrun in their own top-level windowsand launched as standalone programs all three options illustrate code reuse in action attaching frames to illustrate hierarchical gui composition on grander scale than we've seen so farexample - arranges to show all four of the dialog launcher bar scripts of this in single container it reuses examples - - - and - example - pp \gui\tour\demoall-frm py "" demo class components (subframeson one windowthere are quitter buttons on this one window tooand each kills entire guiguis can be reused as frames in containerindependent windowsor processes""from tkinter import from quitter import quitter demomodules ['demodlg''democheck''demoradio''demoscale'parts [def addcomponents(root)for demo in demomodulesmodule __import__(demopart module demo(rootimport by name string attach an instance running gui code three ways |
5,043 | part pack(side=leftexpand=yesfill=bothparts append(partdef dumpstate()for part in partsprint(part __module__ ':'end='if hasattr(part'report')part report(elseprint('none'or pass configs to demo(growstretch with window change list in-place run demo report if any root tk(make explicit root first root title('frames'label(roottext='multiple frame demo'bg='white'pack(button(roottext='states'command=dumpstatepack(fill=xquitter(rootpack(fill=xaddcomponents(rootroot mainloop(because all four demo launcher bars are coded as frames which attach themselves to parent container widgetsthis is easier than you might thinksimply pass the same parent widget (herethe root windowto all four demo constructor callsand repack and configure the demo objects as desired figure - shows this script' graphical result-- single window embedding instances of all four of the dialog demo launcher demos we saw earlier as codedall four embedded demos grow and stretch with the window when resized (try taking out the expand=yes to keep their sizes more constantfigure - demoall_frmnested subframes naturallythis example is artificialbut it illustrates the power of composition when applied to building larger gui displays if you pretend that each of the four attached tkinter tourpart |
5,044 | better appreciate the point of this example besides demo object framesthis composite window also contains no fewer than five instances of the quitter button we wrote earlier (all of which verify the request and any one of which can end the guiand states button to dump the current values of all the embedded demo objects at once (it calls each object' report methodif it has onehere is sample of the sort of output that shows up in the stdout stream after interacting with widgets on this displaystates output is in boldc:\pp \gui\tourpython demoall_frm py in onmove in onmove demodlgnone democheck demoradioerror demoscale you pressed input result in onmove demodlgnone democheck demoradioinput demoscale you pressed query resultyes in onmove you picked none in onmove you picked :/users/mark/stuff/books/ /pp /dev/examples/pp /launcher py query demodlgnone democheck demoradioquery demoscale importing by name string the only substantially tricky part of this script is its use of python' built-in __import__ function to import module by name string look at the following two lines from the script' addcomponents functionmodule __import__(demopart module demo(rootimport module by name string attach an instance of its demo this is equivalent to saying something like thisimport 'demodlgpart 'demodlgdemo(rootrunning gui code three ways |
5,045 | statements and dot expressions must be python variablenot stringmoreoverin an import the name is taken literally (not evaluated)and in dot syntax must evaluate to the object (not its string nameto be genericaddcomponents steps through list of name strings and relies on __import__ to import and return the module identified by each string in factthe for loop containing these statements works as though all of these statements were runimport demodlgdemoradiodemocheckdemoscale part demodlg demo(rootpart demoradio demo(rootpart democheck demo(rootpart demoscale demo(rootbut because the script uses list of name stringsit' easier to change the set of demos embedded--simply change the listnot the lines of executable code furthersuch datadriven code tends to be more compactless redundantand easier to debug and maintain incidentallymodules can also be imported from name strings by dynamically constructing and running import statementslike thisfor demo in demomodulesexec('from % import demodemopart eval('demo')(rootmake and run from fetch known import name by string the exec statement compiles and runs python statement string (herea from to load module' demo class)it works here as if the statement string were pasted into the source code where the exec statement appears the following achieves the same effect by running an import statement insteadfor demo in demomodulesexec('import %sdemopart eval(demodemo(rootmake and run an import fetch module variable by name too because it supports any sort of python statementthese exec/eval techniques are more general than the __import__ callbut can also be slowersince they must parse code strings before running them howeverthat slowness may not matter in guiusers tend to be significantly slower than parsers configuring at construction time one other alternative worth mentioningnotice how example - configures and repacks each attached demo frame for its role in this guidef addcomponents(root)for demo in demomodulesmodule __import__(demopart module demo(rootimport by name string attach an instance as we'll see later in this bookexec can also be dangerous if it is running code strings fetched from users or network connections that' not an issue for the hardcoded strings used internally in this example tkinter tourpart |
5,046 | part pack(side=leftexpand=yesfill=bothor pass configs to demo(growstretch with window because the demo classes use their **options arguments to support constructor argumentsthoughwe could configure at creation timetoo for exampleif we change this code as followsit produces the slightly different composite window captured in figure - (stretched bit horizontally for illustrationtooyou can run this as demoall-frm-ridge py in the examples package)def addcomponents(root)for demo in demomodulesmodule __import__(demopart module demo(rootbd= relief=ridgepart pack(side=leftexpand=yesfill=bothimport by name string attachconfig instance growstretch with window because the demo classes both subclass frame and support the usual construction argument protocolsthey become true widgets--specialized tkinter frames that implement an attachable package of widgets and support flexible configuration techniques figure - demoall_frmconfigure when constructed as we saw in attaching nested frames like this is really just one way to reuse gui code structured as classes it' just as easy to customize such interfaces by subclassing rather than embedding herethoughwe're more interested in deploying an existing widget package than changing itso attachment is the pattern we want the next two sections show two other ways to present such precoded widget packages to users--in pop-up windows and as autonomous programs running gui code three ways |
5,047 | once you have set of component classes coded as framesany parent will work-both other frames and brand-newtop-level windows example - attaches instances of all four demo bar objects to their own independent toplevel windowsinstead of the same container example - pp \gui\tour\demoall-win py "" demo classes in independent top-level windowsnot processeswhen one is quit all others go awaybecause all windows run in the same process heremake tk(first hereelse we get blank default window ""from tkinter import demomodules ['demodlg''demoradio''democheck''demoscale'def makepopups(modnames)demoobjects [for modname in modnamesmodule __import__(modnamewindow toplevel(demo module demo(windowwindow title(module __name__demoobjects append(demoreturn demoobjects import by name string make new window parent is the new window def allstates(demoobjects)for obj in demoobjectsif hasattr(obj'report')print(obj __module__end='obj report(root tk(make explicit root first root title('popups'demos makepopups(demomoduleslabel(roottext='multiple toplevel window demo'bg='white'pack(button(roottext='states'command=lambdaallstates(demos)pack(fill=xroot mainloop(we met the toplevel class earlierevery instance generates new window on your screen the net result is captured in figure - each demo runs in an independent window of its own instead of being packed together in single display tkinter tourpart |
5,048 | the main root window of this program appears in the lower left of this screenshotit provides states button that runs the report method of each demo objectproducing this sort of stdout textc:\pp \gui\tourpython demoall_win py in onmove in onmove in onmove you pressed open resultc:/users/mark/stuff/books/ /pp /dev/examples/pp /launcher py demoradio open democheck demoscale as we learned earlier in this toplevel windows function independentlybut they are not really independent programs destroying just one of the demo windows in figure - by clicking the button in its upper right corner closes just that window but quitting any of the windows shown in figure - --by demo window' quit buttons or the main window' --quits them all and ends the applicationbecause all run in the same program process that' ok in some applicationsbut not all to go truly rogue we need to spawn processesas the next section shows running gui code three ways |
5,049 | to be more independentexample - spawns each of the four demo launchers as independent programs (processes)using the launchmodes module we wrote at the end of this works only because the demos were written as both importable classes and runnable scripts launching them here makes all their names __main__ when runbecause they are separatestand-alone programsthis in turn kicks off the main loop call at the bottom of each of their files example - pp \gui\tour\demoall-prg py "" demo classes run as independent program processescommand linesif one window is quit nowthe others will live onthere is no simple way to run all report calls here (though sockets and pipes could be used for ipc)and some launch schemes may drop child program stdout and disconnect parent/child""from tkinter import from pp launchmodes import portablelauncher demomodules ['demodlg''demoradio''democheck''demoscale'for demo in demomodulesportablelauncher(demodemo py')(see parallel system tools start as top-level programs root tk(root title('processes'label(roottext='multiple program democommand lines'bg='white'pack(root mainloop(make sure the pp directory' container is on your module search path ( pythonpathto run thisit imports an example module from different directory as figure - showsthe display generated by this script is similar to the prior oneall four demos come up in windows of their own this timethoughthese are truly independent programsif any one of the five windows here is quitthe others live on the demos even outlive their parentif the main window is closed on windowsin factthe shell window where this script is started becomes active again when the main window is closedeven though the spawned demos continue running we're reusing the demo code as programnot module tkinter tourpart |
5,050 | launching guis as programs other waysmultiprocessing if you backtrack to to study the portable launcher module used by example - to start programsyou'll see that it works by using os spawnv on windows and os fork/exec on others the net effect is that the gui processes are effectively started by launching command lines these techniques work wellbut as we learned in they are members of larger set of program launching tools that also includes os popenos systemos startfileand the subprocess and multiprocessing modulesthese tools can vary subtly in how they handle shell window connectionsparent process exitsand more for examplethe multiprocessing module we studied in provides similarly portable way to run our guis as independent processesas demonstrated in example - when runit produces the exact same windows shown in figure - except that the label in the main window is different example - pp \gui\tour\demoall-prg-multi py "" demo classes run as independent program processesmultiprocessingmultiprocessing allows us to launch named functions with argumentsbut not lambdasbecause they are not pickleable on windows ()multiprocessing also has its own ipc tools like pipes for communication""running gui code three ways |
5,051 | from multiprocessing import process demomodules ['demodlg''demoradio''democheck''demoscale'def rundemo(modname)module __import__(modnamemodule demo(mainloop(run in new process build gui from scratch if __name__ ='__main__'for modname in demomodulesprocess(target=rundemoargs=(modname,)start(in __main__ onlyroot tk(parent process gui root title('processes'label(roottext='multiple program demomultiprocessing'bg='white'pack(root mainloop(operationallythis version differs on windows only in thatthe child processesstandard output shows up in the window where the script was launchedincluding the outputs of both dialog demos themselves and all demo windowsstate buttons the script doesn' truly exit if any children are still runningthe shell where it is launched is blocked if the main process' window is closed while children are still runningunless we set the child processesdaemon flag to true before they start as we saw in --in which case all child programs are automatically shut down when their parent is (but parents may still outlive their childrenalso observe how we start simple named function in the new process as we learned in the target must be pickleable on windows (which essentially means importable)so we cannot use lambdas to pass extra data in the way we typically could in tkinter callbacks the following coding alternatives both fail with errors on windowsprocess(target=(lambdarundemo(modname))start(these both failprocess(target=(lambda__import__(modnamedemo(mainloop())start(we won' recode our gui program launcher script with any of the other techniques availablebut feel free to experiment on your own using as resource although not universally applicablethe whole point of tools like the portablelauncher class is to hide such details so we can largely forget them cross-program communication spawning guis as programs is the ultimate in code independencebut it makes the lines of communication between components more complex for instancebecause the demos run as programs herethere is no easy way to run all their report methods from the launching script' window pictured in the upper right of figure - in factthe tkinter tourpart |
5,052 | as the demos start up in example - :\pp \gui\tourpython demoall_prg py demodlg demoradio democheck demoscale on some platformsmessages printed by the demo programs (including their own state buttonsmay show up in the original console window where this script is launchedon windowsthe os spawnv call used to start programs by launchmodes in example - completely disconnects the child program' stdout stream from its parentbut the multiprocessing scheme of example - does not regardlessthere is no direct way to call all demosreport methods at once--they are spawned programs in distinct address spacesnot imported modules of coursewe could trigger report methods in the spawned programs with some of the inter-process communication (ipcmechanisms we met in for instancethe demos could be instrumented to catch user signaland could run their report in response the demos could also watch for request strings sent by the launching program to show up in pipes or fifosthe demoall launching program would essentially act as clientand the demo guis as servers that respond to client requests independent programs can also converse this same way over socketsthe general ipc tool introduced in which we'll study in depth in part iv the main window might send report request and receive its result on the same socket (and might even contact demos running remotelyif usedthe multiprocessing module has ipc tools all its ownsuch as the object pipes and queues we studied in that could also be leverageddemos might listen on this type of pipetoo given their event-driven naturegui-based programs like our demos also need to avoid becoming stuck in wait states--they cannot be blocked while waiting for requests on ipc devices like those aboveor they won' be responsive to users (and might not even redraw themselvesbecause of thatthey may also have be augmented with threadstimer-event callbacksnonblocking input callsor some combination of such techniques to periodically check for incoming messages on pipesfifosor sockets as we'll seethe tkinter after method call described near the end of the next is ideal for thisit allows us to register callback to run periodically to check for incoming requests on such ipc tools we'll explore some of these options near the end of after we've looked at gui threading topics but since this is well beyond the scope of the current simple demo programsi'll leave such cross-program extensions up to more parallelminded readers for now running gui code three ways |
5,053 | postscripti coded the demo launcher bars deployed by the last four examples to demonstrate all the different ways that their widgets can be used they were not developed with general-purpose reusability in mindin factthey're not really useful outside the context of introducing widgets in this book that was by designmost tkinter widgets are easy to use once you learn their interfacesand tkinter already provides lots of configuration flexibility by itself but if had it in mind to code checkbutton and radiobutton classes to be reused as general library componentsthey would have to be structured differentlyextra widgets they would not display anything but radio buttons and check buttons as isthe demos each embed state and quit buttons for illustrationbut there really should be just one quit per top-level window geometry management they would allow for different button arrangements and would not pack (or gridthemselves at all in true general-purpose reuse scenarioit' often better to leave component' geometry management up to its caller usage mode limitations they would either have to export complex interfaces to support all possible tkinter configuration options and modesor make some limiting decisions that support one common use only for instancethese buttons can either run callbacks at press time or provide their state later in the application example - shows one way to code check button and radio button bars as library components it encapsulates the notion of associating tkinter variables and imposes common usage mode on callers--state fetches rather than press callbacks--to keep the interface simple example - pp \gui\tour\buttonbars py ""check and radio button bar classes for apps that fetch state laterpass list of optionscall state()variable details automated ""from tkinter import class checkbar(frame)def __init__(selfparent=nonepicks=[]side=leftanchor= )frame __init__(selfparentself vars [for pick in picksvar intvar(chk checkbutton(selftext=pickvariable=varchk pack(side=sideanchor=anchorexpand=yesself vars append(vardef state(self) tkinter tourpart |
5,054 | class radiobar(frame)def __init__(selfparent=nonepicks=[]side=leftanchor= )frame __init__(selfparentself var stringvar(self var set(picks[ ]for pick in picksrad radiobutton(selftext=pickvalue=pickvariable=self varrad pack(side=sideanchor=anchorexpand=yesdef state(self)return self var get(if __name__ ='__main__'root tk(lng checkbar(root['python'' #''java'' ++']gui radiobar(root['win'' ''mac']side=topanchor=nwtgl checkbar(root['all']gui pack(side=leftfill=ylng pack(side=topfill=xtgl pack(side=leftlng config(relief=groovebd= gui config(relief=ridgebd= def allstates()print(gui state()lng state()tgl state()from quitter import quitter quitter(rootpack(side=rightbutton(roottext='peek'command=allstatespack(side=rightroot mainloop(to reuse these classes in your scriptsimport and call them with list of the options that you want to appear in bar of check buttons or radio buttons this module' selftest code at the bottom of the file gives further usage details it generates figure - - top-level window that embeds two checkbarsone radiobara quitter button to exitand peek button to show bar states--when this file is run as program instead of being imported figure - buttonbars self-test window running gui code three ways |
5,055 | methodsx [ [ win [ [ the two classes in this module demonstrate how easy it is to wrap tkinter interfaces to make them easier to usethey completely abstract away many of the tricky parts of radio button and check button bars for instanceyou can forget about linked variable details completely if you use such higher-level classes instead--simply make objects with option lists and call their state methods later if you follow this path to its logical conclusionyou might just wind up with higher-level widget library on the order of the pmw package mentioned in on the other handthese classes are still not universally applicableif you need to run actions when these buttons are pressedfor instanceyou'll need to use other high-level interfaces luckilypython/tkinter already provides plenty later in this bookwe'll again use the widget combination and reuse techniques introduced in this section to construct larger guis like text editorsemail clients and calculators for nowthis first in the widget tour is about to make one last stop--the photo shop images in tkintergraphical images are displayed by creating independent photoimage or bitmapimage objectsand then attaching those image objects to other widgets via image attribute settings buttonslabelscanvasestextand menus can display images by associating prebuilt image objects in this way to illustrateexample - throws picture up on button example - pp \gui\tour\imgbutton py gifdir /gifs/from tkinter import win tk(igm photoimage(file=gifdir "ora-pp gif"button(winimage=igmpack(win mainloop( could try to come up with simpler examplebut it would be tough--all this script does is make tkinter photoimage object for gif file stored in another directoryand associate it with button widget' image option the result is captured in figure - tkinter tourpart |
5,056 | photoimage and its cousinbitmapimageessentially load graphics files and allow those graphics to be attached to other kinds of widgets to open picture filepass its name to the file attribute of these image objects though simpleattaching images to buttons this way has many usesin for instancewe'll use this basic idea to implement toolbar buttons at the bottom of window canvas widgets--general drawing surfaces covered in more detail in the next can display pictures too though this is bit of preview for the upcoming basic canvas usage is straightforward enough to demonstrate hereexample - renders figure - (shrunk here for display)example - pp \gui\tour\imgcanvas py gifdir /gifs/from tkinter import win tk(img photoimage(file=gifdir "ora-lp gif"can canvas(wincan pack(fill=bothcan create_image( image=imganchor=nwwin mainloop(xy coordinates buttons are automatically sized to fit an associated photobut canvases are not (because you can add objects to canvas lateras we'll see in to make canvas fit the picturesize it according to the width and height methods of image objectsas in example - this version will make the canvas smaller or larger than its default size as neededlets you pass in photo file' name on the command lineand can be used as simple image viewer utility the visual effect of this script is captured in figure - images |
5,057 | figure - sizing the canvas to match the photo example - pp \gui\tour\imgcanvas py gifdir /gifs/from sys import argv from tkinter import filename argv[ if len(argv else 'ora-lp gifwin tk(img photoimage(file=gifdir filenamecan canvas(wincan pack(fill=bothcan config(width=img width()height=img height()can create_image( image=imganchor=nwwin mainloop( tkinter tourpart name on cmdlinesize to img size |
5,058 | :\pp \gui\tourimgcanvas py ora-ppr-german gif and that' all there is to it in we'll see images show up again in the items of menuin the buttons of window' toolbarin other canvas examplesand in the image-friendly text widget in later we'll find them in an image slideshow (pyview)in paint program (pydraw)on clocks (pyclock)in generalized photo viewer (pyphoto)and so on it' easy to add graphics to guis in python/tkinter once you start using photos in earnestthoughyou're likely to run into two tricky bits that want to warn you about heresupported file types at presentthe standard tkinter photoimage widget supports only gifppmand pgm graphic file formatsand bitmapimage supports windows-style xbm bitmap files this may be expanded in future releasesand you can convert photos in other formats to these supported formats ahead of timeof course but as we'll see later in this it' easy to support additional image types with the pil open source extension toolkit and its photoimage replacement hold on to your imagesunlike all other tkinter widgetsan image is utterly lost if the corresponding python image object is garbage collected that means you must retain an explicit reference to image objects for as long as your program needs them ( assign them to long-lived variable nameobject attributeor data structure componentpython does not automatically keep reference to the imageeven if it is linked to other gui components for display moreoverimage destructor methods erase the image from memory we saw earlier that tkinter variables can behave oddly when reclaimedtoo (they may be unset)but the effect is much worse and more likely to happen with images this may change in future python releasesthough there are good reasons for not retaining big image files in memory indefinitelyfor nowthoughimages are "use it or lose itwidget fun with buttons and pictures tried to come up with an image demo for this section that was both fun and useful settled for the fun part example - displays button that changes its image at random each time it is pressed example - pp \gui\tour\buttonpics-func py from tkinter import from glob import glob import democheck import random gifdir /gifs/get base widget set filename expansion list attach checkbutton demo to me pick picture at random where to look for gif files images |
5,059 | namephoto random choice(imageslbl config(text=namepix config(image=photoroot=tk(lbl label(roottext="none"bg='blue'fg='red'pix button(roottext="press me"command=drawbg='white'lbl pack(fill=bothpix pack(pady= democheck demo(rootrelief=sunkenbd= pack(fill=bothfiles glob(gifdir "gif"images [(xphotoimage(file= )for in filesprint(filesroot mainloop(gifs for now load and hold this code uses handful of built-in tools from the python librarythe python glob module we first met in gives list of all files ending in gif in directoryin other wordsall gif files stored there the python random module is used to select random gif from files in the directoryrandom choice picks and returns an item from list at random to change the image displayed (and the gif file' name in label at the top of the window)the script simply calls the widget config method with new option settingschanging on the fly like this changes the widget' display dynamically just for funthis script also attaches an instance of the democheck check button demo bar from example - which in turn attaches an instance of the quitter button we wrote earlier in example - this is an artificial exampleof coursebut it again demonstrates the power of component class attachment at work notice how this script builds and holds on to all images in its images list the list comprehension here applies photoimage constructor call to every gif file in the photo directoryproducing list of (filenameimageobjecttuples that is saved in global variable ( map call using one-argument lambda function could do the samerememberthis guarantees that image objects won' be garbage collected as long as the program is running figure - shows this script in action on windows although it may not be obvious in this grayscale bookthe name of the gif file being displayed is shown in red text in the blue label at the top of this window this program' window grows and shrinks automatically when larger and smaller gif files are displayedfigure - shows it randomly picking taller photo globbed from the image directory tkinter tourpart |
5,060 | figure - buttonpics showing taller photo images |
5,061 | selected completely at random from the photo file directory +figure - buttonpics gets political while we're playinglet' recode this script as class in case we ever want to attach or customize it later (it could happenespecially in more realistic programsit' mostly matter of indenting and adding self before global variable namesas shown in example - example - pp \gui\tour\buttonpics py from tkinter import from glob import glob import democheck import random gifdir /gifs/get base widget set filename expansion list attach check button example to me pick picture at random default dir to load gif files class buttonpicsdemo(frame)def __init__(selfgifdir=gifdirparent=none)frame __init__(selfparentself pack(self lbl label(selftext="none"bg='blue'fg='red'self pix button(selftext="press me"command=self drawbg='white'self lbl pack(fill=bothself pix pack(pady= democheck demo(selfrelief=sunkenbd= pack(fill=bothfiles glob(gifdir "gif"self images [(xphotoimage(file= )for in filesprint(filesdef draw(self)namephoto random choice(self images+this particular image is not my creationit appeared as banner ad on developer-related websites such as slashdot when the book learning python was first published in it generated enough of backlash from perl zealots that 'reilly eventually pulled the ad altogether which may be whyof courseit later appeared in this book tkinter tourpart |
5,062 | self pix config(image=photoif __name__ ='__main__'buttonpicsdemo(mainloop(this version works the same way as the originalbut it can now be attached to any other gui where you would like to include such an unreasonably silly button viewing and processing images with pil as mentioned earlierpython tkinter scripts show images by associating independently created image objects with real widget objects at this writingtkinter guis can display photo image files in gifppmand pgm formats by creating photoimage objectas well as -style bitmap files (usually suffixed with an xbm extensionby creating bitmapimage object this set of supported file formats is limited by the underlying tk librarynot by tkinter itselfand may expand in the future (it has not in many yearsbut if you want to display files in other formats today ( the popular jpeg format)you can either convert your files to one of the supported formats with an image-processing program or install the pil python extension package mentioned at the start of pilthe python imaging libraryis an open source system that supports nearly graphics file formats (including gifjpegtiffpngand bmpin addition to allowing your scripts to display much wider variety of image types than standard tkinterpil also provides tools for image processingincluding geometric transformsthumbnail creationformat conversionsand much more pil basics to use its toolsyou must first fetch and install the pil packagesee thonware com (or search for "pilon the webthensimply use special photoimage and bitmapimage objects imported from the pil imagetk module to open files in other graphic formats these are compatible replacements for the standard tkinter classes of the same nameand they may be used anywhere tkinter expects photoimage or bitmapimage object ( in labelbuttoncanvastextand menu object configurationsthat isreplace standard tkinter code such as thisfrom tkinter import imgobj photoimage(file=imgdir "spam gif"button(image=imgobjpack(viewing and processing images with pil |
5,063 | from tkinter import from pil import imagetk photoimg imagetk photoimage(file=imgdir "spam jpg"button(image=photoimgpack(or with the more verbose equivalentwhich comes in handy if you will perform image processing in addition to image displayfrom tkinter import from pil import imageimagetk imageobj image open(imgdir "spam jpeg"photoimg imagetk photoimage(imageobjbutton(image=photoimgpack(in factto use pil for image displayall you really need to do is install it and add single from statement to your code to get its replacement photoimage object after loading the original from tkinter the rest of your code remains unchanged but will be able to display jpegpngand other image typesfrom tkinter import from pil imagetk import photoimage imgobj photoimage(file=imgdir "spam png"button(image=imgobjpack(<=add this line pil installation details vary per platformon windowsit is just matter of downloading and running self-installer pil code winds up in the python install directory' lib\site-packagesbecause this is automatically added to the module import search pathno path configuration is required to use pil simply run the installer and import the pil package' modules on other platformsyou might untar or unzip fetched source code archive and add pil directories to the front of your pythonpath settingsee the pil system' website for more details (in facti am using pre-release version of pil for python in this editionit should be officially released by the time you read these words there is much more to pil than we have space to cover here for instanceit also provides image conversionresizingand transformation toolssome of which can be run as command-line programs that have nothing to do with guis directly especially for tkinter-based programs that display or process imagespil will likely become standard component in your software tool set see documentation sets to help get you startedthoughwe'll close out this with handful of real scripts that use pil for image display and processing tkinter tourpart |
5,064 | in our earlier image exampleswe attached widgets to buttons and canvasesbut the standard tkinter toolkit allows images to be added to variety of widget typesincluding simple labelstextand menu entries example - for instanceuses unadorned tkinter to display single image by attaching it to labelin the main application window the example assumes that images are stored in an images subdirectoryand it allows the image filename to be passed in as command-line argument (it defaults to spam gif if no argument is passedit also joins file and directory names more portably with os path joinand it prints the image' height and width in pixels to the standard output streamjust to give extra information example - pp \gui\pil\viewer-tk py ""show one image with standard tkinter photo objectas is this handles gif filesbut not jpeg imagesimage filename listed in command lineor defaultuse canvas instead of label for scrollingetc ""import ossys from tkinter import imgdir 'imagesimgfile 'london- gifif len(sys argv imgfile sys argv[ imgpath os path join(imgdirimgfilewin tk(win title(imgfileimgobj photoimage(file=imgpathlabel(winimage=imgobjpack(print(imgobj width()imgobj height()win mainloop(use standard tkinter photo object gif worksbut jpeg requires pil cmdline argument givendisplay photo on label show size in pixels before destroyed figure - captures this script' display on windows showing the default gif image file run this from the system console with filename as command-line argument to view other files in the images subdirectory ( python viewer_tk py filename gifviewing and processing images with pil |
5,065 | example - worksbut only for image types supported by the base tkinter toolkit to display other image formatssuch as jpegwe need to install pil and use its replacement photoimage object in terms of codeit' simply matter of adding one import statementas illustrated in example - example - pp \gui\pil\viewer-pil py ""show one image with pil photo replacement object handles many more image typesinstall pil firstplaced in lib\site-packages ""import ossys from tkinter import from pil imagetk import photoimage imgdir 'imagesimgfile 'florida- - jpgif len(sys argv imgfile sys argv[ imgpath os path join(imgdirimgfilewin tk(win title(imgfileimgobj photoimage(file=imgpathlabel(winimage=imgobjpack( tkinter tourpart <=use pil replacement class rest of code unchanged does gifjpgpngtiffetc now jpegs work |
5,066 | print(imgobj width()imgobj height()show size in pixels on exit with pilour script is now able to display many image typesincluding the default jpeg image defined in the script and captured in figure - againrun with command-line argument to view other photos figure - tkinter+pil jpeg display displaying all images in directory while we're at itit' not much extra work to allow viewing all images in directoryusing some of the directory path tools we met in the first part of this book example - for instancesimply opens new toplevel pop-up window for each image in directory (given as command-line argument or default)taking care to skip nonimage files by catching exceptions--error messages are both printed and displayed in the bad file' pop-up window example - pp \gui\pil\viewer-dir py ""display all images in directory in pop-up windows gifs work in basic tkinterbut jpegs will be skipped without pil ""viewing and processing images with pil |
5,067 | from tkinter import from pil imagetk import photoimage <=required for jpegs and others imgdir 'imagesif len(sys argv imgdir sys argv[ imgfiles os listdir(imgdirdoes not include directory prefix main tk(main title('viewer'quit button(maintext='quit all'command=main quitfont=('courier' )quit pack(savephotos [for imgfile in imgfilesimgpath os path join(imgdirimgfilewin toplevel(win title(imgfiletryimgobj photoimage(file=imgpathlabel(winimage=imgobjpack(print(imgpathimgobj width()imgobj height()size in pixels savephotos append(imgobjkeep reference excepterrmsg 'skipping % \ % (imgfilesys exc_info()[ ]label(wintext=errmsgpack(main mainloop(run this code on your own to see the windows it generates if you doyou'll get one main window with quit button to kill all the windows at onceplus as many pop-up image view windows as there are images in the directory this is convenient for quick lookbut not exactly the epitome of user friendliness for large directoriesthe sample images directory used for testingfor instancehas imagesyielding pop-up windowsthose created by your digital camera may have many more to do betterlet' move on to the next section creating image thumbnails with pil as mentionedpil does more than display images in guiit also comes with tools for resizingconvertingand more one of the many useful tools it provides is the ability to generate small"thumbnailimages from originals such thumbnails may be displayed in web page or selection gui to allow the user to open full-size images on demand example - is concrete implementation of this idea--it generates thumbnail images using pil and displays them on buttons which open the corresponding original image when clicked the net effect is much like the file explorer guis that are now standard on modern operating systemsbut by coding this in pythonwe're able to control its behavior and to reuse and customize its code in our own applications in factwe'll tkinter tourpart |
5,068 | some of the primary benefits inherent in open source software in general example - pp \gui\pil\viewer_thumbs py ""display all images in directory as thumbnail image buttons that display the full image when clickedrequires pil for jpegs and thumbnail image creationto doadd scrolling if too many thumbs for window""import ossysmath from tkinter import from pil import image from pil imagetk import photoimage <=required for thumbs <=required for jpeg display def makethumbs(imgdirsize=( )subdir='thumbs')""get thumbnail images for all images in directoryfor each imagecreate and save new thumbor load and return an existing thumbmakes thumb dir if neededreturns list of (image filenamethumb image object)caller can also run listdir on thumb dir to loadon bad file types may raise ioerroror othercaveatcould also check file timestamps""thumbdir os path join(imgdirsubdirif not os path exists(thumbdir)os mkdir(thumbdirthumbs [for imgfile in os listdir(imgdir)thumbpath os path join(thumbdirimgfileif os path exists(thumbpath)thumbobj image open(thumbpathuse already created thumbs append((imgfilethumbobj)elseprint('making'thumbpathimgpath os path join(imgdirimgfiletryimgobj image open(imgpathmake new thumb imgobj thumbnail(sizeimage antialiasbest downsize filter imgobj save(thumbpathtype via ext or passed thumbs append((imgfileimgobj)exceptnot always ioerror print("skipping"imgpathreturn thumbs class viewone(toplevel)""open single image in pop-up window when createdphotoimage object must be savedimages are erased if object is reclaimed""def __init__(selfimgdirimgfile)toplevel __init__(selfself title(imgfileimgpath os path join(imgdirimgfileviewing and processing images with pil |
5,069 | label(selfimage=imgobjpack(print(imgpathimgobj width()imgobj height()self savephoto imgobj size in pixels keep reference on me def viewer(imgdirkind=toplevelcols=none)""make thumb links window for an image directoryone thumb button per imageuse kind=tk to show in main app windowor frame container (pack)imgfile differs per loopmust save with defaultphotoimage objs must be savederased if reclaimedpacked row frames (versus gridsfixed-sizescanvas)""win kind(win title('viewerimgdirquit button(wintext='quit'command=win quitbg='beige'pack first quit pack(fill=xside=bottomso clip last thumbs makethumbs(imgdirif not colscols int(math ceil(math sqrt(len(thumbs)))fixed or savephotos [while thumbsthumbsrowthumbs thumbs[:cols]thumbs[cols:row frame(winrow pack(fill=bothfor (imgfileimgobjin thumbsrowphoto photoimage(imgobjlink button(rowimage=photohandler lambda savefile=imgfileviewone(imgdirsavefilelink config(command=handlerlink pack(side=leftexpand=yessavephotos append(photoreturn winsavephotos if __name__ ='__main__'imgdir (len(sys argv and sys argv[ ]or 'imagesmainsave viewer(imgdirkind=tkmain mainloop(notice how this code' viewer must pass in the imgfile to the generated callback handler with default argumentbecause imgfile is loop variableall callbacks will have its final loop iteration value if its current value is not saved this way (all buttons would open the same image!also notice we keep list of references to the photo image objectsphotos are erased when their object is garbage collectedeven if they are currently being displayed to avoid thiswe generate references in long-lived list figure - shows the main thumbnail selection window generated by example - when viewing the default images subdirectory in the examples source tree (resized here for displayas in the previous examplesyou can pass in an optional directory name to run the viewer on directory of your own (for instanceone copied from your digital cameraclicking thumbnail button in the main window opens corresponding image in pop-up windowfigure - captures one tkinter tourpart |
5,070 | figure - thumbnail viewer pop-up image window viewing and processing images with pil |
5,071 | buttons in row framesmuch like prior examples (see the input forms layout alternatives earlier in this most of the pil-specific code in this example is in the make thumbs function it openscreatesand saves the thumbnail imageunless one has already been saved ( cachedto local file as codedthumbnail images are saved in the same image format as the original full-size photo we also use the pil antialias filter--the best quality for down-sampling (shrinking)this does better job on low-resolution gifs thumbnail generation is essentially just an in-place resize that preserves the original aspect ratio because there is more to this story than we can cover herethoughi'll defer to pil and its documentation for more details on that package' api we'll revisit thumbnail creation again briefly in the next to create toolbar buttons before we move onthoughthree variations on the thumbnail viewer are worth quick consideration--the first underscores performance concepts and the others have to do with improving on the arguably odd layout of figure - performancesaving thumbnail files as isthe viewer saves the generated thumbnail image in fileso it can be loaded quickly the next time the script is run this isn' strictly required--example - for instancecustomizes the thumbnail generation function to generate the thumbnail images in memorybut never save them there is no noticeable speed difference for very small image collections if you run these alternatives on larger image collectionsthoughyou'll notice that the original version in example - gains big performance advantage by saving and loading the thumbnails to files on one test with many large image files on my machine (some images from digital camera memory stick and an admittedly underpowered laptop)the original version opens the gui in roughly just seconds after its initial run to cache thumbnailscompared to as much as minute and seconds for example - factor of slower for thumbnailsloading from files is much quicker than recalculation example - pp \gui\pil\viewer-thumbs-nosave py ""samebut make thumb images in memory without saving to or loading from filesseems just as fast for small directoriesbut saving to files makes startup much quicker for large image collectionssaving may be needed in some apps (web pages""import ossys from pil import image from tkinter import tk import viewer_thumbs def makethumbs(imgdirsize=( )subdir='thumbs') tkinter tourpart |
5,072 | create thumbs in memory but don' cache to files ""thumbs [for imgfile in os listdir(imgdir)imgpath os path join(imgdirimgfiletryimgobj image open(imgpathmake new thumb imgobj thumbnail(sizethumbs append((imgfileimgobj)exceptprint("skipping"imgpathreturn thumbs if __name__ ='__main__'imgdir (len(sys argv and sys argv[ ]or 'imagesviewer_thumbs makethumbs makethumbs mainsave viewer_thumbs viewer(imgdirkind=tkmain mainloop(layout optionsgridding the next variations on our viewer are purely cosmeticbut they illustrate tkinter layout concepts if you look at figure - long enoughyou'll notice that its layout of thumbnails is not as uniform as it could be individual rows are fairly coherent because the gui is laid out by row framesbut columns can be misaligned badly due to differences in image shape different packing options don' seem to help (and can make matters even more askew--try it)and arranging by column frames would just shift the problem to another dimension for larger collectionsit could become difficult to locate and open specific images with just little extra workwe can achieve more uniform layout by either laying out the thumbnails in gridor using uniform fixed-size buttons example - positions buttons in row/column grid by using the tkinter grid geometry manager-- topic we will explore in more detail in the next so like the canvasyou should consider some of this code to be preview and seguetoo in shortgrid arranges its contents by row and columnwe'll learn all about the stickiness of the quit button here in example - pp \gui\pil\viewer-thumbs-grid py ""same as viewer_thumbsbut uses the grid geometry manager to try to achieve more uniform layoutcan generally achieve the same with frames and pack if buttons are all fixed and uniform in size""import sysmath from tkinter import from pil imagetk import photoimage from viewer_thumbs import makethumbsviewone viewing and processing images with pil |
5,073 | ""custom version that uses gridding ""win kind(win title('viewerimgdirthumbs makethumbs(imgdirif not colscols int(math ceil(math sqrt(len(thumbs)))fixed or rownum savephotos [while thumbsthumbsrowthumbs thumbs[:cols]thumbs[cols:colnum for (imgfileimgobjin thumbsrowphoto photoimage(imgobjlink button(winimage=photohandler lambda savefile=imgfileviewone(imgdirsavefilelink config(command=handlerlink grid(row=rownumcolumn=colnumsavephotos append(photocolnum + rownum + button(wintext='quit'command=win quitgrid(columnspan=colsstick=ewreturn winsavephotos if __name__ ='__main__'imgdir (len(sys argv and sys argv[ ]or 'imagesmainsave viewer(imgdirkind=tkmain mainloop(figure - displays the effect of gridding--our buttons line up in rows and columns in more uniform fashion than in figure - because they are positioned by both row and columnnot just by rows as we'll see in the next gridding can help any time our displays are two-dimensional by nature layout optionsfixed-size buttons gridding helps--rows and columns align regularly now--but image shape still makes this less than ideal we can achieve layout that is perhaps even more uniform than gridding by giving each thumbnail button fixed size buttons are sized to their images (or textby defaultbut we can always override this if needed example - does the trick it sets the height and width of each button to match the maximum dimension of the thumbnail iconso it is neither too thin nor too high assuming all thumbnails have the same maximum dimension (something our thumb-maker ensures)this will achieve the desired layout tkinter tourpart |
5,074 | example - pp \gui\pil\viewer-thumbs-fixed py ""use fixed size for thumbnailsso align regularlysize taken from image objectassume all same maxthis is essentially what file selection guis do""import sysmath from tkinter import from pil imagetk import photoimage from viewer_thumbs import makethumbsviewone def viewer(imgdirkind=toplevelcols=none)""custom version that lays out with fixed-size buttons ""win kind(win title('viewerimgdirthumbs makethumbs(imgdirif not colscols int(math ceil(math sqrt(len(thumbs)))savephotos [while thumbsthumbsrowthumbs thumbs[:cols]thumbs[cols:row frame(winrow pack(fill=bothfor (imgfileimgobjin thumbsrowsize max(imgobj sizephoto photoimage(imgobjlink button(rowimage=photofixed or widthheight viewing and processing images with pil |
5,075 | link config(command=handlerwidth=sizeheight=sizelink pack(side=leftexpand=yessavephotos append(photobutton(wintext='quit'command=win quitbg='beige'pack(fill=xreturn winsavephotos if __name__ ='__main__'imgdir (len(sys argv and sys argv[ ]or 'imagesmainsave viewer(imgdirkind=tkmain mainloop(figure - shows the results of applying fixed size to our buttonsall are the same size nowusing size taken from the images themselves the effect is to display all thumbnails as same-size tiles regardless of their shapeso they are easier to view naturallyother layout schemes are possible as wellexperiment with some of the configuration options in this code on your own to see their effect on the display figure - fixed-size thumbnail selection guirow frames scrolling and canvases (aheadthe thumbnail viewer scripts presented in this section work well for reasonably sized image directoriesand you can use smaller thumbnail size settings for larger image collections perhaps the biggest limitation of these programsthoughis that the thumbnail windows they create will become too large to handle (or display at allif the image directory contains very many files tkinter tourpart |
5,076 | the bottom of the display in the last two figures because there are too many thumbnail images to show to illustrate the differencethe original example - packs the quit button first for this very reason--so it is clipped lastafter all thumbnailsand thus remains visible when there are many photos we could do similar thing for the other versionsbut we' still lose thumbnails if there were too many directory from your camera with many images might similarly produce window too large to fit on your computer' screen to do betterwe could arrange the thumbnails on widget that supports scrolling the open source pmw package includes handy scrolled frame that may help moreoverthe standard tkinter canvas widget gives us more control over image displays (including placement by absolute pixel coordinatesand supports horizontal and vertical scrolling of its content in factin the next we'll code one final extension to our script which does just that--it displays thumbnails in scrolled canvasand so it handles large collections much better its thumbnail buttons are fixed-size as in our last example herebut are positioned at computed coordinates 'll defer further details herethoughbecause we'll study that extension in conjunction with canvases in the next and in we'll apply this technique to an even more full-featured image program called pyphoto to learn how these programs do their jobsthoughwe need to move on to the next and the second half of our widget tour viewing and processing images with pil |
5,077 | tkinter tourpart "on today' menuspamspamand spamthis is the second in two-part tour of the tkinter library it picks up where left off and covers some of the more advanced widgets and tools in the tkinter arsenal among the topics presented in this menumenubuttonand optionmenu widgets the scrollbar widgetfor scrolling textlistsand canvases the listbox widgeta list of multiple selections the text widgeta general text display and editing tool the canvas widgeta general graphical drawing tool the grid table-based geometry manager time-based toolsafterupdatewaitand threads basic tkinter animation techniques clipboardserasing widgets and windowsand so on by the time you've finished this you will have seen the bulk of the tkinter libraryand you will have all the information you need to compose largerportable user interfaces of your own you'll also be ready to tackle the larger gui techniques and more complete examples presented in and for nowlet' resume the widget show menus menus are the pull-down lists you're accustomed to seeing at the top of window (or the entire displayif you're accustomed to seeing them that way on macintoshmove the mouse cursor to the menu bar at the top and click on name ( file)and list of selectable options pops up under the name you clicked ( opensavethe options within menu might trigger actionsmuch like clicking on buttonthey may |
5,078 | and so on in tkinterthere are two kinds of menus you can add to your scriptstoplevel window menus and frame-based menus the former option is better suited to whole windowsbut the latter also works as nested component top-level window menus in all recent python releases (using tk and later)you can associate horizontal menu bar with top-level window object ( tk or toplevelon windows and unix ( windows)this menu bar is displayed along the top of the windowon some macintosh machinesthis menu replaces the one shown at the top of the screen when the window is selected in other wordswindow menus look like you would expect on whatever underlying platform your script runs upon this scheme is based on building trees of menu widget objects simply associate one toplevel menu with the windowadd other pull-down menu objects as cascades of the toplevel menuand add entries to each of the pull-down objects menus are cross-linked with the next higher levelby using parent widget arguments and the menu widget' add_cascade method it works like this create topmost menu as the child of the window widget and configure the window' menu attribute to be the new menu for each pull-down objectmake new menu as the child of the topmost menu and add the child as cascade of the topmost menu using add_cascade add menu selections to each pull-down menu from step using the command options of add_command to register selection callback handlers add cascading submenu by making new menu as the child of the menu the cascade extends and using add_cascade to link the parent to the child the end result is tree of menu widgets with associated command callback handlers this is probably simpler in code than in wordsthough example - makes main menu with two pull downsfile and editthe edit pull down in turn has nested submenu of its own example - pp \gui\tour\menu_win py tk style top-level window menus from tkinter import from tkinter messagebox import get widget classes get standard dialogs def notdone()showerror('not implemented''not yet available'def makemenu(win)top menu(winwin config(menu=top tkinter tourpart win=top-level window set its menu option |
5,079 | file add_command(label='new 'command=notdoneunderline= file add_command(label='open 'command=notdoneunderline= file add_command(label='quit'command=win quitunderline= top add_cascade(label='file'menu=fileunderline= edit menu(toptearoff=falseedit add_command(label='cut'edit add_command(label='paste'edit add_separator(top add_cascade(label='edit'command=notdonecommand=notdoneunderline= underline= menu=editunderline= submenu menu(edittearoff=truesubmenu add_command(label='spam'command=win quitunderline= submenu add_command(label='eggs'command=notdoneunderline= edit add_cascade(label='stuff'menu=submenuunderline= if __name__ ='__main__'root tk(or toplevel(root title('menu_win'set window-mgr info makemenu(rootassociate menu bar msg label(roottext='window menu basics'add something below msg pack(expand=yesfill=bothmsg config(relief=sunkenwidth= height= bg='beige'root mainloop( lot of code in this file is devoted to setting callbacks and suchso it might help to isolate the bits involved with the menu tree-building process for the file menuit' done like thistop menu(winwin config(menu=topfile menu(toptop add_cascade(label='file'menu=fileattach menu to window cross-link window to menu attach menu to top menu cross-link parent to child apart from building up the menu object treethis script also demonstrates some of the most common menu configuration optionsseparator lines the script makes separator in the edit menu with add_separatorit' just line used to set off groups of related entries tear-offs the script also disables menu tear-offs in the edit pull down by passing tearoff=false widget option to menu tear-offs are dashed lines that appear by default at the top of tkinter menus and create new window containing the menu' contents when clicked they can be convenient shortcut device (you can click items in the tear-off window right awaywithout having to navigate through menu trees)but they are not widely used on all platforms keyboard shortcuts the script uses the underline option to make unique letter in menu entry keyboard shortcut it gives the offset of the shortcut letter in the entry' label string menus |
5,080 | strictly have to use underline--on windowsthe first letter of pull-down name is shortcut automaticallyand arrow and enter keys can be used to select pulldown items but explicit keys can enhance usability in large menusfor instancethe key sequence alt- - - runs the quit action in this script' nested submenu let' see what this translates to in the realm of the pixel figure - shows the window that first appears when this script is run on windows with my system settingsit looks differentbut similaron unixmacintoshand other windows configurations figure - menu_wina top-level window menu bar figure - shows the scene when the file pull down is selected notice that menu widgets are linkednot packed (or gridded)--the geometry manager doesn' really come into play here if you run this scriptyou'll also notice that all of its menu entries either quit the program immediately or pop up "not implementedstandard error dialog this example is about menusafter allbut menu selection callback handlers generally do more useful work in practice figure - the file menu pull down tkinter tourpart |
5,081 | and selecting the cascading submenu in the edit pull down cascades can be nested as deep as you like (though your users probably won' be happy if this gets sillyin tkinterevery top-level window can have menu barincluding pop ups you create with the toplevel widget example - makes three pop-up windows with the same menu bar as the one we just metwhen runit constructs the scene in figure - figure - file tear-off and edit cascade figure - multiple toplevels with menus example - pp \gui\tour\menu_win-multi py from menu_win import makemenu from tkinter import root tk(for in range( )win toplevel(rootmakemenu(winreuse menu maker function three pop-up windows with menus menus |
5,082 | button(roottext="bye"command=root quitpack(root mainloop(frameand menubutton-based menus although these are less commonly used for top-level windowsit' also possible to create menu bar as horizontal frame before show you howthoughlet me explain why you should care because this frame-based scheme doesn' depend on top-level window protocolsit can also be used to add menus as nested components of larger displays in other wordsit' not just for top-level windows for example' pyedit text editor can be used both as program and as an attachable component we'll use window menus to implement pyedit selections when pyedit is run as standalone programbut we'll use frame-based menus when pyedit is embedded in the pymailgui and pyview displays both schemes are worth knowing frame-based menus require few more lines of codebut they aren' much more complex than window menus to make onesimply pack menubutton widgets within frame containerassociate menu widgets with the menubuttonsand associate the frame with the top of container window example - creates the same menu as example - but using the frame-based approach example - pp \gui\tour\menu_frm py frame-based menusfor top-levels and components from tkinter import from tkinter messagebox import get widget classes get standard dialogs def notdone()showerror('not implemented''not yet available'def makemenu(parent)menubar frame(parentmenubar pack(side=topfill=xrelief=raisedbd= fbutton menubutton(menubartext='file'underline= fbutton pack(side=leftfile menu(fbuttonfile add_command(label='new 'command=notdoneunderline= file add_command(label='open 'command=notdoneunderline= file add_command(label='quit'command=parent quitunderline= fbutton config(menu=fileebutton menubutton(menubartext='edit'underline= ebutton pack(side=leftedit menu(ebuttontearoff=falseedit add_command(label='cut'command=notdoneunderline= edit add_command(label='paste'command=notdoneunderline= edit add_separator(ebutton config(menu=edit tkinter tourpart |
5,083 | submenu add_command(label='spam'command=parent quitunderline= submenu add_command(label='eggs'command=notdoneunderline= edit add_cascade(label='stuff'menu=submenuunderline= return menubar if __name__ ='__main__'root tk(or toplevel or frame root title('menu_frm'set window-mgr info makemenu(rootassociate menu bar msg label(roottext='frame menu basics'add something below msg pack(expand=yesfill=bothmsg config(relief=sunkenwidth= height= bg='beige'root mainloop(againlet' isolate the linkage logic here to avoid getting distracted by other details for the file menu casehere is what this boils down tomenubar frame(parentfbutton menubutton(menubartext='file'file menu(fbuttonfbutton config(menu=filemake frame for the menubar attach menubutton to frame attach menu to menubutton crosslink button to menu there is an extra menubutton widget in this schemebut it' not much more complex than making top-level window menus figures - and - show this script in action on windows figure - menu_frmframe and menubutton menu bar the menu widgets in this script provide default set of event bindings that automatically pop up menus when selected with mouse this doesn' look or behave exactly like the top-level window menu scheme shown earlierbut it is closecan be configured in any way that frames can ( with colors and borders)and will look similar on every platform (though this may or may not be feature in all contextsthe biggest advantage of frame-based menu barsthoughis that they can also be attached as nested components in larger displays example - and its resulting interface (figure - show how--both menu bars are completely functional in the same single window menus |
5,084 | example - pp \gui\tour\menu_frm-multi py from menu_frm import makemenu from tkinter import can' use menu_win here--one window but can attach frame menus to windows root tk(for in range( ) menus nested in one window mnu makemenu(rootmnu config(bd= relief=raisedlabel(rootbg='black'height= width= pack(expand=yesfill=bothbutton(roottext="bye"command=root quitpack(root mainloop(figure - multiple frame menus on one window tkinter tourpart |
5,085 | as part of another attachable component' widget package for examplethe menuembedding behavior in example - works even if the menu' parent is another frame container and not the top-level windowthis script is similar to the priorbut creates three fully functional menu bars attached to frames nested in window example - pp \gui\tour\menu_frm-multi py from menu_frm import makemenu from tkinter import can' use menu_win here--root=frame root tk(for in range( )three menus nested in the containers frm frame(mnu makemenu(frmmnu config(bd= relief=raisedfrm pack(expand=yesfill=bothlabel(frmbg='black'height= width= pack(expand=yesfill=bothbutton(roottext="bye"command=root quitpack(root mainloop(using menubuttons and optionmenus in factmenus based on menubutton are even more general than example - implies-they can actually show up anywhere on display that normal buttons cannot just within menu bar frame example - makes menubutton pull-down list that simply shows up by itselfattached to the root windowfigure - shows the gui it produces example - pp \gui\tour\mbutton py from tkinter import root tk(mbutton menubutton(roottext='food'the pull-down stands alone picks menu(mbuttonmbutton config(menu=pickspicks add_command(label='spam'command=root quitpicks add_command(label='eggs'command=root quitpicks add_command(label='bacon'command=root quitmbutton pack(mbutton config(bg='white'bd= relief=raisedroot mainloop(the related tkinter optionmenu widget displays an item selected from pull-down menu it' roughly like menubutton plus display labeland it displays menu of choices when clickedbut you must link tkinter variables (described in to fetch the choice after the fact instead of registering callbacksand menu entries are passed as arguments in the widget constructor call after the variable example - illustrates typical optionmenu usage and builds the interface captured in figure - clicking on either of the first two buttons opens pull-down menu of menus |
5,086 | optionsclicking on the third "statebutton fetches and prints the current values displayed in the first two example - pp \gui\tour\optionmenu py from tkinter import root tk(var stringvar(var stringvar(opt optionmenu(rootvar 'spam''eggs''toast'opt optionmenu(rootvar 'ham''bacon''sausage'opt pack(fill=xopt pack(fill=xvar set('spam'var set('ham'def state()print(var get()var get()button(rootcommand=statetext='state'pack(root mainloop(like menubutton but shows choice linked variables figure - an optionmenu at work there are other menu-related topics that we'll skip here in the interest of space for instancescripts can add entries to system menus and can generate pop-up menus (posted in response to eventswithout an associated buttonrefer to tk and tkinter resources for more details on this front tkinter tourpart |
5,087 | check button and radio button selectionsand bitmap and photo images the next section demonstrates how some of these special menu entries are programmed windows with both menus and toolbars besides showing menu at the topit is common for windows to display row of buttons at the bottom this bottom button row is usually called toolbarand it often contains shortcuts to items also available in the menus at the top it' easy to add toolbar to windows in tkinter--simply pack buttons (and other kinds of widgetsinto framepack the frame on the bottom of the windowand set it to expand horizontally only this is really just hierarchical gui layout at work againbut make sure to pack toolbars (and frame-based menu barsearly so that other widgets in the middle of the display are clipped first when the window shrinksyou usually want your tool and menu bars to outlive other widgets example - shows one way to go about adding toolbar to window it also demonstrates how to add photo images in menu entries (set the image attribute to photo image objectand how to disable entries and give them grayed-out appearance (call the menu entryconfig method with the index of the item to disablestarting from notice that photoimage objects are saved as listrememberunlike other widgetsthese go away if you don' hold on to them (see if you need refresherexample - pp \gui\tour\menudemo py #!/usr/local/bin/python ""tk style main window menus menu/tool bars packed before middlefill= (pack first=clip last)adds photo menu entriessee alsoadd_checkbuttonadd_radiobutton ""from tkinter import from tkinter messagebox import get widget classes get standard dialogs class newmenudemo(frame)def __init__(selfparent=none)frame __init__(selfparentself pack(expand=yesfill=bothself createwidgets(self master title("toolbars and menus"self master iconname("tkpython"an extended frame attach to top-leveldo superclass init attach frames/widgets set window-manager info label when iconified def createwidgets(self)self makemenubar(self maketoolbar( label(selftext='menu and toolbar demo' config(relief=sunkenwidth= height= bg='white' pack(expand=yesfill=bothmenus |
5,088 | toolbar frame(selfcursor='hand 'relief=sunkenbd= toolbar pack(side=bottomfill=xbutton(toolbartext='quit'command=self quit pack(side=rightbutton(toolbartext='hello'command=self greetingpack(side=leftdef makemenubar(self)self menubar menu(self masterself master config(menu=self menubarself filemenu(self editmenu(self imagemenu(master=top-level window def filemenu(self)pulldown menu(self menubarpulldown add_command(label='open 'command=self notdonepulldown add_command(label='quit'command=self quitself menubar add_cascade(label='file'underline= menu=pulldowndef editmenu(self)pulldown menu(self menubarpulldown add_command(label='paste'command=self notdonepulldown add_command(label='spam'command=self greetingpulldown add_separator(pulldown add_command(label='delete'command=self greetingpulldown entryconfig( state=disabledself menubar add_cascade(label='edit'underline= menu=pulldowndef imagemenu(self)photofiles ('ora-lp gif''pythonpowered gif''python_conf_ora gif'pulldown menu(self menubarself photoobjs [for file in photofilesimg photoimage(file=/gifs/filepulldown add_command(image=imgcommand=self notdoneself photoobjs append(imgkeep reference self menubar add_cascade(label='image'underline= menu=pulldowndef greeting(self)showinfo('greeting''greetings'def notdone(self)showerror('not implemented''not yet available'def quit(self)if askyesno('verify quit''are you sure you want to quit?')frame quit(selfif __name__ ='__main__'newmenudemo(mainloop(if ' run as script when runthis script generates the scene in figure - at first figure - shows this window after being stretched bitwith its image menu torn off and its edit menu selected the toolbar at the bottom grows horizontally with the window but not vertically for emphasisthis script also sets the cursor to change to hand when moved over the toolbar at the bottom run this on your own to get better feel for its behavior tkinter tourpart |
5,089 | figure - images and tear-offs on the job menus |
5,090 | as shown in figure - it' easy to use images for menu items although not used in example - toolbar items can be pictures toojust like the image menu' items-simply associate small images with toolbar frame buttonsjust as we did in the image button examples we wrote in the last part of if you create toolbar images manually ahead of timeit' simple to associate them with buttons as we've learned in factit' not much more work to build them dynamically--the pil-based thumbnail image construction skills we developed in the prior might come in handy in this context as well to illustratemake sure you've installed the pil extensionand replace the toolbar construction method of example - with the following ( 've done this in file menudemo py in the examples distribution so you can run and experiment on your own)resize toolbar images on the fly with pil def maketoolbar(selfsize=( ))from pil imagetk import photoimageimage if jpegs or make new thumbs imgdir /pil/images/toolbar frame(selfcursor='hand 'relief=sunkenbd= toolbar pack(side=bottomfill=xphotos 'ora-lp -big jpg''pythonpoweredanim gif''python_conf_ora gifself toolphotoobjs [for file in photosimgobj image open(imgdir filemake new thumb imgobj thumbnail(sizeimage antialiasbest downsize filter img photoimage(imgobjbtn button(toolbarimage=imgcommand=self greetingbtn config(relief=raisedbd= btn config(width=size[ ]height=size[ ]btn pack(side=leftself toolphotoobjs append((imgimgobj)keep reference button(toolbartext='quit'command=self quitpack(side=rightfill=ywhen runthis alternative creates the window captured in figure - --the three image options available in the image menu at the top of the window are now also buttons in the toolbar at the bottomalong with simple text button for quitting on the right as beforethe cursor becomes hand over the toolbar you don' need pil at all if you're willing to use gif or supported bitmap images that you create by hand manually--simply load by filename using the standard tkinter photo objectas shown by the following alternative coding for the toolbar construction method (this is file menudemo py in the examples distribution if you're keeping scope)use unresized gifs with standard tkinter def maketoolbar(selfsize=( ))imgdir /gifs/toolbar frame(selfcursor='hand 'relief=sunkenbd= toolbar pack(side=bottomfill= tkinter tourpart |
5,091 | self toolphotoobjs [for file in photosimg photoimage(file=imgdir filebtn button(toolbarimage=imgcommand=self greetingbtn config(bd= relief=ridgebtn config(width=size[ ]height=size[ ]btn pack(side=leftself toolphotoobjs append(imgkeep reference button(toolbartext='quit'command=self quitpack(side=rightfill=yfigure - menudemo images in the toolbar with pil when runthis alternative uses gif imagesand renders the window grabbed in figure - depending on your user' preferencesyou might want to resize the gif images used here for this role with other toolswe only get part of unresized photos in the fixed-width buttonswhich may or may not be enough as isthis is something of first cut solution to toolbar image buttons there are many ways to configure such image buttons since we're going to see pil in action again later in this when we explore canvasesthoughwe'll leave further extensions in the suggested exercise column automating menu construction menus are powerful tkinter interface device if you're like methoughthe examples in this section probably seem like lot of work menu construction can be both code intensive and error prone if done by calling tkinter methods directly better approach might automatically build and link up menus from higher-level description of their contents in factin we'll meet tool called guimixin that automates the menu construction processgiven data structure that contains all menus desired as menus |
5,092 | an added bonusit supports both window and frame-style menusso it can be used by both standalone programs and nested components although it' important to know the underlying calls used to make menusyou don' necessarily have to remember them for long listboxes and scrollbars let' rejoin our widget tour listbox widgets allow you to display list of items for selectionand scrollbars are designed for navigating through the contents of other widgets because it is common to use these widgets togetherwe'll study them both at once example - builds both listbox and scrollbaras packaged set example - pp \gui\tour\scrolledlist py " simple customizable scrolled listbox componentfrom tkinter import class scrolledlist(frame)def __init__(selfoptionsparent=none)frame __init__(selfparentself pack(expand=yesfill=bothself makewidgets(optionsdef handlelist(selfevent)index self listbox curselection(label self listbox get(indexself runcommand(labeldef makewidgets(selfoptions)sbar scrollbar(self tkinter tourpart make me expandable on list double-click fetch selection text and call action here or get(active |
5,093 | sbar config(command=list yviewlist config(yscrollcommand=sbar setsbar pack(side=rightfill=ylist pack(side=leftexpand=yesfill=bothpos for label in optionslist insert(poslabelpos + #list config(selectmode=singlesetgrid= list bind(''self handlelistself listbox list def runcommand(selfselection)print('you selected:'selectionif __name__ ='__main__'options (('lumberjack-%sxfor scrolledlist(optionsmainloop(xlink sbar and list move one moves other pack first=clip last list clipped first add to listbox or insert(end,labelor enumerate(optionsselect,resize modes set event handler redefine me lower in range( )or map/lambdathis module can be run standalone to experiment with these widgetsbut it is also designed to be useful as library object by passing in different selection lists to the options argument and redefining the runcommand method in subclassthe scrolled list component class defined here can be reused anytime you need to display scrollable list in factwe'll be reusing it this way in ' pyedit program with just little forethoughtit' easy to extend the tkinter library with python classes this way when run standalonethis script generates the window in figure - shown here with windows look-and-feel it' framewith listbox on its left containing generated entries (the fifth has been clicked)along with an associated scrollbar on its right for moving through the list if you move the scrollthe list movesand vice versa figure - scrolledlist at the top listboxes and scrollbars |
5,094 | listboxes are straightforward to usebut they are populated and processed in somewhat unique ways compared to the widgets we've seen so far many listbox calls accept passed-in index to refer to an entry in the list indexes start at integer and grow higherbut tkinter also accepts special name strings in place of integer offsetsend to refer to the end of the listactive to denote the line selectedand more this generally yields more than one way to code listbox calls for instancethis script adds items to the listbox in this window by calling its insert methodwith successive offsets (starting at zero--something the enumerate built-in could automate for us)list insert(poslabelpos + but you can also fill list by simply adding items at the end without keeping position counter at allwith either of these statementslist insert('end'labellist insert(endlabeladd at endno need to count positions end is preset to 'endinside tkinter the listbox widget doesn' have anything like the command option we use to register callback handlers for button pressesso you either need to fetch listbox selections while processing other widgetsevents ( button press elsewhere in the guior tap into other event protocols to process user selections to fetch selected valuethis script binds the left mouse button double-click event to callback handler method with bind (seen earlier on this tourin the double-click handlerthis script grabs the selected item out of the listbox with this pair of listbox method callsindex self listbox curselection(label self listbox get(indexget selection index fetch text by its index heretooyou can code this differently either of the following lines has the same effectthey get the contents of the line at index 'active'--the one selectedlabel self listbox get('active'label self listbox get(activefetch from active index active='activein tkinter for illustration purposesthe class' default runcommand method prints the value selected each time you double-click an entry in the list--as fetched by this scriptit comes back as string reflecting the text in the selected entryc:\pp \gui\tourpython scrolledlist py you selectedlumberjack- you selectedlumberjack- you selectedlumberjack- you selectedlumberjack- listboxes can also be useful input devices even without attached scroll barsthey accept colorfontand relief configuration options they also support both single and multiple tkinter tourpart |
5,095 | selectmode argument supports four settingssinglebrowsemultipleand extended (the default is browseof thesethe first two are single selection modesand the last two allow multiple items to be selected these modes vary in subtle ways for instancebrowse is like singlebut it also allows the selection to be dragged clicking an item in multiple mode toggles its state without affecting other selected items and the extended mode allows for multiple selections and works like the windows file explorer gui--you select one item with simple clickmultiple items with ctrl-click combinationand ranges of items with shift-clicks multiple selections can be programmed with code of this sortlistbox listbox(windowbg='white'font=('courier'fontsz)listbox config(selectmode=extendedlistbox bind(''(lambda eventondoubleclick())ondoubeclickget messages selected in listbox selections listbox curselection(tuple of digit strs - selections [int( )+ for in selectionsconvert to intsmake when multiple selections are enabledthe curselection method returns list of digit strings giving the relative numbers of the items selectedor it returns an empty tuple if none is selected reallythis method always returns tuple of digit stringseven in single selection mode (we don' care in example - because the get method does the right thing for one-item tuplewhen fetching value out of the listboxyou can experiment with the selection alternatives on your own by uncommenting the selectmode setting in example - and changing its value you may get an error on double-clicks in multiple selection modesthoughbecause the get method will be passed tuple of more than one selection index (print it out to see for yourselfwe'll see multiple selections in action in the pymailgui example later in this book ()so 'll pass on further examples here programming scroll bars perhaps the deepest magic in the example - scriptthoughboils down to two lines of codesbar config(command=list yviewlist config(yscrollcommand=sbar setcall list yview when move call sbar set when move the scroll bar and listbox are effectively cross-linked to each other through these configuration optionstheir values simply refer to bound widget methods of the other by linking like thistkinter automatically keeps the two widgets in sync with each other as they move here' how this worksmoving scroll bar invokes the callback handler registered with its command option herelist yview refers to built-in listbox method that adjusts the listbox display proportionallybased on arguments passed to the handler listboxes and scrollbars |
5,096 | command option in this scriptthe sbar set built-in method adjusts scroll bar proportionally in other wordsmoving one automatically moves the other it turns out that every scrollable object in tkinter--listboxentrytextand canvas--has built-in yview and xview methods to process incoming vertical and horizontal scroll callbacksas well as yscrollcommand and xscrollcommand options for specifying an associated scroll bar' callback handler to invoke all scroll bars have command optionto name an associated widget' handler to be called on moves internallytkinter passes information to all of these methodsand that information specifies their new position ( "go percent down from the top")but your scripts usually need never deal with that level of detail because the scroll bar and listbox have been cross-linked in their option settingsmoving the scroll bar automatically moves the listand moving the list automatically moves the scroll bar to move the scroll bareither drag the solid part or click on its arrows or empty areas to move the listclick on the list and either use your arrow keys or move the mouse pointer above or below the listbox without releasing the mouse button in all casesthe list and scroll bar move in unison figure - shows the scene after expanding the window and moving down few entries in the listone way or another figure - scrolledlist in the middle packing scroll bars finallyremember that widgets packed last are always clipped first when window is shrunk because of thatit' important to pack scroll bars in display as soon as possible so that they are the last to go when the window becomes too small for everything you can generally make do with less than complete listbox textbut the scroll bar is crucial tkinter tourpart |
5,097 | cuts out part of the list but retains the scroll bar figure - scrolledlist gets small at the same timeyou don' generally want scroll bar to expand with windowso be sure to pack it with just fill= (or fill= for horizontal scrolland not an expand=yes expanding this example' window in figure - for instancemade the listbox grow along with the windowbut it kept the scroll bar attached to the right and kept it the same size we'll see both scroll bars and listboxes repeatedly in later examples in this and later (flip ahead to examples for pyeditpymailguipyformpytreeand shellgui for moreand although the example script in this section captures the fundamentalsi should point out that there is more to both scroll bars and listboxes than meets the eye here for exampleit' just as easy to add horizontal scroll bars to scrollable widgets they are programmed almost exactly like the vertical one implemented herebut callback handler names start with " ,not " ( xscrollcommand)and an orient='horizontalconfiguration option is set for the scroll bar object to add both vertical and horizontal scrolls and to crosslink their motionsyou would use the following sort of codewindow frame(selfvscroll scrollbar(windowhscroll scrollbar(windoworient='horizontal'listbox listbox(windowmove listbox when scroll moved vscroll config(command=listbox yviewrelief=sunkenhscroll config(command=listbox xviewrelief=sunkenmove scroll when listbox moved listbox config(yscrollcommand=vscroll setrelief=sunkenlistbox config(xscrollcommand=hscroll setsee the image viewer canvas later in this as well as the pyeditpytreeand pymailgui programs later in this bookfor examples of horizontal scroll bars at work scroll bars see more kinds of gui action too--they can be associated with other kinds of widgets in the tkinter library for instanceit is common to attach one to the text listboxes and scrollbars |
5,098 | widget tour text it' been said that tkinter' strongest points may be its text and canvas widgets both provide remarkable amount of functionality for instancethe tkinter text widget was powerful enough to implement the web pages of grailan experimental web browser coded in pythontext supports complex font-style settingsembedded imagesunlimited undo and redoand much more the tkinter canvas widgeta general-purpose drawing deviceallows for efficient free-form graphics and has been the basis of sophisticated image-processing and visualization applications in we'll put these two widgets to use to implement text editors (pyedit)paint programs (pydraw)clock guis (pyclock)and image programs (pyphoto and pyviewfor the purposes of this tour thoughlet' start out using these widgets in simpler ways example - implements simple scrolled-text displaywhich knows how to fill its display with text string or file example - pp \gui\tour\scrolledtext py " simple text or file viewer componentprint('pp scrolledtext'from tkinter import class scrolledtext(frame)def __init__(selfparent=nonetext=''file=none)frame __init__(selfparentself pack(expand=yesfill=bothmake me expandable self makewidgets(self settext(textfiledef makewidgets(self)sbar scrollbar(selftext text(selfrelief=sunkensbar config(command=text yviewtext config(yscrollcommand=sbar setsbar pack(side=rightfill=ytext pack(side=leftexpand=yesfill=bothself text text xlink sbar and text move one moves other pack first=clip last text clipped first def settext(selftext=''file=none)if filetext open(file' 'read(self text delete(' 'endself text insert(' 'textself text mark_set(insert' 'self text focus(delete current text add at line col set insert cursor save user click def gettext(self)returns string tkinter tourpart |
5,099 | if __name__ ='__main__'root tk(if len(sys argv st scrolledtext(file=sys argv[ ]elsest scrolledtext(text='words\ngo here'def show(event)print(repr(st gettext())root bind(''showroot mainloop(first through last filename on cmdline or nottwo lines show as raw string esc dump text like the scrolledlist in example - the scrolledtext object in this file is designed to be reusable component which we'll also put to work in later examplesbut it can also be run standalone to display text file contents also like the last sectionthis script is careful to pack the scroll bar first so that it is cut out of the display last as the window shrinks and arranges for the embedded text object to expand in both directions as the window grows when run with filename argumentthis script makes the window shown in figure - it embeds text widget on the left and cross-linked scroll bar on the right figure - scrolledtext in action just for funi populated the text file displayed in the window with the following code and command lines (and not just because used to live near an infamous hotel in colorado) :\pp \gui\tourtype makefile py open('jack txt'' 'text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.