如果 window 关闭,gWidgets 如何处理无效引用

gWidgets how to handle invalid reference if window is closed

下面gWidgets例子中的情况我该如何处理?

我试图用这个小的图形用户界面实现的是有一个可以更新的子window。它运作良好。但是,如果用户通过单击 'X' 关闭 'Click history' window,则会出现错误:

Error: attempt to call 'GetBuffer' on invalid reference 'view'

看来子window的reference/pointer丢失了。我尝试了各种策略来解决问题。例如使用 tryCatch 并重新创建 window。这导致每次点击都会打开一个新的 window。能否以某种方式保留引用?

更新:我在 Windows 7 系统上使用 R 3.2.2 和 gWidgetsRGtk2 工具包。

mainWindow <- function(){

  require(gWidgets)

  # This works well until the log window is closed.
  # Next click gives this error:
  # Error: attempt to call 'GetBuffer' on invalid reference 'view'

  w_main <- gwindow(title="Main", visible=TRUE)
  b_time <- gbutton("Show time!", container=w_main)
  w_time <- gwindow(title="Click history", visible=FALSE)
  t_time <- gtext("", container=w_time)

  addHandlerChanged(b_time, handler = function(h, ...) {

    # Log click.
    insert(t_time, paste(date()))

    # Show window.
    visible(w_time) <- TRUE  

  } )

}

更新 2:根据 jverzani 的建议实施似乎工作正常。事实上我试过类似的东西,但我想我忘记了 <<-

mainWindow <- function(){

  require(gWidgets)

  # This works well also when the log window has been closed!

  w_main <- gwindow(title="Main", visible=TRUE)
  b_time <- gbutton("Show time!", container=w_main)
  w_time <- gwindow(title="Click history", visible=FALSE)
  t_time <- gtext("", container=w_time)
  closed <- FALSE

  addHandlerChanged(b_time, handler = function(h, ...) {

    if(closed){
       # Re-create window.
       w_time <<- gwindow(title="Click history", visible=FALSE)
       t_time <<- gtext("", container=w_time)
       closed <<- FALSE
    }

    # Log click.
    insert(t_time, paste(date()))

    # Show window.
    visible(w_time) <- TRUE  

  } )

  addHandlerDestroy(w_time, handler = function(h, ...) {

    # Subwindow closed!
    closed <<- TRUE

  } )

}

这是@jverzani提供的解决方案

mainWindow <- function(){

  require(gWidgets)

  # This works well also when the log window has been closed!

  w_main <- gwindow(title="Main", visible=TRUE)
  b_time <- gbutton("Show time!", container=w_main)
  w_time <- gwindow(title="Click history", visible=FALSE)
  t_time <- gtext("", container=w_time)

  addHandlerChanged(b_time, handler = function(h, ...) {

    if(!isExtant(w_time)){
      # Re-create window.
      w_time <<- gwindow(title="Click history", visible=FALSE)
      t_time <<- gtext("", container=w_time)
    }

    # Log click.
    insert(t_time, paste(date()))

    # Show window.
    visible(w_time) <- TRUE  

  } )

}