Mot magique en C avec affichage graphique gtk
Code
#include <gtk/gtk.h>
GtkWidget *window, *label, *entry, *button, *hbox;
// Fonction appelée lorsque le bouton est cliqué ou la touche Entrée est pressée
void on_button_clicked(GtkWidget *widget, gpointer data) {
const char *text = gtk_entry_get_text(GTK_ENTRY(entry));
// Comparaison du texte entré avec 'magique'
if (g_strcmp0(text, 'magique') == 0) {
gtk_label_set_text(GTK_LABEL(label), 'BRAVO');
} else {
gtk_label_set_text(GTK_LABEL(label), 'ERREUR');
}
// Cacher le champ de texte et le bouton
gtk_widget_hide(entry);
gtk_widget_hide(button);
// Afficher le label
gtk_widget_show(label);
}
// Fonction principale
int main(int argc, char *argv[]) {
gtk_init(&argc, &argv);
// Création de la fenêtre principale
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), 'Magic Text Entry');
gtk_window_set_default_size(GTK_WINDOW(window), 240, 50);
g_signal_connect(window, 'destroy', G_CALLBACK(gtk_main_quit), NULL);
// Création d'une boîte horizontale pour contenir les widgets
hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
gtk_container_add(GTK_CONTAINER(window), hbox);
// Création du champ de texte
entry = gtk_entry_new();
gtk_box_pack_start(GTK_BOX(hbox), entry, TRUE, TRUE, 0);
g_signal_connect(entry, 'activate', G_CALLBACK(on_button_clicked), NULL);
// Création du bouton OK
button = gtk_button_new_with_label('OK');
gtk_box_pack_start(GTK_BOX(hbox), button, FALSE, FALSE, 0);
g_signal_connect(button, 'clicked', G_CALLBACK(on_button_clicked), NULL);
// Création d'un label pour afficher 'BRAVO' ou 'ERREUR'
label = gtk_label_new('');
gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
gtk_widget_hide(label); // Cacher le label initialement
// Affichage de tous les widgets
gtk_widget_show_all(window);
// Démarrage de la boucle principale de GTK
gtk_main();
return 0;
}
Compiler
gcc `pkg-config --cflags --libs gtk+-3.0` -o magique magique.c
Exécuter
./magique
↑ Haut de page