DEV Community

Luis Ángel Méndez Gort
Luis Ángel Méndez Gort

Posted on

F# đŸ€ GTK4

#r "nuget: GirCore.Gtk-4.0,0.5.0"

open System
open Gtk

let label () =
  let label = new Label()
  label.SetText "hello"
  label

let button (label: Label) =
  let button = new Button()
  button.SetLabel "click me"
  let mutable counter = 0

  let clickHnd (_: Button) (_: EventArgs) =
    label.SetText $"hello {counter}"
    counter <- counter + 1

  button.add_OnClicked (new GObject.SignalHandler<Button>(clickHnd))
  button

let box () =
  let box = new Box()
  box.SetOrientation Orientation.Vertical
  box.SetHomogeneous true

  let l = label ()
  box.Append l
  button l |> box.Append
  box

let onActivateApp (sender: Gio.Application) (_: EventArgs) =
  let window = ApplicationWindow.New(sender :?> Application)
  window.Title <- "Gtk4 Window"
  window.SetDefaultSize(300, 300)
  window.SetChild(box ())
  window.Show()

let application = Application.New("org.gir.core", Gio.ApplicationFlags.FlagsNone)
application.add_OnActivate (new GObject.SignalHandler<Gio.Application>(onActivateApp))
application.RunWithSynchronizationContext(null)
Enter fullscreen mode Exit fullscreen mode

The above code does the following:

  • creates a 300px × 300px window with GTK4
  • the window title is "Gtk4 Window"
  • it has a button and a label controls
  • when clicking the button the label text changes to show the value of a counter that increases with each click

Notice the code is an F# script, which means it doesn't need a main function and can run by putting the code in an .fsx file and then running it with dotnet fsi your_file.fsx

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
giullianosep profile image
Giulliano Ferreira ‱

Is there any advantage of using GTK instead of something like Avalonia?

Collapse
 
lamg profile image
Luis Ángel MĂ©ndez Gort ‱

A simple window in GTK seems to be more resource efficient than one in Avalonia. On the other hand Avalonia has functional wrappers that might be more appealing to some people.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay