将Enter键绑定到Button(PyGObject)

时间:2017-09-06 11:44:31

标签: python gtk pygobject

我正在为教育目的编写一个非常简单的GUI程序。该窗口有一个Gtk.Entry区域,我从中获取输入并用作函数num_check()的参数,该函数检查数字是奇数还是偶数(如果输入无效则输出错误)。

按钮工作正常,但我希望能够使用Enter键而不是鼠标。按Enter键后,焦点应返回到输入框(Gtk.Entry)

这是代码。我感谢任何帮助。

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
import odd_even

class EntryWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="ODD OR EVEN")
        self.set_size_request(200, 100)

        self.timeout_id = None

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        self.entry = Gtk.Entry()
        self.entry.get_text()
        vbox.pack_start(self.entry, True, True, 0)

        button = Gtk.Button.new_with_label("Go")
        button.connect("clicked", self.on_click_me_clicked)
        vbox.pack_start(button, True, True, 0)

        self.label = Gtk.Label()
        self.label.get_text()
        vbox.pack_start(self.label, True, True, 0)

# after pressing "Go", grab text from entry and run num_check() with it, then set label with the result
    def on_click_me_clicked(self, button):
        number = self.entry.get_text()
        func = odd_even.num_check(number)
        print(func)

        self.label.set_text(func)


win = EntryWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

1 个答案:

答案 0 :(得分:0)

试试这段代码:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
import odd_even

class EntryWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="ODD OR EVEN")
        self.set_size_request(200, 100)

        self.timeout_id = None

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        self.entry = Gtk.Entry()
        self.entry.get_text()
        self.entry.connect("activate", self.on_entry_activate)
        vbox.pack_start(self.entry, True, True, 0)

        button = Gtk.Button.new_with_label("Go")
        button.connect("clicked", self.on_click_me_clicked)
        vbox.pack_start(button, True, True, 0)

        self.label = Gtk.Label()
        self.label.get_text()
        vbox.pack_start(self.label, True, True, 0)

    def on_entry_activate (self, entry):
        number = entry.get_text()
        func = odd_even.num_check(number)
        print(func)

        self.label.set_text(func)

# after pressing "Go", grab text from entry and run num_check() with it, then set label with the result
    def on_click_me_clicked(self, button):
        number = self.entry.get_text()
        func = odd_even.num_check(number)
        print(func)

        self.label.set_text(func)


win = EntryWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

编辑:信号的文档为here