Как получить ответ gtkDialog по умолчанию на триггер пробела, а также - PullRequest
1 голос
/ 22 октября 2010

У меня есть messageDialog, настроенный так, чтобы его ответ по умолчанию был gtk.RESPONSE_OK, поэтому кнопка «ОК» нажимается, когда пользователь нажимает клавишу ввода, даже если кнопка «ОК» не имеет фокуса. Я хотел бы также иметь пробел триггета default_response. Каков наилучший способ сделать это?

Это с Python 2.4 в среде Linux. К сожалению, у меня нет разрешения на обновление Python.

Ответы [ 2 ]

2 голосов
/ 23 октября 2010

Подключение к сигналу key-press-event в диалоговом окне сообщения:

def on_dialog_key_press(dialog, event):
    if event.string == ' ':
        dialog.response(gtk.RESPONSE_OK)
        return True
    return False

dialog = gtk.MessageDialog(message_format='Some message', buttons=gtk.BUTTONS_OK_CANCEL)
dialog.add_events(gtk.gdk.KEY_PRESS_MASK)
dialog.connect('key-press-event', on_dialog_key_press)
dialog.run()

Имейте в виду, однако, что изменение ожиданий пользователей относительно пользовательского интерфейса обычно считается не крутым.

0 голосов
/ 23 октября 2010

Я абсолютный новичок в pygtk, но я не мог заставить работать пример @ ptomato + шаблон "hello world", пока я не ответил на пробел и возврат, а также добавил вызов dialog.destroy ().Возьми это за то, что оно стоит.

#!/usr/bin/env python

# example helloworld.py

import pygtk
pygtk.require('2.0')
import gtk

def md_event(dialog, event):
    if event.keyval in (gtk.keysyms.Return, gtk.keysyms.space):
        dialog.response(gtk.RESPONSE_OK)
        dialog.destroy()
        return True
    elif event.keyval == gtk.keysyms.Escape:
        dialog.response(gtk.RESPONSE_CANCEL)
        dialog.destroy()
        return True
    return False

class HelloWorld:
    # This is a callback function. The data arguments are ignored
    # in this example. More on callbacks below.
    def hello(self, widget, data=None):
        print "Hello World"

    # Another callback
    def destroy(self, widget, data=None):
        gtk.main_quit()

    def create_message_dialog(self, x, y):
        md = gtk.MessageDialog(buttons=gtk.BUTTONS_OK_CANCEL, message_format="wawawawaaaaa")
        md.add_events(gtk.gdk.KEY_PRESS_MASK)
        md.connect("key-press-event", md_event)
        result = md.run()
        print result

    def __init__(self):
        # create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        # Here we connect the "destroy" event to a signal handler.
        # This event occurs when we call gtk_widget_destroy() on the window,
        # or if we return FALSE in the "delete_event" callback.
        self.window.connect("destroy", self.destroy)

        # Sets the border width of the window.
        self.window.set_border_width(10)

        self.button2 = gtk.Button("Message Dialog")
        self.button2.connect("clicked", self.create_message_dialog, None)
        self.window.add(self.button2)
        self.button2.show()

        # and the window
        self.window.show()

    def main(self):
        # All PyGTK applications must have a gtk.main(). Control ends here
        # and waits for an event to occur (like a key press or mouse event).
        gtk.main()

def run_hello():
    hello = HelloWorld()
    hello.main()

# If the program is run directly or passed as an argument to the python
# interpreter then create a HelloWorld instance and show it
if __name__ == "__main__":
    run_hello()
...