Next / Previous / Contents / Shipman's homepage

10. PageTurner.__pageNoHandler(): Jump to a user-selected page

When the user presses the Enter key in the self.pageNoEntry field, this handler is called. If the user has entered a valid integer that is within the range of external page numbers (counting from 1), we call the self.setPageNo() method to present that page.

Because this handler uses the event binding (.bind()) rather than the command binding (command=...), it is called with an Event object as an argument. However, we don't need the event to find out what happened. We simply inspect the value of the .__pageNoVar control variable and attempt to use it to change the page number.

If the user enters something other than a number in the Entry widget, or a number that is outside the range of page numbers, we could give them an error popup, but it should be sufficient feedback just to change the field's value back to the current page number.

pageturner.py
# - - -   P a g e T u r n e r . _ _ p a g e N o H a n d l e r   - - -

    def __pageNoHandler ( self, event ):
        """Handle a change to self.pageNoEntry

          [ event is an Event object ->
              if self.__pageNoVar contains a valid integer that
              is in the range [1,len(self.__pageList)] ->
                self  :=  self displaying int(self.__pageNoVar.get())
              else ->
                self.pageNoEntry  :=  self.__pageNo as a string ]
        """

First we get the field value, attempt to convert it to an integer, and check that it is a valid external page number. If any of these steps fail, reset the page number and exit.

pageturner.py
        #-- 1 --
        # [ if self.__pageNoVar contains an integer in
        #   [1,len(self.__pageList)] ->
        #     self  :=  self displaying page (pageNo)
        #     return
        #   else -> I ]
        try:
            pageNo  =  int ( self.__pageNoVar.get() )
            if  ( 1 <= pageNo <= len(self.__pageList) ):
                self.setPageNo ( pageNo )
                return
        except ValueError:
            pass

        #-- 2 --
        # [ self.pageNoEntry  :=  self.__pageNo as a string ]
        self.__pageNoVar.set ( self.__pageNo )