PyGobject(六十五)Gtk.Widget之Gtk.Image

来源:互联网 发布:免费商城系统 php 编辑:程序博客网 时间:2024/04/27 20:31

  • GtkImage
    • 继承关系
    • Methods
    • Virtual Methods
    • Properties
    • Signals
    • 例子
      • 一选择磁盘中的图片并显示
      • 二显示网络图片
      • 三显示gif和动态加载图片

Gtk.Image

继承关系

这里写图片描述

Methods

方法修饰词 方法名及参数 static new () static new_from_animation (animation) static new_from_file (filename) static new_from_gicon (icon, size) static new_from_icon_name (icon_name, size) static new_from_icon_set (icon_set, size) static new_from_pixbuf (pixbuf) static new_from_resource (resource_path) static new_from_stock (stock_id, size) static new_from_surface (surface) clear () get_animation () get_gicon () get_icon_name () get_icon_set () get_pixbuf () get_pixel_size () get_stock () get_storage_type () set_from_animation (animation) set_from_file (filename) set_from_gicon (icon, size) set_from_icon_name (icon_name, size) set_from_icon_set (icon_set, size) set_from_pixbuf (pixbuf) set_from_resource (resource_path) set_from_stock (stock_id, size) set_from_surface (surface) set_pixel_size (pixel_size)

Virtual Methods

Properties

Name Type Flags Short Description file str r/w Filename to load and display gicon Gio.Icon r/w The Gio.Icon being displayed icon-name str r/w The name of the icon from the icon theme icon-set Gtk.IconSet d/r/w Icon set to display deprecated icon-size int r/w/en Symbolic size to use for stock icon, icon set or named icon pixbuf GdkPixbuf.Pixbuf r/w A GdkPixbuf.Pixbuf to display pixbuf-animation GdkPixbuf.PixbufAnimation r/w GdkPixbuf.PixbufAnimation to display pixel-size int r/w/en Pixel size to use for named icon resource str r/w The resource path being displayed stock str d/r/w Stock ID for a stock image to display deprecated storage-type Gtk.ImageType r The representation being used for image data surface cairo.Surface r/w A cairo.Surface to display use-fallback bool r/w/en Whether to use icon names fallback

Signals

Name Short Description

例子

一.选择磁盘中的图片并显示

这里写图片描述
这里写图片描述
代码:

#!/usr/bin/env python3# Created by xiaosanyu at 16/7/25# section 105# # author: xiaosanyu# website: yuxiaosan.tk \#  http://blog.csdn.net/a87b01c14# created: 16/7/25TITLE = "ImageViewer"DESCRIPTION = """loads and displays an image file"""import gigi.require_version("Gtk", "3.0")from gi.repository import Gtk, GdkPixbuf, Gdk, Gioimport os, sysclass GUI:    def __init__(self):        window = Gtk.Window()        window.set_title("ImageViewer")        window.connect_after('destroy', self.on_destroy)        self.sw = Gtk.ScrolledWindow()        sw = Gtk.ScrolledWindow()        sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)        sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)        box = Gtk.Box()        box.add(sw)        box.set_spacing(5)        box.set_orientation(Gtk.Orientation.VERTICAL)        self.image = Gtk.Image()        sw.add(self.image)        button = Gtk.Button("Open a picture...")        box.pack_start(button, False, False, 0)        button.connect_after('clicked', self.on_open_clicked, window)        window.add(box)        window.show_all()    def on_open_clicked(self, button, window):        dialog = Gtk.FileChooserDialog("Open Image", button.get_toplevel(), Gtk.FileChooserAction.OPEN);        dialog.add_button(Gtk.STOCK_CANCEL, 0)        dialog.add_button(Gtk.STOCK_OK, 1)        dialog.set_default_response(1)        filefilter = Gtk.FileFilter()        filefilter.add_pixbuf_formats()        dialog.set_filter(filefilter)        if dialog.run() == 1:            pixbuf = GdkPixbuf.Pixbuf.new_from_file(dialog.get_filename())            window.resize(min(pixbuf.get_width(), Gdk.Screen.width()),                          min(pixbuf.get_height(), Gdk.Screen.height()) - 100)            self.image.set_from_file(dialog.get_filename())        dialog.destroy()    def on_destroy(self, window):        window.destroy()        Gtk.main_quit()def main():    app = GUI()    Gtk.main()if __name__ == "__main__":    sys.exit(main())

二.显示网络图片

这里写图片描述
代码:

#!/usr/bin/env python3# Created by xiaosanyu at 16/7/25# section 106# # author: xiaosanyu# website: yuxiaosan.tk \#          http://blog.csdn.net/a87b01c14# created: 16/7/25import gigi.require_version("Gtk", "3.0")from gi.repository import Gtk, GdkPixbufimport urllib.requestTITLE = "Internet Image"DESCRIPTION = """loading an Internet Image"""class ImagesWindow(Gtk.Window):    def __init__(self, *args, **kwargs):        Gtk.Window.__init__(self, title="Show Internet Image")        box = Gtk.VBox(spacing=6)        box.add(Gtk.Label("This photo from the network"))        image = Gtk.Image()        box.add(image)        self.add(box)        self.load_image(image)    @staticmethod    def load_image(image):        response = urllib.request.urlopen("http://pic29.nipic.com/20130508/9252150_163600489317_2.jpg")        data = response.read()        pixbuf_loader = GdkPixbuf.PixbufLoader.new()        pixbuf_loader.write(data)        pixbuf = pixbuf_loader.get_pixbuf()        image.set_from_pixbuf(pixbuf)        pixbuf_loader.close()def main():    win = ImagesWindow()    win.connect("delete-event", Gtk.main_quit)    win.show_all()    Gtk.main()if __name__ == "__main__":    main()

