Skip to main content
 首页 » 编程设计

python之使用 PyGObject 创建自定义小部件

2024年11月01日13sharpest

我正在尝试使用 PyGObject 创建自定义小部件。例如,我想创建这个 CustomButton 小部件,它在按钮中添加图像和标签(仅用于示例):

#!/usr/bin/python 
#-*- coding: utf-8 -* 
 
from gi.repository import Gtk 
 
class ImageButton(Gtk.Widget): 
 
    def __init__(self, label, image): 
        Gtk.Widget.__init__(self) 
 
        self.hbox = Gtk.HBox() 
        self.label = Gtk.Label(label) 
        self.image = Gtk.Image.new_from_stock(image, Gtk.IconSize.MENU) 
 
        self.hbox.pack_start(self.image, False, False, 3) 
        self.hbox.pack_start(self.label, False, False, 3) 
 
        self.button = Gtk.Button() 
        self.button.add(self.hbox) 

在另一个文件或类中,我可以这样使用它:

button = ImageButton("My label", Gtk.STOCK_HOME) 

但是当我想使用它时,我不得不调用button 属性,像这样:

# Connect the "clicked" event  
button.button.connect("clicked", on_clicked_button) 
 
# Add the button in a container 
window.add(button.button) 

它有效但不实用。请如何创建像任何其他小部件一样工作的自定义小部件:

button = ImageButton("My label", Gtk.STOCK_HOME) 
button.connect("clicked", on_clicked_button) 
window.add(button) 

请您参考如下方法:

我认为你的问题实际上是一个关于理解类而不是继承的问题。如果您希望您的小部件完全充当按钮,那么它应该是一个按钮。

看看下面的例子:

from gi.repository import Gtk 
 
class ImageButton(Gtk.EventBox): 
 
    def __init__(self, label): 
 
        Gtk.EventBox.__init__(self) 
        self.label = Gtk.Label(label) 
        self.add(self.label)     
 
 
if __name__ == '__main__': 
    def on_imagebutton_clicked(button, data=None): 
        print("Button has been clicked!") 
 
    window = Gtk.Window() 
    button = ImageButton("My label") 
    button.connect('button-press-event', on_imagebutton_clicked) 
    window.add(button) 
    window.show_all() 
    Gtk.main() 

我没有说我的类是一个 Gtk.Widget,而是说它是一个 Gtk.EventBox 并且我是这样开始的。从现在开始,ImageButton 将拥有与 Gtk.EventBox 相同的属性和方法。

*如果我使用 Gtk.Button 而不是 Gtk.EventBox 做了同样的例子 你可以调用 button.connect(.. 而不是 buton.connect.connect(.. 就像你在问题中想要的那样。问题是如果 ImageButton它是一个 Gtk.Button 不可能再修改它来做按钮不能做的事情(比如添加容器和标签)。

简而言之:

您可以基于其他小部件创建自定义小部件,但只有一个小部件会位于树的顶部。

--> Parent   
---------> Child 
---------> Child 

所以当你执行 self.method 时,它总是会寻找:

1) 您的父方法(您使用 Gtk.EventBox.__init__(self)

复制的方法)

2) 您创建的方法。

或者你也可以说谎:

from gi.repository import Gtk 
 
class ImageButton(Gtk.EventBox): 
 
    def __init__(self, label): 
 
        Gtk.EventBox.__init__(self) 
        self.label = Gtk.Label(label) 
        self.add(self.label)     
 
    def set_text(self, text): 
        self.label.set_text(text) 
 
if __name__ == '__main__': 
    def on_imagebutton_clicked(button, data=None): 
        print("Button has been clicked!") 
 
    window = Gtk.Window() 
    button = ImageButton("My label") 
    button.connect('button-press-event', on_imagebutton_clicked) 
    button.set_text('New text!!') 
    window.add(button) 
    window.show_all() 
    Gtk.main() 

请注意,我不必调用 button.label.set_text(..) 我希望它足够清楚!