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 veri...
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 screenshot...
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' dictio...
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 (no...
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 o...
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...
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=keycomman...
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 ...
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 outp...
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 t...
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 b...
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...
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 mo...
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 scr...
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 p...
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 bin...
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 common...
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-r...
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 auto...
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...
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 n...
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' g...
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 o...
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 ...
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 ea...
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 entry...
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 v...
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 fetc...
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 la...
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 wi...
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...
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 che...
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 [falsefalsetruefalsetrue...
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 rad...
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 ...
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 au...
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...
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 associ...
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 pheno...
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 mov...
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 beforeusi...
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 insta...
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 syncmo...
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(r...
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...
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 identif...
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 captur...
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 independen...
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/exampl...
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 ...
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 ...
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(paren...
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 program...
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...
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(...
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-leve...
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 ...
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( im...
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 (pyclo...
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 files...
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 varia...
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 im...
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 "sp...
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 wi...
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 ...
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 dir...
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 ...
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...
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 ...
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 th...
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[ ]...
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=photohandle...
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(imgdi...
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...
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 thin...
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 te...
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 m...
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(to...
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 wha...
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...
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-le...
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 lab...
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=bothb...
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 - p...
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 ...
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 c...
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 ima...
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 manuall...
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 - menu...
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 al...
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:'selecti...
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 ...
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 a...
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 cal...
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...
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 settings...
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 scro...