Text labels in Tk windows

Text labels in Tk windows

James Wettenhall & Philippe Grosjean bio photo By James Wettenhall & Philippe Grosjean

Text labels can easily be added to a toplevel window using the tklabel() or ttklable() functions in tcltk, or the tk2label() function in tcltk2. It is not necessary to assign the result of tklabel() to a variable unless you want to change the text later on.

win1 <- tktoplevel()
tkgrid(tk2label(win1, text = "This is a text label"))


The following code illustrates how the text in a label can be linked to a variable:

win2 <- tktoplevel()
labelText <- tclVar("This is a text label")
win2$env$label <- tk2label(win2, textvariable = labelText)

changeText <- function()
  tclvalue(labelText) <- "This text label has changed!"
win2$env$butChange <- tk2button(win2, text = "Change text label", command = changeText)

Running the R code above gives the following window:

label changeable

Pressing the “Change text label” button, gives the following window:

label changed