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

(yzsuai) #1

self.beep = True
self.drawn = None


def makeWidgets(self):
height, width = self.size
self.canvas = Canvas(self, bg='white', height=height, width=width)
self.canvas.pack(side=LEFT, fill=BOTH, expand=YES)
self.onoff = Button(self, text='Start', command=self.onStart)
self.onoff.pack(fill=X)
Button(self, text='Open', command=self.onOpen).pack(fill=X)
Button(self, text='Beep', command=self.onBeep).pack(fill=X)
Button(self, text='Quit', command=self.onQuit).pack(fill=X)


def onStart(self):
self.loop = True
self.onoff.config(text='Stop', command=self.onStop)
self.canvas.config(height=self.size[0], width=self.size[1])
self.onTimer()


def onStop(self):
self.loop = False
self.onoff.config(text='Start', command=self.onStart)


def onOpen(self):
self.onStop()
name = askopenfilename(initialdir=self.opens, filetypes=imageTypes)
if name:
if self.drawn: self.canvas.delete(self.drawn)
img = PhotoImage(file=name)
self.canvas.config(height=img.height(), width=img.width())
self.drawn = self.canvas.create_image(2, 2, image=img, anchor=NW)
self.image = name, img


def onQuit(self):
self.onStop()
self.update()
if askyesno('PyView', 'Really quit now?'):
self.quit()


def onBeep(self):
self.beep = not self.beep # toggle, or use ^ 1


def onTimer(self):
if self.loop:
self.drawNext()
self.after(self.msecs, self.onTimer)


def drawNext(self):
if self.drawn: self.canvas.delete(self.drawn)
name, img = random.choice(self.images)
self.drawn = self.canvas.create_image(2, 2, image=img, anchor=NW)
self.image = name, img
if self.beep: self.bell()
self.canvas.update()


736 | Chapter 11: Complete GUI Programs

Free download pdf