id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
5,100 | write('% dall work and no play makes jack dull boy \nif close( :\pp \gui\tourpython makefile py :\pp \gui\tourpython scrolledtext py jack txt pp scrolledtext to view filepass its name on the command line--its text is automatically displayed in the new window by defaultit is shown in font that may vary per platform (and... |
5,101 | run without argumentsthe script stuffs simple literal string into the widgetdisplayed by the first escape press output here (recall that \ is the escape sequence for the lineend characterthe second output here happens after editing the window' textwhen pressing escape in the shrunken window captured in figure - by defa... |
5,102 | index expression end+'- cin the get call in the previous examplefor instanceis really the string 'end- cand refers to one character back from end because end points to just beyond the last character in the text stringthis expression refers to the last character itself the - extension effectively strips the trailing \ t... |
5,103 | self text tag_add(selindex index self text tag_remove(sel' 'endtag all text in the widget select from index up to index remove selection from all text the first line here creates new tag that names all text in the widget--from start through end positions the second line adds range of characters to the built-in sel sele... |
5,104 | ""add common edit tools to scrolledtext by inheritancecomposition (embeddingwould work just as well herethis is not robust!--see pyedit for feature superset""from tkinter import from tkinter simpledialog import askstring from tkinter filedialog import asksaveasfilename from quitter import quitter from scrolledtext impo... |
5,105 | if __name__ ='__main__'if len(sys argv simpleeditor(file=sys argv[ ]mainloop(elsesimpleeditor(mainloop(select text widget filename on command line or notstart empty thistoowas written with one eye toward reuse--the simpleeditor class it defines could be attached or subclassed by other gui code as 'll explain at the end... |
5,106 | the find again (we willin ' more full-featured pyedit examplequit operations reuse the verifying quit button component we coded in yet againcode reuse means never having to say you're quitting without warning figure - save pop-up dialog on windows figure - find pop-up dialog using the clipboard besides text widget oper... |
5,107 | variable but the clipboard is actually much larger concept the clipboard used by this script is an interface to system-wide storage spaceshared by all programs on your computer because of thatit can be used to transfer data between applicationseven ones that know nothing of tkinter for instancetext cut or copied in mic... |
5,108 | self st scrolledtext(selffile=fileattachnot subclass self st text config(font=('courier' 'normal')def onsave(self)filename asksaveasfilename(if filenamealltext self st gettext(open(filename' 'write(alltextgo through attribute def oncut(self)text self st text get(sel_firstsel_lastself st text delete(sel_firstsel_lastmor... |
5,109 | international character sets for both str and bytesbut we must pass decoded unicode str to support the broadest range of character types in this sectionwe decompose the text story in tkinter in general to show why string types in the text widget you may or may not have noticedbut all our examples so far have been repre... |
5,110 | print( get(' ''end')bytesfileline textfileline textfileline bytesfileline this makes it easy to perform text processing on content after it is fetchedwe may conduct it in terms of strregardless of which type of string was inserted howeverthis also makes it difficult to treat text data generically from unicode perspecti... |
5,111 | unicodedecodeerror'utf codec can' decode bytes in position - invalid dat decode(unicodedecodeerror'utf codec can' decode bytes in position - invalid dat decode('latin ' 'aabaconce you've decoded to unicode stringyou can "convertit to variety of different encoding schemes reallythis simply translates to alternative bina... |
5,112 | 'aabacx encode('utf- 'decode('latin- 'decoding worksresult is garbage unicodeencodeerror'charmapcodec can' encode character '\xc in position len( )len( ( no longer the same string encode('utf- ' ' \xc \ \xc \xa cx encode('utf- ' ' \xc \ \xc \ \xc \ \xc \xa cno longer same code points encode('latin- ' ' \xc \xe cx encod... |
5,113 | nowthe same rules apply to text filesbecause unicode strings are stored in files as encoded bytes when writingwe can encode in any format that accommodates the string' characters when readingthoughwe generally must know what that encoding is or provide one that formats characters the same wayopen('ldata'' 'encoding='la... |
5,114 | insert(' 'open('udata''rb'read() pack( get(' ''end''aabac\nstring appears in gui ok it works the same if we pass str fetched in text modebut we then need to know the encoding type on the python side of the fence--reads will fail if the encoding type doesn' match the stored datat text( insert(' 'open('ldata'' 'encoding=... |
5,115 | may be the default platform encoding the problem with treating text as bytes the prior sectionsrules may seem complexbut they boil down to the followingunless strings always use the platform defaultwe need to know encoding types to read or write in text mode and to manually decode or encode for binary mode we can use a... |
5,116 | supports translation using the platform and locale encodings in the local operating system with latin- as fallback python' tkinter passes bytes strings to tcl directlybut copies python str unicode strings to and from tcl unicode string objects tk inherits all of tcl' unicode policiesbut adds additional font selection p... |
5,117 | binary mode for undecoded bytesbut drop \rc:\pp \gui\tourpython from tkinter import use bytesstrip \ if any text(data open('jack txt''rb'read(data data replace( '\ \ ' '\ ' insert(' 'datat pack( get(' ''end')[: ' all work and no play makes jack dull boy \ all work and no plato save content laterwe can either add the \ ... |
5,118 | may also be desirable to limit encoding attempts to just one such source in some contexts watch for this code in franklypyedit in this edition originally read and wrote files in text mode with platform default encodings didn' consider the implications of unicode on pyedit until the pymailgui example' internet world rai... |
5,119 | text config(font=('courier' 'normal')text config(width= height= text pack(expand=yesfill=bothtext insert(end'this is\ \nthe meaning\ \nof life \ \ 'embed windows and photos btn button(texttext='spam'command=lambdahello( )btn pack(text window_create(endwindow=btntext insert(end'\ \ 'img photoimage(file=/gifs/pythonpower... |
5,120 | optionsconsult other tk and tkinter references right nowart class is about to begin canvas when it comes to graphicsthe tkinter canvas widget is the most free-form device in the library it' place to draw shapesmove objects dynamicallyand place other kinds of widgets the canvas is based on structured graphic object mode... |
5,121 | photo on canvas and size canvas for photo earlier on this tour (see "imageson page this script also draws shapestextand even an embedded label widget its window gets by on looks alonein momentwe'll learn how to add event callbacks that let users interact with drawn items figure - canvas hardcoded object sketches progra... |
5,122 | this is different from the constraints we've used to pack widgets thus farbut it allows very fine-grained control over graphical layoutsand it supports more free-form interface techniques such as animation object construction the canvas allows you to draw and display common shapes such as linesovalsrectanglesarcsand po... |
5,123 | although not used by the canvas scriptevery object you put on canvas has an identifierreturned by the create_ method that draws or embeds the object (what was coded as id in the last section' examplesthis identifier can later be passed to other methods that move the object to new coordinatesset its configuration option... |
5,124 | canvas move('bubbles'diffxdiffythis makes three ovals and moves them at the same time by associating them all with the same tag name many objects can have the same tagmany tags can refer to the same objectand each tag can be individually configured and processed as in textcanvas widgets have predefined tag names toothe... |
5,125 | def fillcontent(selfcanv)override me below for in range( )canv create_text( +( * )text='spam'+str( )fill='beige'def ondoubleclick(selfevent)override me below print(event xevent yprint(self canvas canvasx(event )self canvas canvasy(event )if __name__ ='__main__'scrolledcanvas(mainloop(this script makes the window in fig... |
5,126 | and height options to specify an overall canvas sizegive the ( ,ycoordinates of the upper-left and lower-right corners of the canvas in four-item tuple passed to the scrollregion option if no view area size is givena default size is used if no scrollregion is givenit defaults to the view area sizethis makes the scroll ... |
5,127 | at the end of we looked at collection of scripts that display thumbnail image links for all photos in directory therewe noted that scrolling is major requirement for large photo collections now that we know about canvases and scrollbarswe can finally put them to work to implement this much-needed extensionand conclude ... |
5,128 | canvas pack(side=topfill=bothexpand=yesso clipped first vbar config(command=canvas yviewhbar config(command=canvas xviewcanvas config(yscrollcommand=vbar setcanvas config(xscrollcommand=hbar setcanvas config(height=heightwidth=widthcall on scroll move call on canvas move init viewable area size changes if user resizes ... |
5,129 | or simply run the script as is from command lineby clicking its file iconor within idle--without command-line argumentsit displays the contents of the default sample images subdirectory in the book' source code treeas captured in figure - figure - displaying the default images directory canvas |
5,130 | despite its evolutionary twiststhe scrollable thumbnail viewer in example - still has one major limitation remainingimages that are larger than the physical screen are simply truncated on windows when popped up this becomes glaringly obvious when opening large photos copied from digital camera like those in figure - mo... |
5,131 | self oncleardelete all canvas bind(''self onmovemove latest self canvas canvas self drawn none self kinds [canvas create_ovalcanvas create_rectangledef onstart(selfevent)self shape self kinds[ self kinds self kinds[ :self kinds[: self start event self drawn none start dragout def ongrow(selfevent)delete and redraw canv... |
5,132 | remember the last drawn object' identifier two events come into playthe initial button press event saves the start coordinates (reallythe initial press event objectwhich contains the start coordinates)and mouse movement events erase and redraw from the start coordinates to the new mouse coordinates and save the new obj... |
5,133 | much like we did for the text widgetit is also possible to bind events for one or more specific objects drawn on canvas with its tag_bind method this call accepts either tag name string or an object id in its first argument for instanceyou can register different callback handler for mouse clicks on every drawn item or ... |
5,134 | text item clicked (the one closest to the click spot) :\pp \gui\tourpython canvas-bind py got canvas click canvas clicks got canvas click got object click ( ,first text click got canvas click got object click ( ,second text click got canvas click we'll revisit the notion of events bound to canvases in the pydraw exampl... |
5,135 | as grids or as row frames with fixed-width labelsso that labels and entry fields line up horizontally as expected on all platforms (as we learnedcolumn frames don' work reliablybecause they may misalign rowsalthough grids and row frames are roughly the same amount of workgrids are useful if calculating maximum label wi... |
5,136 | from the perspective of the container windowthe label is gridded to column in the current row number ( counter that starts at and the entry is placed in column the upshot is that the grid system lays out all the labels and entries in two-dimensional table automaticallywith both evenly sized rows and evenly sized column... |
5,137 | row + def packbox(parent)"row frames with fixed-width labelsfor color in colorsrow frame(parentlab label(rowtext=colorrelief=ridgewidth= ent entry(rowbg=colorrelief=sunkenwidth= row pack(side=toplab pack(side=leftent pack(side=rightent insert( 'pack'if __name__ ='__main__'root tk(gridbox(toplevel()packbox(toplevel()but... |
5,138 | ent grid(row=rowcolumn= ent insert( 'grid'we'll leave further code compaction to the more serious sports fans in the audience (this code isn' too horrificbut making your code concise in general is not always in your coworkersbest interest!irrespective of coding tricksthe complexity of packing and gridding here seems si... |
5,139 | frm pack(padx= pady= gridbox(frmlabel(roottext='pack:'pack(frm frame(rootbd= relief=raisedfrm pack(padx= pady= packbox(frmbutton(roottext='quit'command=root quitpack(mainloop(when this runs we get composite window with two forms that look identical (figure - )but the two nested frames are actually controlled by complet... |
5,140 | from grid import gridboxpackbox root tk(gridbox(rootpackbox(rootbutton(roottext='quit'command=root quitpack(mainloop(this script passes the same parent (the top-level windowto each function in an effort to make both forms appear in one window it also utterly hangs the python process on my machinewithout ever showing an... |
5,141 | for color in colorslab label(roottext=colorrelief=ridgewidth= ent entry(rootbg=colorrelief=sunkenwidth= lab grid(row=rowcolumn= sticky=nsewent grid(row=rowcolumn= sticky=nsewroot rowconfigure(rowweight= row + root columnconfigure( weight= root columnconfigure( weight= def packbox(root)label(roottext='pack'pack(for colo... |
5,142 | as codedshrinking the pack window clips items packed lastshrinking the grid window shrinks all labels and entries together unlike grid ' default behavior (try this on your ownresizing in grids now that 've shown you what these windows doi need to explain how they do it we learned in how to make widgets expand with pack... |
5,143 | packer gridded widgets can optionally be made sticky on one side of their allocated cell space (such as anchoror on more than one side to make them stretch (such as fillwidgets can be made sticky in four directions--nseand wand concatenations of these letters specify multiple-side stickiness for instancea sticky settin... |
5,144 | we'll code near the end of and use again in when developing file transfer and ftp client user interface as we'll seedoing forms well once allows us to skip the details later we'll also use more custom form layout code in the pyedit program' change dialog in and the pymailgui example' email header fields in laying out l... |
5,145 | table of input fieldsdefault tk root window from tkinter import rows [for in range( )cols [for in range( )ent entry(relief=ridgeent grid(row=icolumn=jsticky=nsewent insert(end'% % (ij)cols append(entrows append(colsdef onpress()for row in rowsfor col in rowprint(col get()end='print(button(text='fetch'command=onpressgri... |
5,146 | rows [for in range(numrow)cols [for in range(numcol)ent entry(relief=ridgeent grid(row=icolumn=jsticky=nsewent insert(end'% % (ij)cols append(entrows append(colssums [for in range(numcol)lab label(text='?'relief=sunkenlab grid(row=numrowcolumn=isticky=nsewsums append(labdef onprint()for row in rowsfor col in rowprint(c... |
5,147 | button(text='quit'command=sys exitgrid(row=numrow+ column= mainloop(figure - shows this script at work summing up four columns of numbersto get different-size tablechange the numrow and numcol variables at the top of the script figure - adding column sums and finallyexample - is one last extension that is coded as clas... |
5,148 | for in range(numcol)lab label(selftext='?'relief=sunkenlab grid(row=numrow+ column=isticky=nsewself sums append(labbutton(selftext='sum'command=self onsumgrid(row= column= button(selftext='print'command=self onprintgrid(row= column= button(selftext='clear'command=self oncleargrid(row= column= button(selftext='load'comm... |
5,149 | import sys root tk(root title('summer grid'if len(sys argv! sumgrid(rootpack(grid(works here too elserowscols eval(sys argv[ ])eval(sys argv[ ]sumgrid(rootrowscolspack(mainloop(notice that this module' sumgrid class is careful not to either grid or pack itself in order to be attachable to containers where other widgets... |
5,150 | figure - opening data file for sumgrid figure - data file loadeddisplayedand summed tkinter tourpart |
5,151 | of its columnsnot just simple numbers because this script converts input field values with the python eval built-in functionany python syntax will work in this table' fieldsas long as it can be parsed and evaluated within the scope of the onsum methodc:\pp \gui\tour\gridtype grid -data txt * - << % pow( , ** [ , ][ {' ... |
5,152 | exercises should also point out that there is more to gridding than we have time to present fully here for instanceby creating subframes that have grids of their ownwe can build up more sophisticated layouts as component hierarchies in much the same way as nested frames arranged with the packer for nowlet' move on to o... |
5,153 | and the simpler examples aheadwidget after_idle(function*argsthis tool schedules the function to be called once when there are no more pending events to process that isfunction becomes an idle handlerwhich is invoked when the gui isn' busy doing anything else widget after_cancel(idthis tool cancels pending after callba... |
5,154 | widget wait_window(winwidget wait_visibility(winthese tools pause the caller until tkinter variable changes its valuea window is destroyedor window becomes visible all of these enter local event loopsuch that the application' mainloop continues to handle events note that var is tkinter variable object (discussed earlie... |
5,155 | constraints on programs for examplebecause spawned threads cannot usually perform gui processingthey must generally communicate with the main thread using global variables or shared mutable objects such as queuesas required by the application spawned thread which watches socket for datafor instancemight simply set glob... |
5,156 | default second frame __init__(selfself msecs msecs self pack(stopper button(selftext='stop the beeps!'command=self quitstopper pack(stopper config(bg='navy'fg='white'bd= self stopper stopper self repeater(def repeater(self)self bell(self stopper flash(self after(self msecsself repeateron every millisecs beep now flash ... |
5,157 | the button flash method flashes the widgetbut it' easy to dynamically change other appearance options of widgetssuch as buttonslabelsand textwith the widget config method for instanceyou can also achieve flash-like effect by manually reversing foreground and background colors with the widget config method in scheduled ... |
5,158 | normaliconiczoomed (full screen)or withdrawn experiment with these methods on your own to see how they differ they are also useful to pop up prebuilt dialog windows dynamicallybut are perhaps less practical here example - pp \gui\tour\alarm-withdraw py samebut hide or show entire window on after(timer callbacks from tk... |
5,159 | deferred because of thatcanvas update must be called to redraw the screen after each moveor else updates don' appear until the entire movement loop callback finishes and returns this is classic long-running callback scenariowithout manual update callsno new gui events are handled until the callback returns in this sche... |
5,160 | self kinds self create_oval_taggedself create_rectangle_tagged def create_oval_tagged(selfx )objectid self canvas create_oval( self canvas itemconfig(objectidtag='ovals'fill='blue'return objectid def create_rectangle_tagged(selfx )objectid self canvas create_rectangle( self canvas itemconfig(objectidtag='rectangles'fil... |
5,161 | using widget after events the main drawback of this first approach is that only one animation can be going at onceif you press "ror "owhile move is in progressthe new request puts the prior movement on hold until it finishes because each move callback handler assumes the only thread of control while it runs that isonly... |
5,162 | ""similarbut with widget after(scheduled eventsnot time sleep loopsbecause these are scheduled eventsthis allows both ovals and rectangles to be moving at the _same_ time and does not require update calls to refresh the guithe motion gets wild if you press 'oor 'rwhile move in progressmultiple move updates start firing... |
5,163 | import canvasdraw_tags import _threadtime class canvaseventsdemo(canvasdraw_tags canvaseventsdemo)def moveem(selftag)for in range( )for (diffxdiffyin [(+ )( + )(- )( - )]self canvas move(tagdiffxdiffytime sleep( pause this thread only def moveinsquares(selftag)_thread start_new_thread(self moveem(tag,)if __name__ ='__m... |
5,164 | besides canvas-based animationswidget configuration tools support variety of animation effects for exampleas we saw in the flashing and hiding alarm scripts earlier (see example - )it is also easy to change the appearance of other kinds of widgets dynamically with after timer-event loops with timer-based loopsyou can p... |
5,165 | package for common animation and movie file formats such as fli and mpeg other third-party toolkits such as openglblenderpygamemayaand vpython provide even higher-level graphics and animation toolkits the pyopengl system also offers tk support for guis see the pypi websites for links or search the web if you're interes... |
5,166 | popular pmwtixor ttk extension packages for tkinter (described in or any other third-party packages in general for instancetix and ttk both provide additional widget options outlined in which are now part of python' standard library the third-party domain tends to change over timebut has hosted tree widgetshtml viewers... |
5,167 | gui coding techniques "building better mousetrapthis continues our look at building guis with python and the tkinter library by presenting collection of more advanced gui programming patterns and techniques in the preceding three we explored all the fundamentals of tkinter itself hereour goal is to put them to work to ... |
5,168 | you study them in the examples distribution package two notes before we beginfirstbe sure to read the code listings in this for details we won' present in the narrative secondalthough small examples that apply in this techniques will show up along the waymore realistic application will have to await more realistic prog... |
5,169 | widget label(roottext=textrelief=ridgewidget pack(side=sideexpand=yesfill=bothif extraswidget config(**extrasreturn widget default config pack automatically apply any extras def button(rootsidetextcommand**extras)widget button(roottext=textcommand=commandwidget pack(side=sideexpand=yesfill=bothif extraswidget config(**... |
5,170 | ""############################################################################## "mixinclass for other framescommon methods for canned dialogsspawning programssimple text viewersetcthis class must be mixed with frame (or subclass derived from framefor its quit method ####################################################... |
5,171 | text with scrollbar view text config(height= width= config text in frame view text config(font=('courier' 'normal')use fixed-width font new title("text viewer"set window mgr attrs new iconname("browser"file text added auto ""def browser(selffilename)new toplevel(text scrolledtext(newheight= width= text config(font=('co... |
5,172 | the quit method serves some of the same purpose as the reusable quitter button we used in earlier because mixin classes can define large library of reusable methodsthey can be more powerful way to package reusable components than individual classes if the mixin is packaged wellwe can get lot more from it than single bu... |
5,173 | guimakerautomating menus and toolbars the last section' mixin class makes common tasks simplerbut it still doesn' address the complexity of linking up widgets such as menus and toolbars of courseif we had access to gui layout tool that generates python codethis would not be an issueat least for some of the more static ... |
5,174 | [helpbutton true def __init__(selfparent=none)frame __init__(selfparentself pack(expand=yesfill=bothself start(self makemenubar(self maketoolbar(self makewidgets(change per instance in subclasses set these in start(if need self make frame stretchable for subclassset menu/toolbar done herebuild menu bar done herebuild t... |
5,175 | ""if self toolbartoolbar frame(selfcursor='hand 'relief=sunkenbd= toolbar pack(side=bottomfill=xfor (nameactionwherein self toolbarbutton(toolbartext=namecommand=actionpack(wheredef makewidgets(self)""make 'middlepart lastso menu/toolbar is always on top/bottom and clipped lastoverride this defaultpack middle any sidef... |
5,176 | self-test when file run standalone'python guimaker py##############################################################################if __name__ ='__main__'from guimixin import guimixin mix in help method menubar ('file' [('open' lambda: )lambda: is no-op ('quit' sys exit)])use sysno self here ('edit' [('cut' lambda: )('... |
5,177 | to be textbut images could be supported too (see the note under "bigguia client demo programon page for varietythe mouse cursor changes based upon its locationa hand in the toolbarcrosshairs in the default middle partand something else over help buttons of framebased menus (customize as desiredsubclass protocols in add... |
5,178 | in return for conforming to guimaker protocols and templatesclient subclasses get frame that knows how to automatically build up its own menus and toolbars from template data structures if you read the preceding menu examplesyou probably know that this is big win in terms of reduced coding requirements gui maker is als... |
5,179 | we'll put guimaker to more practical use in instances such as the pyedit example in the next section shows another way to use guimaker' templates to build up sophisticated interfaceand serves as another test of its functionality bigguia client demo program let' look at program that makes better use of the two automatio... |
5,180 | or guimakerframemenu def start(self)self hellos self master title("guimaker demo"self master iconname("guimaker"def spawnme()self spawn('big_gui py'defer call vs lambda self menubar ('file' [('new ' spawnme)('open ' self fileopen)('quit' self quit))('edit' [('cut'- self notdone)('paste'- self notdone)'separator'('stuff... |
5,181 | print("hi"elseself infobox("three"'hello!'on every third press def dialog(self)button self question('oops!''you typed "rm*continue?''questhead'('yes''no')[lambdanoneself quit][button](old style args ignored def fileopen(self)pick self selectopenfile(file='big_gui py'if pickself browser(pickbrowse my source fileor other... |
5,182 | figure - big_gui with spawned demos finallyi should note that guimaker could be redesigned to use trees of embedded class instances that know how to apply themselves to the tkinter widget tree being constructedinstead of branching on the types of items in template data structures in the interest of spacethoughwe'll ban... |
5,183 | which redefines its toolbar construction method would be both great way to experiment with the code and useful utility if added every cool feature imaginablethoughthis book could easily become big enough to be gravitationally significant shellguiguis for command-line tools demos are funbut to better show how things lik... |
5,184 | self setmenubar(self settoolbar(self master title("shell tools listbox"self master iconname("shell tools"use guimaker if component def handlelist(selfevent)label self listbox get(activeself runcommand(labelon listbox double-click fetch selection text and call action here def makewidgets(self)add listbox in middle sbar ... |
5,185 | def runcommand(selfcmd)self mymenu[cmd](the shellgui class in this module knows how to use the guimaker and guimixin interfaces to construct selection window that displays tool names in menusa scrolled listand toolbar it also provides fortoolbar method that you can override and that allows subclasses to specify which t... |
5,186 | def __init__(self)self mymenu {'pack 'runpackdialog'unpack'rununpackdialog'mtool 'self notdonedictmenugui __init__(selfif __name__ ='__main__'from sys import argv if len(argv and argv[ ='list'print('list test'textpak (mainloop(elseprint('dict test'textpak (mainloop(or use input here instead of in dialogs self-test code... |
5,187 | so farwe've coded general shell tools class libraryas well as an application-specific tool set module that names callback handlers in its option menus to complete the picturewe still need to define the callback handlers run by the guias well as the scripts they ultimately invoke non-gui scripts to test the shell gui' a... |
5,188 | name prefix line[mlen:- print('creating:'nameoutput open(name' 'or make new output if __name__ ='__main__'unpack(sys argv[ ]these scripts are fairly basicand this gui part of the book assumes you've already scanned the system tools so we won' go into their code in depth variants of these scripts appeared in the first e... |
5,189 | ::::::::::::::::::::textpak=>spam txt spam spam spam these scripts don' do anything about binary filescompressionor the likebut they serve to illustrate command-line scripts that require arguments when run although they can be launched with shell commands as above (and hence python tools like os popen and subprocess)th... |
5,190 | uses packed row frames lab pack(side=leftand fixed-width labels ent pack(side=leftexpand=yesfill=xor use grid(rowcolif browsebtn button(rowtext='browse 'btn pack(side=rightif not extendbtn config(commandlambdavar set(askopenfilename(or var get()elsebtn config(commandlambdavar set(var get(askopenfilename()return var nex... |
5,191 | form shown in figure - this is also what we get when its main function is launched by the mytools py shell tools gui users may either type input and output filenames into the entry fields or press the "browsebuttons to pop up standard file selection dialogs they can also enter filename patterns--the manual glob call in... |
5,192 | win title('enter unpack parameters'var makeformrow(winlabel='input file'width= win bind(''lambda eventwin destroy()win grab_set(win focus_set(make myself modal win wait_window(till ' destroyed on return return var get(or closed by wm action def rununpackdialog()input unpackdialog(if input !''print('unpacker:'inputunpac... |
5,193 | pp scrolledtext list test packerpacked all ['spam txt''ham txt''eggs txt'packingspam txt packingham txt packingeggs txt unpackerpacked all creatingspam txt creatingham txt creatingeggs txt this may be less than ideal for gui' usersthey may not expect (or even be able to findthe command-line console we can do better her... |
5,194 | ""##############################################################################first-cut implementation of file-like classes that can be used to redirect input and output streams to gui displaysas isinput comes from common dialog pop-up ( single output+input interface or persistent entry field for input would be bette... |
5,195 | line self buff while linetext text line line self inputline(return text def readline(self)text self buff or self inputline(self buff 'return text def readlines(self)lines [while truenext self readline(if not nextbreak lines append(nextreturn lines def redirectedguifunc(func*pargs**kargs)import sys savestreams sys stdin... |
5,196 | print('end of file'root tk(button(roottext='test streams'command=lambdaredirectedguifunc(makeupper)pack(fill=xbutton(roottext='test files 'command=lambdamakelower(guiinput()guioutput()pack(fill=xbutton(roottext='test popen 'command=lambdaredirectedguishellcmd('dir *')pack(fill=xroot mainloop(as coded hereguioutput atta... |
5,197 | although guioutput takes care to call tkinter' update method to update the display after each line is writtenthis module has no control in general over the duration of functions or shell commands it runs in redirectedguishellcmdfor examplethe call to input readline will pause until an output line is received from the s... |
5,198 | mytools py in example - to register code like the function wrapper here as its callback handlers in factyou can use this technique to route the output of any function call or command line to pop-up windowas usualthe notion of compatible object interfaces is at the heart of much of python code' flexibility reloading cal... |
5,199 | provide an indirection layer that routes callbacks from registered objects to modules so that reloads have impact for examplethe script in example - goes the extra mile to indirectly dispatch callbacks to functions in an explicitly reloaded module the callback handlers registered with tkinter are method objects that do... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.