Re: Key press events on Canvas



On Fri, 30 Oct 2015 14:24:16 -0300
John Coppens <john jcoppens com> wrote:

Is there any way to detect keypresses?

Here's a complete working program:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  test_key_press.py
#  
#  Copyright 2015 John Coppens <john jcoppens com>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
#  


from gi.repository import Gtk, Gdk, GooCanvas

class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.set_size_request(400, 400)
        self.connect("destroy", lambda x: Gtk.main_quit())

        canvas = GooCanvas.Canvas()
        root = canvas.get_root_item()
        #canvas.set_can_focus(True)                         # Makes no difference
        #canvas.set_events(Gdk.EventMask.KEY_PRESS_MASK)    # Makes no difference

        canvas.connect("button-press-event",   self.on_darea_button_pressed)
        canvas.connect("key-press-event",      self.on_darea_key_pressed)

        # Just to show graphics are working:
        rect = GooCanvas.CanvasRect(parent = root,
            x = 40, y = 50, width = 200, height = 40,
            stroke_color = 'red')

        self.add(canvas)
        
        self.show_all()

    def run(self):
        Gtk.main()
        
    def on_darea_button_pressed(self, darea, event):
        print("button pressed")

    def on_darea_key_pressed(self, darea, event):
        print("key pressed")


def main(args):
    mainwdw = MainWindow()
    mainwdw.run()
    
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]