Python GTK3将图像添加到Widget



我有以下片段:

def updateImages(self):
  filename = '.scriptsfile.png'
  self.image = Gtk.Image()
  image.set_from_file(filename)
  # i need a line here to put the file object in a widget
  image.show()

当我加载使用Glade构建的GUI时,我有一个特定的图片区域,请参阅下面。如何将image连接到该区域(picturearea)?

  self.builder = Gtk.Builder()
  self.picturearea = self.builder.get_object('picturearea')

更新示例:

class Picture(Gtk.Window):
def __init__(self, *args, **kwargs):
    Gtk.Window.__init__(self)
    self.builder = Gtk.Builder()
    self.builder.add_objects_from_file('layout.glade', ('window1',''))
    #self.builder.connect_signals(Signals())
    thewindow = self.builder.get_object('window1')
    self.picturearea = self.builder.get_object('imagefield')
    filechooserbutton = self.builder.get_object('button2')
    button = self.builder.get_object('button1')
    button.connect("clicked", self.on_load_image_clicked)
    filechooserbutton.connect("clicked", self.on_chooser_clicked)
    self.text_entry = self.builder.get_object('entry1')
    thewindow.set_title("Show an image")
    thewindow.show_all() 
def on_load_image_clicked(self, button):
    #currentpicture = self.picturearea.get_child()
    #self.picturearea.remove(currentpicture)
    image = Gtk.Image()
    path = self.text_entry.get_text()
    try:
        image.set_from_file(path)
        self.picturearea.add(image)
        image.show()
        self.picturearea.show_all()
    except:
        pass
def on_chooser_clicked(self, button):
    dialog = Gtk.FileChooserDialog("Please select an image file", self, Gtk.FileChooserAction.OPEN, ( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print "Response was OK"
        text = dialog.get_filename()
        self.text_entry.set_text(text)
    dialog.destroy()

app = Picture()
app.connect("delete-event", Gtk.main_quit)
Gtk.main()

然而,图像仍然没有显示(在glade中使用imagefield)

我不知道picturearea对象是什么,但通常它可以是Box或DrawingArea。此外,您似乎正在创建一个图像,但没有将图像添加到任何小部件中。

以下示例通过使用框来工作:

#/usr/bin/env python3
from gi.repository import Gtk
def update_image(widged, data=None):
    # remove the previous image
    for child in image_area.get_children():
        image_area.remove(child)
    ## add a new image
    image = Gtk.Image()
    image.set_from_file('./test.png')
    image_area.add(image)
    image_area.show_all()

window = Gtk.Window()
box = Gtk.VBox()
image_area = Gtk.Box()

button=Gtk.Button(label="click me to set the image")
button.connect('clicked', update_image)

box.add(button)
box.add(image_area)
window.add(box)
window.show_all()
Gtk.main()

(当然,您可以在glade中定义Box。)

最新更新