Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Canvas and its callbacks in OO code (See related posts)

I learn to use 2 different types of Canvas callbacks
in the last snippet.

Typically, when I wrote a non-OO code, I will use
   1  app.body = c = Canvas()
where I already had
   1  from appuifw import *


The shortcoming is that I need to define callbacks first,
then pass it to the constructor
c = Canvas(redraw_callback, event_callback)
By using OO, the canvas is created in __init__() and it
can access other methods that come later in the code.
In this case, I use Canvas(self.update) which means that
the self.update will be used to redraw screen.

The secode way to use callback is Canvas.bind() method.
I have always been using this approach to binding any event
callback to a canvas. In some case, the event_callback in
the constructor maybe more elegant, though.

Notice my use of
   1  self.canvas.bind(EKeySelect, self.toggle)

Here I can bind the select key to self.toggle whose definition
will follow. This is more convenient than having to define
it first. So, I think OO code is easier to write in this way.

I also use class variables instead of instance variables.
I found declaring it outside __init__() is more natural
and similar to my previous non-OO approach.
(still easy to read, with variable & def declarations)
When I write self.myvar inside __init__(), I feel the code
is somewhat bloated. The class will have only 1 instance
anyway.

You need to create an account or log in to post comments to this site.


Click here to browse all 5551 code snippets

Related Posts