三.显示gif和动态加载图片

这里写图片描述

代码:

#!/usr/bin/env python3# Created by xiaosanyu at 16/7/14# section 104# # author: xiaosanyu# website: yuxiaosan.tk \#          http://blog.csdn.net/a87b01c14# created: 16/7/14TITLE = "Images"DESCRIPTION = """The Gtk.Image widget displays an image. Various kinds of object can be displayed as an image; most typically,you would load a GdkPixbuf.Pixbuf (“pixel buffer”) from a file, and then display that."""import gigi.require_version("Gtk", "3.0")from gi.repository import Gtk, Gdk, Gio, GLib, GdkPixbufimport osclass ImagesWindow(Gtk.Window):    def __init__(self, *args, **kwargs):        Gtk.Window.__init__(self, title="Images Example")        # self.set_size_request(200, 200)        box = Gtk.VBox()        image1 = Gtk.Image.new_from_icon_name("call-start", Gtk.IconSize.MENU)        image2 = Gtk.Image.new_from_file(os.path.join(os.path.dirname(__file__), "../../Data/yxs.png"))        image3 = Gtk.Image.new_from_gicon(Gio.ThemedIcon.new(iconname="battery-caution-charging-symbolic"),                                          Gtk.IconSize.MENU)        image4 = Gtk.Image.new_from_animation(                GdkPixbuf.PixbufAnimation.new_from_file(                    os.path.join(os.path.dirname(__file__), "../../Data/sanpang.gif")))        # Create an empty image for now; the progressive loader will create the pixbuf and fill it in.        image5 = Gtk.Image.new_from_pixbuf()        self.image_stream = None        self.pixbuf_loader = None        self.start_progressive_loading(image5)        box.add(image1)        box.add(image2)        box.add(image3)        box.add(image4)        box.add(image5)        self.add(box)    def progressive_prepared_callback(self, loader, image):        pixbuf = loader.get_pixbuf()        # Avoid displaying random memory contents, since the pixbuf        # isn't filled in yet.        pixbuf.fill(0xaaaaaaff)        image.set_from_pixbuf(pixbuf)    def progressive_updated_callback(self, loader, x, y, width, height, image):        # We know the pixbuf inside the GtkImage has changed, but the image        # itself doesn't know this; so give it a hint by setting the pixbuf        # again. Queuing a redraw used to be sufficient, but nowadays GtkImage        # uses GtkIconHelper which caches the pixbuf state and will just redraw        # from the cache.        pixbuf = image.get_pixbuf()        image.set_from_pixbuf(pixbuf)    def progressive_timeout(self, image):        # This shows off fully-paranoid error handling, so looks scary.        # You could factor out the error handling code into a nice separate        # function to make things nicer.        if self.image_stream:            buf = bytes(256)            bytes_read = self.image_stream.read(buf, None)            if bytes_read < 0:                return False  # uninstall the timeout            if not self.pixbuf_loader.write(buf):                return False  # uninstall the timeout            if bytes_read == 0:                # Errors can happen on close, e.g. if the image                # file was truncated we'll know on close that                # it was incomplete.                if not self.image_stream.close():                    return False  # uninstall the timeout                self.image_stream = None                #   Errors can happen on close, e.g. if the image                #   file was truncated we'll know on close that                #   it was incomplete.                if not self.pixbuf_loader.close():                    return False  # uninstall the timeout                self.pixbuf_loader = None        else:            self.image_stream = Gio.resources_open_stream("/images/alphatest.png",                                                          Gio.ResourceLookupFlags.NONE)            if not self.image_stream:                return False  # uninstall the timeout            if self.pixbuf_loader:                self.pixbuf_loader.close()            self.pixbuf_loader = GdkPixbuf.PixbufLoader.new()            self.pixbuf_loader.connect("area-prepared",                                       self.progressive_prepared_callback, image)            self.pixbuf_loader.connect("area-updated",                                       self.progressive_updated_callback, image)        return True  # leave timeout installed    def start_progressive_loading(self, image):        # This is obviously totally contrived (we slow down loading        # on purpose to show how incremental loading works).        # The real purpose of incremental loading is the case where        # you are reading data from a slow source such as the network.        # The timeout simply simulates a slow data source by inserting        # pauses in the reading process.        self.load_timeout = Gdk.threads_add_timeout(GLib.PRIORITY_DEFAULT_IDLE, 150, self.progressive_timeout, image)        GLib.source_set_name_by_id(self.load_timeout, "[gtk+] progressive_timeout")def main():    win = ImagesWindow()    win.connect("delete-event", Gtk.main_quit)    win.show_all()    Gtk.main()if __name__ == "__main__":    base_path = os.path.abspath(os.path.dirname(__file__))    resource_path = os.path.join(base_path, '../../Data/demo.gresource')    resource = Gio.Resource.load(resource_path)    Gio.resources_register(resource)    main()

关于Gio.Resource文件生成,参见这里




代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728

0 0
原创粉丝点击