我正在寻找一种在使用Python和GTK + 3的对话框中添加快捷方式选择器小部件的方法。
我试图搜索所有可用的小部件,但似乎没有找到任何现成的解决方案。在这方面,我最好的电话是什么?我应该使用GtkEntry
并拦截按键吗?
尽管这似乎是一个非常普遍的用例,但我找不到任何可行的示例。
答案 0 :(得分:0)
目前没有现成的解决方案,但是您可能可以在Keyboard panel of GNOME Control Center中找到适合的示例。
答案 1 :(得分:0)
我已经使用一个单独的对话框实现了此操作。有一个常规按钮显示当前任务,单击该按钮可打开实现如下的KeyboardShortcutDialog
:
class KeyboardShortcutDialog(Gtk.Dialog):
"""Dialog that allows to grab a keyboard shortcut."""
def __init__(self, parent):
Gtk.Dialog.__init__(self, _("Keyboard shortcut"), parent, 0)
self.shortcut = None
self.set_border_width(32)
# Add a label
label = Gtk.Label(xalign=0.5, yalign=0.5)
label.set_markup(
_('Press the desired key combination, <b>Backspace</b> to remove any shortcut, or <b>Esc</b> to cancel.'))
self.get_content_area().pack_start(label, True, True, 0)
self.connect('key-press-event', self.on_key_press)
self.show_all()
def on_key_press(self, widget, event: Gdk.EventKey):
"""Signal handler: key pressed."""
keyval = event.get_keyval()[1]
name = Gdk.keyval_name(keyval)
# For some reason event.is_modifier == 0 here, even for modifier keys, so we need to resort to checking by name
if name not in [
'Shift_L', 'Shift_R', 'Control_L', 'Control_R', 'Meta_L', 'Meta_R', 'Alt_L', 'Alt_R', 'Super_L',
'Super_R', 'Hyper_L', 'Hyper_R']:
logging.debug('Key pressed: state=%s, keyval=%d', event.state, keyval)
self.shortcut = (
keyval,
event.state &
(Gdk.ModifierType.META_MASK | Gdk.ModifierType.SUPER_MASK | Gdk.ModifierType.HYPER_MASK |
Gdk.ModifierType.SHIFT_MASK | Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.MOD1_MASK))
self.response(Gtk.ResponseType.ACCEPT)
return True
def run(self):
"""Show the dialog and block until it's closed.
:return: tuple (keyval, state) of the key captured or None if the dialog has been closed."""
super().run()
return self.shortcut
对话框的run()
方法返回一个元组,用于指定按下的键组合。