How to add an image to a button with GTK

跟風遠走 提交于 2021-02-10 07:14:59

问题


I am trying to add an image to a button with label, but the image doesn't show and the broken image doesn't display either.

stop_button = gtk_button_new_with_label("stop");
image = gtk_image_new_from_file ("/home/cendit/Escritorio/index.jpeg");
gtk_button_set_image (GTK_BUTTON(stop_button),image);

I tried a different path "file:///home/cendit/Escritorio/index.jpeg" but it was not successful.


回答1:


Images inside buttons are not visible by default, as we transitioned from GTK+ 2.x to 3.x. Sadly, the API hasn't been cleaned up to reflect this change, so it's a bit of a trap.

If you want to display a button with only an image inside it, you can use:

GtkWidget *image = gtk_image_new_from_file ("...");
GtkWidget *button = gtk_button_new ();

gtk_button_set_image (GTK_BUTTON (button), image);

On the other hand, if you want to have a button with both text and an image inside it, you can use:

GtkWidget *image = gtk_image_new_from_file ("...");
GtkWidget *button = gtk_button_new_with_label ("...");

gtk_button_set_always_show_image (GTK_BUTTON (button), TRUE);
gtk_button_set_image (GTK_BUTTON (button), image);

See the documentation of gtk_button_set_image() for further information.




回答2:


This is what yo need to do

GtkImage *imagen_pantalla_completa;
GtkWidget *pantalla_completa;

pantalla_completa = gtk_button_new_with_label("");                                                  
imagen_pantalla_completa = (GtkImage *)gtk_image_new_from_file("/home/user..."); 
gtk_button_set_image (GTK_BUTTON(pantalla_completa),(GtkWidget *)imagen_pantalla_completa); 

You need to add this to display the image

GtkSettings *default_settings = gtk_settings_get_default();
g_object_set(default_settings, "gtk-button-images", TRUE, NULL);


来源:https://stackoverflow.com/questions/43070832/how-to-add-an-image-to-a-button-with-gtk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!