要求和最终效果

参考任意一篇 Fyne 官方文档, 可以看到写法:

func makeUI() (*widget.Label, *widget.Entry) {
  return widget.NewLabel("Hello world!"),
    widget.NewEntry()
}

func main() {
  a := app.New()
  w := a.NewWindow("Hello Person")

  w.SetContent(container.NewVBox(makeUI()))
  w.ShowAndRun()
}

所以, 我们也会写makeUI()

优势

  1. 逻辑清晰
  2. 便于测试

读法的小提示

*... 可以读成Pointer to ...

成品代码

package main

import (
 "fmt"

 "fyne.io/fyne/v2"
 "fyne.io/fyne/v2/app"
 "fyne.io/fyne/v2/container"
 "fyne.io/fyne/v2/widget"
)

type App struct{
 output *widget.Label
}

var myApp App

func (app *App) makeUI()(*widget.Label, *widget.Entry, *widget.Button, *widget.Label, *widget.Button ){
 output := widget.NewLabel("Gopher Go go go")
 entry:= widget.NewEntry()
 btn := widget.NewButton("Click!", func() {
  output.SetText(entry.Text)
 })

 app.output = output

 btn.Importance = widget.HighImportance

 number := 0
 count := widget.NewLabel(fmt.Sprintf("Current Number: %d", number))
 incrementbtn := widget.NewButton("Click again!", func() {
  number++
  count.SetText(fmt.Sprintf("Current Number: %d", number))
 })

 incrementbtn.Importance = widget.DangerImportance

 return output, entry, btn, count, incrementbtn
}

func main() {
 a := app.New()
 w := a.NewWindow("Gopher Go go go!02")

 output, entry, btn, count, incrementbtn := myApp.makeUI()

 w.SetContent(container.NewVBox(output, entry, btn, count, incrementbtn))

 w.Resize(fyne.Size{Width: 1600, Height: 1000})

 w.ShowAndRun()
}