在 gWidgets2 中切换一个 gbutton

Toggle a gbutton in gWidgets2

我正在 gWidgets2 中创建一个 gbutton,当它被点击时,它将在 "go" 和 "stop" 之间切换。

我正在关注这个例子:

我的代码:

library(gWidgets2)
library(gWidgets2RGtk2)
options(guiToolkit="RGtk2")

w= gwindow()
g1 <- ggroup(horizontal=TRUE, cont=w)
icon <- gbutton('go', container = g1)
state <- FALSE # a global
changeState <- function(h,...) {
  if(state) {
    svalue(icon) <- "go"
  } else {
    svalue(icon) <- "stop"
  }
  state <<- !state
}
addHandlerClicked(icon, handler=changeState)

它创建一个按钮并在单击时在 "go" 和 "stop" 之间切换。但问题是我必须点击两次才能切换。我希望它应该在 "go" 和 "stop" 之间一次单击切换。

You can use blockHandlers() and unblockHandlers() functions to avoid this issue.

w= gwindow()
g1 <- ggroup(horizontal=FALSE, cont=w)
icon <- gbutton("go", container = g1)
#icon <- gimage(reject,cont=g1)
state <- FALSE # a global
addHandlerClicked(icon, function(h,...) {
  #
  if(!state) {
    blockHandlers(icon)
    svalue(icon) <- "stop"
    unblockHandlers(icon)
  } else {
    blockHandlers(icon)
    svalue(icon) <- "go"
    unblockHandlers(icon)
  }
  state <<- !state
})

I tried this and it works for me.