2
votes

This is my code:

#include <gtk/gtk.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

void destroy(void) {
    gtk_main_quit();
}


int main()
{
    GdkPixbuf* buf;
    GdkPixbuf* buf2;
    GError* err = NULL;
    int a=0, i=0, j=0;

    GtkWidget* window;
    GtkWidget *image =0;

    gtk_init (NULL,NULL);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    buf = gdk_pixbuf_new_from_file("1.jpg", &err);
    buf2 = gdk_pixbuf_new_from_file("2.jpg", &err);

    for(i=0; i<10; i++)
    {
        if((i%2)==0)
        {
            gtk_image_set_from_pixbuf(GTK_IMAGE(image), buf);

            for(j=0; j<10000; j++)
            {}
        }
        else
        {
            gtk_image_set_from_pixbuf(GTK_IMAGE(image), buf2);
            for(j=0; j<10000; j++)
            {}
        }

        g_signal_connect(G_OBJECT (window), "destroy",
        G_CALLBACK (destroy), NULL);
        gtk_container_add(GTK_CONTAINER (window), image);
        gtk_widget_show_all(window);
        gtk_main();
    }

    return 0;
}

And this is the result:

(gtk:4783): Gtk-CRITICAL **: gtk_image_set_from_pixbuf: assertion 'GTK_IS_IMAGE (image)' failed

(gtk:4783): Gtk-CRITICAL **: gtk_container_add: assertion 'GTK_IS_WIDGET (widget)' failed
^C

What I am trying to do is : I have 2 images, and a loop that I want to show one image for odd numbers and other image for even numbers. But this simple task seems very hard to do! please help me to correcting my code...thank you!

1

1 Answers

3
votes

You don't need to create a new GtkImage just to change an image. Juste create a simple GtkWindow with an GtkImage inside. No if/else like you're doing that duplicates code. Then load the image you want to display in a GdkPixbuf, which is the objet that really stores the pixel data. This is done using gdk_pixbuf_new_from_file, and helps you keep around the image data in case you want to show it again (caching). Then you use gtk_image_set_from_pixbuf to ask the GtkImage to change the image it displays.

About your interactive loop: you can't do that unless you create/destroy the whole UI each time you're asked a new number, which is not a refresh. What you need to do is either:

  • ask the user the numbers of all the frames you want to display, and then, create the window and stuff and run the gtk main loop.
  • or better, use a timeout event source using g_timeout_add that will create regularly call a callback where you'll be able to increment a frame counter. Use this counter to get the appropriate image, and call gtk_image_set_from_pixbuf or gtk_image_set_from_file.