簡單繫結到小部件按鍵事件
在按鍵上呼叫事件處理程式的最簡單方法是將處理程式連線到 key-press-event 訊號。在此示例中,我們為整個視窗註冊事件,但你也可以註冊單個視窗小部件。
最重要的部分是處理程式與事件的連線:
self.connect("key-press-event",self.on_key_press_event)
在事件處理程式中,視窗小部件和按鍵事件作為引數傳入。鍵按鍵修改器如 Ctrl 鍵在 event.state 中可用,按下的鍵是 event.keyval。
修飾鍵的值可在 Gdk.ModiferType 中找到,包括 CONTROL_MASK,SHIFT_MASK 和其他幾個。
關鍵值在 Gdk 中找到,字首為 KEY_ ,例如,h 關鍵是 Gdk.KEY_h)這些可以使用 Gdk.keyval_name() 轉換為字串。
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
class MyWindow(Gtk.Window):
    key = Gdk.KEY_h
    def __init__(self):
        # init the base class (Gtk.Window)
        super().__init__()
        # state affected by shortcuts
        self.shortcut_hits = 0
        # Tell Gtk what to do when the window is closed (in this case quit the main loop)
        self.connect("delete-event", Gtk.main_quit)
        # connect the key-press event - this will call the keypress
        # handler when any key is pressed
        self.connect("key-press-event",self.on_key_press_event)
        # Window content goes in a vertical box
        box = Gtk.VBox()
        # mapping between Gdk.KEY_h and a string
        keyname = Gdk.keyval_name(self.key)
        # a helpful label
        instruct = Gtk.Label(label="Press Ctrl+%s" % keyname)
        box.add(instruct)
        # the label that will respond to the event
        self.label = Gtk.Label(label="")
        self.update_label_text()
        # Add the label to the window
        box.add(self.label)
        self.add(box)
    def on_key_press_event(self, widget, event):
        print("Key press on widget: ", widget)
        print("          Modifiers: ", event.state)
        print("      Key val, name: ", event.keyval, Gdk.keyval_name(event.keyval))
        # check the event modifiers (can also use SHIFTMASK, etc)
        ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)
        # see if we recognise a keypress
        if ctrl and event.keyval == Gdk.KEY_h:
            self.shortcut_hits += 1
            self.update_label_text()
    def update_label_text(self):
        # Update the label based on the state of the hit variable
        self.label.set_text("Shortcut pressed %d times" % self.shortcut_hits)
if __name__ == "__main__":
    win = MyWindow()
    win.show_all()
    # Start the Gtk main loop
    Gtk.main()
使用加速器組( Gtk.AccelGroup ) 可以實現應用程式範圍快捷方式的更高階行為,但通常只需快速按鍵處理程式即可捕獲特定小元件所需的鍵盤事件。