1

I am creating a gbutton in gWidgets2 which will toggle between "go" and "stop" when it will be clicked.

I am following this example: toggling a group of icons in gWidgets

My Code:

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)

It creates a button and toggle between "go" and "stop" when it is clicked. But the problem is I have to click two times to toggle. I want it should toggle between "go" and "stop" on one click.

Ekanshu
  • 69
  • 1
  • 11
  • Hmm, this is odd. For some reason the callback is being called twice. I can replicate my mac. I wonder if this is OS specific. What OS are you using? (This works as intended under tcltk) – jverzani Aug 30 '19 at 16:20
  • I am using ubuntu. – Ekanshu Aug 31 '19 at 05:32
  • My guess is svalue<- invokes the changehandler, so it is called twice. To avoid that, annoyingly, there is block_handler and unblock_handler functions that can wrap the code within the callback. – jverzani Aug 31 '19 at 11:58
  • Hi jverzani, It worked for me. Thanks a lot. – Ekanshu Sep 02 '19 at 06:54

1 Answers1

1
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.
Sandeep Dahake
  • 188
  • 1
  • 11
  • Great. A bit cleaner to wrap the if/else block, rather than each result, but that is the pattern to use. – jverzani Sep 02 '19 at 21:04