Ruby GTK Pixbuf timed image change

2019-05-21 22:40发布

问题:

I am creating an image slideshow in ruby, using gtk pixbuf to load images. I am very new to ruby & GTK, this may be an stupid question.

Currently image changes are linked to the GUI button_press_event, I would like them to change /refresh automatically based on a set time, like a slideshow or animation. I saw the gtk animation using a gif method, but I would like to use individual jpeg files inline sequence, so that I can set the time to show a slide. Once the loop has gone through all the images, the GUI should display buttons for replay or quit. ( I haven't used @time yet, it is just there for possibilities ) Thanks for any suggestions;

require 'gtk2'

class Pics
  attr_accessor :pile, :picindex, :imgLoaded, :image, :box, :window, :time

def initialize
  @window = Gtk::Window.new()
  @window.signal_connect("destroy"){Gtk.main_quit}
  pic1 = "1.jpg"
  pic2 = "2.jpg"
  pic3 = "3.jpg"
  pic4 = "4.jpg"
  @pile = [pic1, pic2, pic3, pic4]
  @picindex = 0
  self.getImage
  @box = Gtk::EventBox.new.add(@image)
  @time = true
end

def nuImage
  @box.remove(@image)
  @picindex = @picindex + 1
  @picindex = 0 if @picindex == @pile.length
  self.getImage
  @box.add(@image)
  @box.show
end

def getImage
  @imgLoaded = @pile[@picindex]
  img = Gdk::Pixbuf.new(@imgLoaded, 556, 900)
  @image = Gtk::Image.new(img)
  @image.show
end

end # class Pics

pics = Pics.new
  pics.box.signal_connect("button_press_event"){pics.nuImage}
  pics.window.set_default_size(556, 900)
  pics.window.add(pics.box)
  pics.window.show_all

Gtk.main

回答1:

use GLib.timeout_add () or GLib.timeout_add_seconds (). Return False if you don't want to use it anymore.read GLib documentation, Section: Main Event Loop



回答2:

This is a solution:

  def start_button__clicked(but)
    @thread = Thread.new { 
      loop do 
        next_button__clicked
        sleep(2) 
      end 
  end

  def stop_button__clicked(but)
    @thread.kill
  end

This is how I would do it in visual ruby. Its basically the same.

You'd just have a form with a button named "start_button" and "stop_button" etc.



回答3:

the following code is an implementation:

GLib::Timeout.add(1000) do
  pics.nuImage if pics.time
  true
end

pics.window.signal_connect("key_press_event") do |_window, event|
  case event.keyval
  when Gdk::Keyval::GDK_KEY_space
    pics.time = !pics.time
  end
end

more details: http://ruby-gnome2.sourceforge.jp/hiki.cgi?GLib%3A%3ATimeout