带有图像和标签的Python GTK3按钮

shu*_*hug 2 python label image button gtk3

我正试图获得带有图像和标签的按钮,并没有成功.我可以使用标签或图像的按钮,但不能同时使用.这是我的代码部分:

try:
    pb = Pixbuf.new_from_file_at_size('myimg.jpg', 100, 100)
except:
    pb = None
img = Gtk.Image()
img.set_from_pixbuf(pb)
button1 = Gtk.Button(xalign=0.5, yalign=1)
#button1.set_label(lbl)
button1.set_image(img)
button1.set_image_position(Gtk.PositionType.TOP)
button1.get_style_context().add_class("btn_article")
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?谢谢

小智 6

Doc:Gtk.Button.set_image(小部件,数据):"如果标签文本为NULL,将显示图像".这里的图像通常是一个图标,因此有一个与之关联的图标名称和(取决于设置),如果需要,根据图标显示标签.反转情况,标签用于查找与其关联的图标以及(如有必要)显示图标.使用:

button1.set_always_show_image (True)
Run Code Online (Sandbox Code Playgroud)

或者,如果没有成功,在里面创建一个容器(在你的情况下为Gtk.Grid)并在按钮内打包,即:

grid = Gtk.Grid ()
img = Gtk.Image()
img.set_from_pixbuf(pb)
label = Gtk.Label ('test')

grid.attach (img, 0, 0, 1, 1)
grid.attach (label, 0, 1, 1, 1)
grid.show_all ()    

button1.add (grid)
Run Code Online (Sandbox Code Playgroud)