如何更改GtkImage显示的图像?

时间:2017-11-13 14:36:41

标签: python gtk gtk3 gdkpixbuf

在我的程序中我想通过单击按钮来更改图像,但我找不到该功能

class TestGdkPixbuf(Gtk.Window):
    Cover= "image.png"
    Cover2= "image2.png"

    def __init__(self):
        Gtk.Window.__init__(self, title="TestGdkPixbuf")

        mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)


        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250)
        image_renderer = Gtk.Image.new_from_pixbuf(self.image)

        button = Gtk.Button(label='Change')
        button.connect('clicked', self.editPixbuf)

        mainLayout.pack_start(image_renderer, True, True, 0)
        mainLayout.pack_start(button, True, True, 0)

        self.add(mainLayout)

    def editPixbuf(self, button):
        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250)
        print(self.Cover2)

非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

当您创建了Gtk.Image image_renderer时,您提供了一个pixbuf,self.image

然后在您的按钮回调中,您确实将图像加载到pixbuf中,但未使用新的pixbuf更新image_renderer。你应该使用Gtk.Image set_from_pixbuf

尝试:

class TestGdkPixbuf(Gtk.Window):
    Cover= "image.png"
    Cover2= "image2.png"

    def __init__(self):
        Gtk.Window.__init__(self, title="TestGdkPixbuf")

        mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)


        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250)
        self.image_renderer = Gtk.Image.new_from_pixbuf(self.image)

        button = Gtk.Button(label='Change')
        button.connect('clicked', self.editPixbuf)

        mainLayout.pack_start(image_renderer, True, True, 0)
        mainLayout.pack_start(button, True, True, 0)

        self.add(mainLayout)

    def editPixbuf(self, button):
        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250)
        self.image_renderer.set_from_pixbuf (self.image)
        print(self.Cover2)