GTK+ 示例/GTK+/Hello World
外观
这个小型教程演示了如何创建一个带有单个按钮的简单窗口。当按钮被点击时,按钮上的标签内容将被打印到标准输出。
标签被包装到按钮中,按钮又被包装到窗口中。
首先,您必须包含 gtk 头文件。
#include<gtk/gtk.h>
接下来,定义了两个**回调函数**原型,一个用于关闭窗口,另一个用于点击按钮。回调函数基本上是调用由低级代码(在本例中是 GTK 本身)通过传递函数地址调用的函数。
static gint delete_callback(GtkWidget* w, GdkEventAny* e, gpointer data);
static void button_callback(GtkWidget* w ,gpointer data);
#include<gtk/gtk.h>
static gint delete_callback(GtkWidget* w, GdkEventAny* e, gpointer data);
static void button_callback(GtkWidget* w ,gpointer data);
int main(int argc, char* argv[])
{
GtkWidget* window;
GtkWidget* button;
GtkWidget* label;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
button = gtk_button_new();
label = gtk_label_new("Hello World");
gtk_container_add(GTK_CONTAINER(button),label);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_window_set_title(GTK_WINDOW(window), " Hello World");
gtk_container_set_border_width(GTK_CONTAINER(button),10);
gtk_window_set_default_size(GTK_WINDOW(window),400,400);
gtk_signal_connect(GTK_OBJECT(window),
"delete_event",
GTK_SIGNAL_FUNC(delete_callback),
NULL);
gtk_signal_connect(GTK_OBJECT(button),
"clicked",
GTK_SIGNAL_FUNC(button_callback),
label);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
static gint delete_callback(GtkWidget* w, GdkEventAny* e, gpointer data)
{
gtk_main_quit();
}
static void button_callback(GtkWidget* w ,gpointer data)
{
GtkWidget* label;
gchar* text;
label = GTK_WIDGET(data);
gtk_label_get(GTK_LABEL(label), &text);
printf("%s \n", text);
}
#!/usr/bin/perl
use Gtk2 "-init";
use warnings;
use strict;
my $window = new Gtk2::Window;
my $button = new Gtk2::Button('Reset');
$window->add($button);
$window->set_title("Hello, world!");
$button->set_border_width(10);
$window->set_default_size(400,400);
$window->signal_connect("delete_event", \&delete_callback);
$button->signal_connect("clicked", \&button_callback);
$window->show_all;
Gtk2->main;
sub delete_callback{
Gtk2->main_quit;
}
sub button_callback{
my $label = $button->get_child;
$label->set_text ("Support your local bakery");
$window->show_all;
}
module Main where
import Graphics.UI.Gtk
main :: IO ()
main = do
initGUI
window ← windowNew
button ← buttonNewWithLabel "Reset"
set window [windowTitle := "Hello",
windowDefaultWidth := 400,
windowDefaultHeight := 400,
containerChild := button]
set button [containerBorderWidth := 10]
onClicked button $ buttonSetLabel button "Support your local pâtisserie"
onDestroy window mainQuit
widgetShowAll window
mainGUI