Build

A basic hello world application with Go-GTK is similar to the previous one we looked at: we create a window, add a vertical box, and append a label and a button. The following code sample should be straightforward, but we'll look in more detail at some of the specifics:

package main

import "github.com/mattn/go-gtk/gtk"

func main() {
gtk.Init(nil)
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
window.SetTitle("Hello")

quit := gtk.NewButton()
quit.SetLabel("Quit")
quit.Clicked(func() {
gtk.MainQuit()
})

vbox := gtk.NewVBox(false, 3)
vbox.Add(gtk.NewLabel("Hello World!"))
vbox.Add(quit)

window.Add(vbox)
window.SetBorderWidth(3)
window.ShowAll()
gtk.Main()
}

Firstly, we import the github.com/mattn/go-gtk/gtk package for the main GTK namespace. The Go-GTK project is split into various namespaces, which we will explore further later in this chapter. Next, the window is created with gtk.NewWindow()—note that the parameter to this function is the window type, not its title (which is set next with SetTitle()). The Quit button is created with gtk.NewButton() and the text is set with SetLabel(), and then we add the code to quit using the Clicked() function, passing an anonymous function.

The layout is managed by a vertical box that's created with gtk.NewVBox(bool, int). The parameters to this message are firstly a homogeneous bool flag (determining whether all child components should be the same size), and secondly an int value for spacing (this specifies the amount of padding to place between each child element).

Lastly, the content is set on the window using Add() and we set a padding consistent with the spacing in the VBox using SetBorderWidth(3). Calling ShowAll() sets the window and its contents to be shown (as widgets are hidden by default), and the call to gtk.Main() runs the application to render and respond to user input.

You can build this using the standard go build hello.go command, which should create a runnable file for your operating system:

Building the hello world example with Go-GTK
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.225