from gi.repository import Gtk, GObject
class Window(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.button = Gtk.Button("Hi Printer")
self.button.connect("pressed", self.on_button_clicked)
self.button.connect("released", self.on_button_released)
self.add(self.button)
self.connect("delete-event", Gtk.main_quit)
def on_button_clicked(self, widget):
# arm repeater
self._repeat = True
# trigger printing
self.print_hi()
def on_button_released(self, widget):
# disarm repeater
self._repeat = False
def print_hi(self):
print 'hi'
# tune timeout for repeat rate
timeout = 50
# if should still be repeating
if self._repeat:
# arm timer, with call back to this function
GObject.timeout_add(timeout, self.print_hi)
window = Window()
window.show_all()
Gtk.main()
之前的问题是“点击”在按钮上是上下,“按下”是向下,“释放”是向上。
还更新为使用正确的计时器。
事实证明 gtk 中的超时功能可以自动重新设置,因此可以更简单地完成:
from gi.repository import Gtk, GObject
class Window(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.button = Gtk.Button("Hi Printer")
self.button.connect("pressed", self.on_button_clicked)
self.button.connect("released", self.on_button_released)
self.add(self.button)
self.connect("delete-event", Gtk.main_quit)
def on_button_clicked(self, widget):
# arm repeater
self._repeat = True
# kick off time out
timeout = 50
GObject.timeout_add(timeout, self.print_hi)
def on_button_released(self, widget):
# disarm repeater
self._repeat = False
def print_hi(self):
print 'hi'
# if should still be repeating
return self._repeat
window = Window()
window.show_all()
Gtk.main()
例子