Shortcuts

Lesson #5: Handling mouse events, keyboard shortcuts, label alt shortcuts, input widgets, directory chooser, listing directories and Image viewer assignment

Note: setting a keyboard shortcut overrides the & in the label

Callback behavior based on mouse button events:

def but_cb(wid, x):
    if Fl.event_button() == FL_RIGHT_MOUSE:
        wid.color(FL_RED)
    elif Fl.event_button() == FL_LEFT_MOUSE:
        wid.color(FL_GREEN)
    wid.label(str(x))

Celcius to Farenheit converter.

Example code for Fl_Input and Fl_Output widgets and input pop up dialog. The color integers are chosen from
https://www.fltk.org/doc-1.3/drawing.html#drawing_colors

from fltk import *

def but_cb(wid):
    cel=int(inp.value())
    #cel=int(fl_input('Enter celcius: ')) # Alternative is pop-up input dialog 
    far=(cel*9/5)+32
    out.value(str(far))

win = Fl_Window(300,400, 400,300, 'Input Demo')
win.begin()

p=Fl_Pack(0,0,win.w(),win.h())
p.begin()

inp=Fl_Input(0,0,0,50,'Celcius')
inp.align(FL_ALIGN_BOTTOM_LEFT)
inp.textsize(24)
inp.textcolor(218)
inp.labelsize(20) #Celcius
inp.labelcolor(220)
inp.color(247)

out=Fl_Output(0,0,0,50,'Farenheit')
out.align(FL_ALIGN_BOTTOM_LEFT)
out.textsize(24)
out.labelsize(20) #Farenheit
out.labelcolor(100)
out.color(127)

but = Fl_Return_Button(0,0,0,80,'Convert C->F')
but.callback(but_cb)

p.end()
#p.type(FL_VERTICAL) #this is wrong in video
p.type(Fl_Pack.VERTICAL) #corrected
p.spacing(30)

win.end()
win.show()
Fl.run()

temp.png

Here is an example program to execute a function when a specific key is pressed using Fl.add_handler Although, the prefered way to achieve this is to override the handle method of a widget. See OOP Extending section .

from fltk import *

def foo(event):
    if event == FL_SHORTCUT:
        pressed = Fl.event_key()
        if pressed == ord('a'):
            print('you pressed the letter a')
            return 1
        elif pressed == FL_Enter:
            print('you pressed Enter')
            return 1
        else:
            return 0
    else:
        return 0

#see Enumerations for other Fl::event_key() Values

win=Fl_Window(200,200)
Fl.add_handler(foo)
win.show()
Fl.run()

Example code for shortcut special keys and combinations:

from fltk import *

def but_cb(wid):
    print('event')

win = Fl_Window(0,0,400, 400, "shortcuts")
win.begin()
but = Fl_Button(10,10, 170, 50,'OK')
win.end()
but.shortcut(FL_CTRL | ord('a')) #Ctrl-a

# or any of the shortcuts below 
#but.shortcut(FL_META | ord('a')) #windows-a
#but.shortcut(FL_Left) #left arrow
#but.shortcut(FL_ALT|FL_F+6) #Alt-F6
#but.shortcut(ord('6')) #6

but.callback(but_cb)

win.show()
Fl.run()