Gtk.对话在Python中按OK键

2024-09-25 08:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个登录对话框,工作正常,但作为response_ok,它只接受ok按钮(尽管作为CANCEL,我可以从键盘按esc)。我试着让它在回车键上做出反应,我觉得应该很容易,但对我来说不是。我试过用set_default_response和其他一些响应,但是没有用。我希望有比连接信号更简单的方法。代码如下:

def get_user_pw(self):
    dialogWindow = Gtk.MessageDialog(self,Gtk.DialogFlags.MODAL|Gtk.DialogFlags.DESTROY_WITH_PARENT,Gtk.MessageType.QUESTION,Gtk.ButtonsType.OK_CANCEL,"Log in")
    dialogBox = dialogWindow.get_content_area()
    login = Gtk.Entry()
    pas = Gtk.Entry()
    pas.set_visibility(False)
    pas.set_invisible_char("*")
    dialogBox.pack_end(has, False, False, 0)
    dialogBox.pack_end(uzytkownik, False, False, 0)
    dialogWindow.show_all()
    Gtk.Dialog.set_default_response(dialogWindow,response_id=Gtk.ResponseType.OK)
    response = dialogWindow.run()
    {some action here}
    dialogWindow.destroy()

Tags: selffalsedefaultgtkgetresponseokpas
1条回答
网友
1楼 · 发布于 2024-09-25 08:38:45

几天前我也遇到过同样的问题,结果发现解决方案是在Entryactivate信号上使用侦听器。在

所以我编辑了您的代码,在username字段中点击Enter将焦点转移到密码字段,在密码字段中,点击Enter模拟单击OK。在

def get_user_pw(self):
    # Create the dialog window
    self.dialogWindow = Gtk.MessageDialog(self,Gtk.DialogFlags.MODAL|Gtk.DialogFlags.DESTROY_WITH_PARENT,Gtk.MessageType.QUESTION,Gtk.ButtonsType.OK_CANCEL,"Log in")

    # Get the content area
    dialogBox = self.dialogWindow.get_content_area()

    # Create fields
    login = Gtk.Entry()
    pas = Gtk.Entry()
    pas.set_visibility(False)
    pas.set_invisible_char("*")

    # Add the fields to the dialog
    dialogBox.pack_end(pas, False, False, 0)
    dialogBox.pack_end(login, False, False, 0)

    # Connect activate to the username field to move to the password field when enter is hit
    login.__next_field = pas
    login.connect("activate", self.next_field)

    # Connect activate to submit the data when enter is hit
    pas.connect("activate", self.submit)

    self.dialogWindow.show_all()

    response = self.dialogWindow.run()
    self.dialogWindow.destroy()

def submit(self, entry):
    # Send the OK response to the dialog
    self.dialogWindow.response(Gtk.ResponseType.OK)

def next_field(self, entry):
    # Move the focus to the next field
    if entry.__next_field is not None:
        entry.__next_field.grab_focus()

相关问题 更多 >