Fyne传递不同参数给多个按钮

huangapple go评论78阅读模式
英文:

Fyne passing changing arguments to multiple buttons

问题

我在使用Fyne时遇到了一个问题,无法将动态参数传递给按钮回调函数。我想创建一个按钮列表,当点击按钮时,会调用一个带有特定字符串参数的函数:

  clients := []fyne.CanvasObject{}
  for _, uuidStr := range uuidStrs {
    clientBtn := widget.NewButton(uuidStr, func() { server.selectClient(uuidStr)})
    clients = append(clients, clientBtn)
  } 
  clientsListed := container.New(layout.NewGridLayout(1), clients...)

问题是,当点击任何一个按钮时,它们都会选择最后一个客户端,即调用server.selectClient(uuidStr),其中uuidStr始终为uuidStrs[len(uuidStrs)-1],但我希望每个按钮都传递一个唯一的uuidStr。所有的按钮显示了正确的字符串,但在回调中没有传递正确的字符串。

如何使按钮在点击时选择显示的客户端呢?

英文:

I'm having an issue with passing dynamic arguments to a button callback with Fyne. I'm trying to create a list of buttons that when clicked will call a function with a specific string argument:

  clients := []fyne.CanvasObject{}
  for _, uuidStr := range uuidStrs {
    clientBtn := widget.NewButton(uuidStr, func() { server.selectClient(uuidStr))
    clients = append(clients, clientBtn)
  } 
  clientsListed := container.New(layout.NewGridLayout(1), clients...)

The issue is that all of the buttons, when clicked, will select the last client e.g. it will call server.selectClient(uuidStr) where uuidStr is always uuidStrs[len(uuidStrs)-1], but I want each button to pass in a unique uuidStr. All of the buttons display the correct string, but don't pass the correct string in the callback.

How can I get the buttons, when clicked, to select the client it displays?

答案1

得分: 0

这是由于Go在循环迭代中如何重用变量的原因。你需要"捕获"这个值,以便按钮回调函数得到正确的值。如下所示:

  clients := []fyne.CanvasObject{}
  for _, uuidStr := range uuidStrs {
    uuid := uuidStr
    clientBtn := widget.NewButton(uuidStr, func() { server.selectClient(uuid)})
    clients = append(clients, clientBtn)
  } 
  clientsListed := container.New(layout.NewGridLayout(1), clients...)
英文:

This is due to how Go re-uses variables in loop iterations. You need to "capture" the value so that the button callback func gets the right value. As follows:

  clients := []fyne.CanvasObject{}
  for _, uuidStr := range uuidStrs {
    uuid := uuidStr
    clientBtn := widget.NewButton(uuidStr, func() { server.selectClient(uuid))
    clients = append(clients, clientBtn)
  } 
  clientsListed := container.New(layout.NewGridLayout(1), clients...)

huangapple
  • 本文由 发表于 2021年6月23日 18:00:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/68097646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定