Gtk3 Image full window image from file (python

2019-09-09 20:28发布

问题:

I need to find a way to load a image from file such that the image is actual size. I have read documentation [here][https://lazka.github.io/pgi-docs/Gtk-3.0] and [here][http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html] but the only way that seems to work is using the builder class to load a gui designed in glade. However via code I came up with the following and this does not produce the desired result, image is clipped.

from gi.repository import Gtk

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title='GMouse 600')
        self.layout = Gtk.Layout.new(None,None)
        self.add(self.layout)
        self.background = Gtk.Image.new_from_file('./images/g600-thumb-buttons.jpg')
        self.layout.put(self.background, 0, 0)    

window = MainWindow()
window.connect('delete-event', Gtk.main_quit)
window.show_all()
Gtk.main()

I’m trying to find out how I can do this via code, in such a way that my image is filling the window. Can someone please provide any suggestions or possible solutions that I can try.

Note that the reason I wish to do this via code is when I use glade it does produce the desired result except when I try to add a grid layout on top of the image, or any other widget, it will not allow me. Also coding it will give me a chance to better learn and my gui is rather small, very few widgets will be used.

回答1:

It seems I have solved the problem with the following code using Gtk.Overlay

from gi.repository import Gtk

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title='GMouse 600')
        self.overlay = Gtk.Overlay()
        self.add(self.overlay)
        self.background = Gtk.Image.new_from_file('./images/g600-thumb-buttons.jpg')
        self.overlay.add(self.background)
        self.grid = Gtk.Grid()
        self.button = Gtk.Button(label='Test')
        self.grid.add(self.button)
        self.overlay.add_overlay(self.grid)


window = MainWindow()
window.connect('delete-event', Gtk.main_quit)
window.show_all()
Gtk.main()