Next / Previous / Contents / Shipman's homepage

14. PageTurner.setPageNo(): Select which page is displayed

This method selects which content page is displayed in self.bodyFrame.

pageturner.py
# - - -   P a g e T u r n e r . s e t P a g e N o   - - -

    def setPageNo ( self, n ):
        """Display the nth page, counting from 1."""

First we test the value of n to be sure it is a valid page number. If not, we silently return.

pageturner.py
        #-- 1 --
        # [ if  (n < 1) or (n > len(self.__pageList)) ->
        #     return
        #   else -> I ]
        if  not ( 1 <= n <= len(self.__pageList) ):
            return

The invariant for self.__pageNo states that it is zero if there are no pages; otherwise it is the number of the current page, counting from 1. So, if self.__pageNo is greater than zero, we must remove the current page before we can display a new one.

pageturner.py
        #-- 2 --
        # [ if self.__pageNo > 0 ->
        #     self.__pageList[self.__pageNo-1]  :=  itself ungridded
        #   else -> I ]
        if  self.__pageNo > 0:
            oldPage  =  self.__pageList[self.__pageNo-1]
            oldPage.grid_forget()

Next we adjust the controls to reflect the newly selected page number. In addition to setting the current page number, we also set the total number of pages, because this might be the first time we're displaying a page.

pageturner.py
        #-- 3 --
        # [ self.__pageNoVar  :=  n
        #   self.__nPagesVar  :=  len(self.__pageList) ]
        self.__pageNoVar.set ( str ( n ) )
        self.__nPagesVar.set ( str ( len ( self.__pageList ) ) )

To make the new page appear, we grid it into self.bodyFrame. The sticky argument positions the content in the upper left corner of the frame. The call to the .columnconfigure() and .rowconfigure() methods on the parent widget make the column and row stretchable. Also, we store the new page number in self.__pageNo.

pageturner.py
        #-- 4 --
        # [ self.__pageList[n-1]  :=  itself, gridded
        #   self.__pageNo         :=  n ]
        newPage  =  self.__pageList[n-1]
        newPage.grid ( row=0, column=0, sticky=NW )
        self.bodyFrame.columnconfigure(0, weight=1)
        self.bodyFrame.rowconfigure(0, weight=1)
        self.__pageNo  =  n

There is one additional detail. The Next and Previous buttons are initially disabled. If we have gotten this far, we must also enable them.

pageturner.py
        #-- 5 --
        # [ self.prevButton  :=  self.prevButton enabled
        # [ self.nextButton  :=  self.nextButton enabled ]
        self.prevButton["state"]  =  NORMAL
        self.nextButton["state"]  =  NORMAL