[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

vbar = Scrollbar(container)
hbar = Scrollbar(container, orient='horizontal')


vbar.pack(side=RIGHT, fill=Y) # pack canvas after bars
hbar.pack(side=BOTTOM, fill=X) # so clipped first
self.pack(side=TOP, fill=BOTH, expand=YES)


vbar.config(command=self.yview) # call on scroll move
hbar.config(command=self.xview)
self.config(yscrollcommand=vbar.set) # call on canvas move
self.config(xscrollcommand=hbar.set)


class ViewOne(Toplevel):
"""
open a single image in a pop-up window when created;
a class because photoimage obj must be saved, else
erased if reclaimed; scroll if too big for display;
on mouse clicks, resizes to window's height or width:
stretches or shrinks; on I/O keypress, zooms in/out;
both resizing schemes maintain original aspect ratio;
code is factored to avoid redundancy here as possible;
"""
def init(self, imgdir, imgfile, forcesize=()):
Toplevel.init(self)
helptxt = '(click L/R or press I/O to resize, S to save, D to open)'
self.title(appname + imgfile + ' ' + helptxt)
imgpath = os.path.join(imgdir, imgfile)
imgpil = Image.open(imgpath)
self.canvas = ScrolledCanvas(self)
self.drawImage(imgpil, forcesize)
self.canvas.bind('', self.onSizeToDisplayHeight)
self.canvas.bind('', self.onSizeToDisplayWidth)
self.bind('', self.onZoomIn)
self.bind('', self.onZoomOut)
self.bind('', self.onSaveImage)
self.bind('', onDirectoryOpen)
self.focus()


def drawImage(self, imgpil, forcesize=()):
imgtk = PhotoImage(image=imgpil) # not file=imgpath
scrwide, scrhigh = forcesize or self.maxsize() # wm screen size x,y
imgwide = imgtk.width() # size in pixels
imghigh = imgtk.height() # same as imgpil.size


fullsize = (0, 0, imgwide, imghigh) # scrollable
viewwide = min(imgwide, scrwide) # viewable
viewhigh = min(imghigh, scrhigh)


canvas = self.canvas
canvas.delete('all') # clear prior photo
canvas.config(height=viewhigh, width=viewwide) # viewable window size
canvas.config(scrollregion=fullsize) # scrollable area size
canvas.create_image(0, 0, image=imgtk, anchor=NW)


724 | Chapter 11: Complete GUI Programs

Free download pdf