英文:
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...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论