使用Golang和Fyne创建桌面应用程序

今天我们将在Golang上开发桌面应用程序


对于golang程序员来说,开发golang桌面应用程序不是一项典型的任务。 Google并没有太多现成的开源库可以根据golang桌面的要求来解决它,以下是一些示例:

  1. k
  2. 费恩
  3. ui

之所以选择Fyne,是因为该项目的github存储库包含最多数量的星星,并且它还支持臭名昭著的Material设计。

让我们看看显示它提供给我们的界面有哪些选项。

该框提供了以下小部件:

  • 按钮
  • 一个容器(用于将子小部件分组并水平或垂直定向它们)。
  • 复选框,用于输入文本或密码的字段。
  • 表格和组。
  • 超链接。
  • 图标。
  • 标签。
  • 进度条。
  • 可滚动的容器。
  • 开关。
  • 选择
  • 标签。
  • 工具栏。

如果在界面元素中找不到必要的元素,则可以使用简单的API来实现自定义窗口小部件。

让我们尝试编写一个golang gui应用程序,以使用Fyne显示未来几天的天气预报。完整的应用程序代码可以在github上的链接上找到。

首先,在Golang上创建一个空项目并安装Fyne。

go get fyne.io/fyne

由于该应用程序将显示天气信息,因此您需要获取此信息。为此,请转到开放天气地图API。

func getWeatherForecast(result interface{}) error {
  var url = fmt.Sprintf("https://api.openweathermap.org/data/2.5/forecast?q=Voronezh&cnt=4&units=metric&appid=%s", openWeatherMapApiKey) //    
  response, err := http.Get(url)
  if err != nil {
     fmt.Print(err)
  }
  defer response.Body.Close()
  return json.NewDecoder(response.Body).Decode(result)
}

要存储数据,您可以使用以下结构(我只留下了API返回的某些字段),值得注意的是该结构的所有字段都大写,但在API响应中用一个小字段描述了这一事实。

type WeatherInfo struct {
  List []WeatherListItem `json:list`
}

type WeatherListItem struct {
  Dt      int           `json:dt`
  Main    WeatherMain   `json:main`
  Weather []WeatherType `json:weather`
}

type WeatherMain struct {
  Temp      float32 `json:temp`
  FeelsLike float32 `json:feels_like`
  Humidity  int     `json:humidity`
}

type WeatherType struct {
  Icon string `json:icon`
}

现在我们可以以结构形式接收天气数据。它仍然可以实现golang桌面应用程序界面。

func setupUi(weatherInfo WeatherInfo) {
  app := app.New()

  w := app.NewWindow("   ")

  var vBox = widget.NewVBox() //        

  for i := 0; i < len(weatherInfo.List); i++ {
     var weatherForDay = weatherInfo.List[i] //     
     var weatherMainGroup = widget.NewVBox(
        widget.NewLabel(fmt.Sprintf(": %.2f °C", weatherForDay.Main.Temp)),
        widget.NewLabel(fmt.Sprintf(" : %.2f °C", weatherForDay.Main.FeelsLike)),
        widget.NewLabel(fmt.Sprintf(": %d%%", weatherForDay.Main.Humidity)),
     ) //  3    

     var weatherTypeGroup = widget.NewVBox()
     for weatherTypeI := 0; weatherTypeI < len(weatherForDay.Weather); weatherTypeI++ {
        var resource, _ = fyne.LoadResourceFromURLString(fmt.Sprintf("http://openweathermap.org/img/wn/%s.png", weatherForDay.Weather[weatherTypeI].Icon)) //   ,   
        var icon = widget.NewIcon(resource)
        weatherTypeGroup.Append(icon)
     }

     var time = time2.Unix(int64(weatherInfo.List[i].Dt), 0).String()
     vBox.Append(widget.NewGroup(time)) 
     vBox.Append(widget.NewHBox(weatherMainGroup, weatherTypeGroup))
  }
  vBox.Append(widget.NewButton("", func() {
     app.Quit()
  }))

  w.SetContent(vBox) //    

  w.ShowAndRun() //   
}

在这里,我们创建了小部件,将其填充数据并将其收集到组中以组织它们的显示顺序。

做完了

它仅用于运行应用程序并查看其外观。由于该框架是跨平台的,因此您可以在Windows,macOS和Linux上运行它。

图片
启动了golang mac os应用程序

图片
,它看起来像一个golang Windows应用程序

。结果,结果是创建了一个简单的跨平台golang桌面应用程序,并尝试使用Fyne。不幸的是,作为开发现代桌面应用程序的合适语言,go几乎不值得考虑,但是,在实践中接触到一些新奇的东西总是很有趣的。

谢谢大家的关注。

All Articles