lxn / walk

A Windows GUI toolkit for the Go Programming Language
Other
6.86k stars 887 forks source link

Dynamically add Buttons with OnClick Functions #419

Open djarbz opened 6 years ago

djarbz commented 6 years ago

I have the following function to generate a GUI and I want to create a number of buttons based on the number of items in an array. When the button is clicked I want to pass the appropriate struct to a function.

plants is an array of structs When I click the button, I want to pass the appropriate plant to the specified function The buttons get created properly, but they all pass the last item of the array since that was the last value of plant.

func selectQueryDynamicGUI() {
    var widgets []Widget
    for _, plant := range plants {
        widget := PushButton{
            Text: plant.Name,
            OnClicked: func() {
                generateReport(plant)
            },
        }
        widgets = append(widgets, widget)
    }
    window := MainWindow{
        Title: "Window Title",
        MinSize: Size{
            Width:  600,
            Height: 400,
        },
        Layout: VBox{},
    }
    window.Children = widgets
    window.Run()
}
lxn commented 6 years ago

Sounds similar to this: https://github.com/golang/go/wiki/CommonMistakes

djarbz commented 6 years ago

Thank you! I'll look closer at that, when I originally looked I discounted it because I was not using Goroutines.