Convert to OOP

Lesson 12: Converting Procedural code to OOP

From callbacks and images page

from fltk import *
#OOP
class Imgwin(Fl_Window):
    def __init__(self, width, label, img):
        self.pic=Fl_PNG_Image(img)
        ar = self.pic.w()/self.pic.h() #aspect ratio
        bh = int(width/ar) #correct box height for width of 300
        Fl_Window.__init__(self, width , bh, label)
        self.begin()
        self.box=Fl_Box(0, 0, width, bh)
        self.end()
        self.pic= self.pic.copy(self.box.w(), self.box.h())
        self.box.image(self.pic)

app=Imgwin(300,'Cat image','cat.png')
app.show()
Fl.run()

Next example: From Slotmachine page

from fltk import *
import random

class slotmachine(Fl_Window):
    def __init__(self, w, h, label=None):
        Fl_Window.__init__(self, w, h, label)
        fnames=['cherry.png','lemon.png','watermelon.png','bell.png','seven.png','grapes.png']
        pbw=50
        imgw= (w-pbw)//3
        self.I = [ Fl_PNG_Image(f'pics/{name}').copy(imgw, h) for name in fnames ]

        self.B=[]
        self.begin()
        self.pack = Fl_Pack(0,0,self.w(),self.h())
        self.pack.begin()
        for x in range(3):
            self.B.append(Fl_Box(0, 0, 200,0))
            self.B[-1].box(FL_SHADOW_BOX)
            self.B[-1].color(207)
        self.pull = Fl_Return_Button(0,0,pbw ,0,'Pull')
        self.pull.tooltip('Hit enter to play again')
        self.pull.callback(self.pull_cb)
        self.pack.end()
        self.pack.type(Fl_Pack.HORIZONTAL)
        self.end()

    def pull_cb(self,wid):
        shown=[]
        for x in range(3):
            i=random.randrange(len(self.I))
            self.B[x].image(self.I[i])
            shown.append(i) #checking indices not images
            self.redraw() #usually B[x].redraw() but images are transparent
        if len(set(shown)) == 1: #remember sets are unique
            fl_message('You win!')

Fl.scheme('plastic')
app = slotmachine(650, 300, 'slotmachine')
app.show()
Fl.run()