função ns nullwindow this.window
Transcrição
função ns nullwindow this.window
O pacote tcltk Prof. Marcos Oliveira Prates Departamento de Estatística – UFMG [email protected] Slides by Prof. Marcelo A Costa “The windows, icons, and menus, as well as other graphical controls such as buttons, sliders and text fields, have come to be known as widgets”. Widget type hierarchy 2 Cada widget tem um “parent”, no qual está contido, exceto a “top-level window”, que não possui “parent”, e funciona como “root of the tree” (raiz da árvore. “Child widgets” estão contidas dentro do retângulo de seus “parents”. Widgets que contém outras widgets são clamadas de “containers”. Combinando widgets “primitivas” como “labels” e “icons” dentro de “containers”, permite a criação de interfaces mais complexas. Um “container” é responsável pela alocação de espaço para seus “children” Window Vertical Box Horizontal Box Image Label Horizontal Box List View Horizontal Box Button Button 3 file.choose() choose.dir() 4 require(tcltk) tkmessageBox(message="Do you want to save before quitting?", icon="question", type="yesnocancel", default="yes") ## icon = "info", "error", "warning", "question". ## type = "ok", "okcancel", "retrycancel", "yesno", or ## "yesnocancel" 5 # Load the tcltk package require(tcltk) # Create a new toplevel window tt <- tktoplevel() ## Define o titulo da interface tkwm.title(tt,"A parabola") # Create a button whose function (command) is to destroy the window OK.but <- tkbutton(tt,text="OK", command = function() tkdestroy(tt) ) # Place the button on the window, using the grid manager. tkgrid(OK.but) # Now, bring the window to the focus, using tkfocus. (This will not work # if the code is run from RGui, because the focus will automatically # return to RGui, but it will work if the code is copied and pasted into # a script file and run using # Rterm < scriptfile.R > scriptfile.Rout tkfocus(tt) 6 # Load the tcltk package require(tcltk) # Create a new toplevel window tt <- tktoplevel() # Give the window a title tkwm.title(tt,"Simple Dialog") # Create a variable to keep track of the state of the dialog window: # If the window is active, done = 0 # If the window has been closed using the OK button, done = 1 # If the window has been closed using the Cancel button or destroyed, done = 2 done <- tclVar(0) # Create two buttons and for each one, set the value of the done variable # to an appropriate value. OK.but <- tkbutton(tt,text=" OK ", command=function() tclvalue(done)<-1) Cancel.but <- tkbutton(tt,text="Cancel",command=function() tclvalue(done)<-2) # Place the two buttons on the same row in their assigned window (tt). tkgrid(OK.but,Cancel.but) # Capture the event "Destroy" (e.g. Alt-F4 in Windows) and when this happens, # assign 2 to done. tkbind(tt,"<Destroy>",function() tclvalue(done)<-2) tkfocus(tt) # Do not proceed with the following code until the variable done is non-zero. # (But other processes can still run, i.e. the system is not frozen.) tkwait.variable(done) 7 # # # # The variable done is now non-zero, so we would like to record its value before destroying the window tt. If we destroy it first, then done will be set to 2 because of our earlier binding, but we want to determine whether the user pressed OK (i.e. see whether done is equal to 1). doneVal <- as.integer(tclvalue(done)) tkdestroy(tt) if(doneVal==1) tkmessageBox(message="You pressed OK!") if(doneVal==2) tkmessageBox(message="You either pressed Cancel or destroyed the dialog!") Outro exemplo: http://bioinf.wehi.edu.au/~wettenhall/RTclTkExamples/modalDialog.html 8 # Load the tcltk package require(tcltk) PressedOK <- function() { tkmessageBox(message="You pressed OK!") } tt <- tktoplevel() OK.but <- tkbutton(tt,text="OK",command=PressedOK) tkgrid(OK.but) tkfocus(tt) 9 require(tcltk) tt <- tktoplevel() labelText <- tclVar("This is a text label") label1 <- tklabel(tt,text=tclvalue(labelText)) tkconfigure(label1 ,textvariable=labelText) tkgrid(label1) ChangeText <- function() tclvalue(labelText) <- "This text label has changed! " ChangeText.but <- tkbutton(tt, text="Change text label", command=ChangeText) tkgrid(ChangeText.but) 10 ## Define uma fonte fontTextLabel <- tkfont.create(family="courier",size=11) changeText.but <- tkbutton(tt, text="Change text label", command=ChangeText, width=10, font=fontTextLabel) 11 require(tcltk) tt <- tktoplevel() rb1 <- tkradiobutton(tt) rb2 <- tkradiobutton(tt) rbValue <- tclVar("oranges") tkconfigure(rb1,variable=rbValue,value="apples") tkconfigure(rb2,variable=rbValue,value="oranges") tkgrid(tklabel(tt,text="Which do you prefer?")) tkgrid(tklabel(tt,text="Apples "),rb1) tkgrid(tklabel(tt,text="Oranges "),rb2) OnOK <- function() { rbVal <- as.character(tclvalue(rbValue)) tkdestroy(tt) if (rbVal=="apples") tkmessageBox(message="Good choice! An apple a day keeps the doctor away!") if (rbVal=="oranges") tkmessageBox(message="Good choice! Oranges are full of Vitamin C!") } OK.but <- tkbutton(tt,text="OK",command=OnOK) tkgrid(OK.but) tkfocus(tt) 12 require(tcltk) tt <- tktoplevel() cb <- tkcheckbutton(tt) cbValue <- tclVar(“1") tkconfigure(cb,variable=cbValue) tkgrid(tklabel(tt,text="I like R TclTk "),cb) OnOK <- function() { cbVal <- as.character(tclvalue(cbValue)) tkdestroy(tt) if (cbVal=="1") tkmessageBox(message="So do I!") if (cbVal=="0") tkmessageBox(message="You forgot to check the box!",icon="warning") } OK.but <- tkbutton(tt,text="OK",command=OnOK) tkgrid(OK.but) tkfocus(tt) 13 14 require(tcltk) tt <- tktoplevel() txt <- tktext(tt, height=5) ## see "http://www.tkdocs.com/tutorial/index.html" tkpack(txt) ## tclvalue(tkget(txt,"0.0","end")) 15 Implemente uma interface gráfica para a função read.table() 16 require(tcltk) tt <- tktoplevel() combo.names <- c("opcao 1", "opcao 2", "opcao 3") ##Cria o ComboBox e define a 1a opcao como selecionada comboBoxVar <- tclVar() ## Define o primeiro nome como a "referencia" tclvalue(comboBoxVar) <- combo.names[1] comboBox01 <- ttkcombobox(tt, values=combo.names, textvariable=comboBoxVar) tkgrid(comboBox01) tkfocus(tt) 17 require(tcltk) tt <- tktoplevel() frameOverall <- tkframe(tt) frameUpper <- tkframe(frameOverall, relief="groove",borderwidth=2) tkgrid(tklabel(frameUpper,text="Text in the upper frame")) frameLower <- tkframe(frameOverall,relief="groove",borderwidth=2) tkgrid(tklabel(frameLower,text="Text in the lower frame")) tkgrid(frameUpper) tkgrid( tklabel(frameOverall, text="Text between the upper and lower frames")) tkgrid(frameLower) tkgrid(frameOverall) 18 Borders You can display a border around the frame widget; you see this a lot where you might have a part of the user interface looking "sunken" or "raised" in relation to its surroundings. To do this, you need to set the "borderwidth" configuration option (which defaults to 0, so no border), as well as the "relief" option, which specifies the visual appearance of the border: "flat" (default), "raised", "sunken", "solid", "ridge", or "groove". http://www.tkdocs.com/tutorial/widgets.html#frame19 require(tcltk) tt <- tktoplevel() frame.A <- ttklabelframe(tt, text="Selecione uma opcao“) combo.names <- c("opcao 1", "opcao 2", "opcao 3") ##Cria o ComboBox e define a 1a opcao como selecionada comboBoxVar <- tclVar() ## Define o primeiro nome como a "referencia" tclvalue(comboBoxVar) <- combo.names[1] comboBox01 <- ttkcombobox(frame.A, values=combo.names, textvariable=comboBoxVar) tkgrid(comboBox01) tkgrid(frame.A) tkfocus(tt) 20 require(tcltk) tt<-tktoplevel() Name <- tclVar("") entry.Name <-tkentry(tt,width="20",textvariable=Name) tkgrid(tklabel(tt,text="Please enter your first name.")) tkgrid(entry.Name) OnOK <- function() { NameVal <- tclvalue(Name) tkdestroy(tt) msg <- paste("You have a nice name,",NameVal) tkmessageBox(message=msg) } OK.but <-tkbutton(tt,text=" OK ",command=OnOK) tkbind(entry.Name, "<Return>",OnOK) tkgrid(OK.but) tkfocus(tt) 21 Crie uma interface gráfica para a seguinte função do R: plot(x, y, type=c("l", "p"), main=XXX, xlab=XXX, ylab=XXX, cex=c(1,2,3), lwd=c(1,2,3)) Use a base de dados: “centers.txt” 22 require(tcltk) tclRequire("BWidget") # Type B or C in the text entry field and press the button "Get values". # This will update the values in the dropdown field tt <- tktoplevel() tkwm.title(tt,"Test GUI") tkgrid(tklabel(tt,text="Test label")) ttframe<-tkframe(tt,relief="groove",borderwidth=2) x<<-cbind(x=rep(LETTERS[1:3],each=4),y=1:12) v<-tclVar("A") z<-x[x[,1]==tclvalue(v),2] entry.v<-tkentry(ttframe,width="30",textvariable=v) label.v<-tklabel(ttframe,text=tclvalue(v)) tkconfigure(label.v,textvariable=v) tkgrid(entry.v) tkgrid(tklabel(ttframe,text="")) tkgrid(label.v) getVal<-function(){ z<-x[x[,1]==tclvalue(v),2] tkconfigure(comboBox,values=z) } comboBox<-tkwidget(ttframe,"ComboBox",editable=FALSE,values=z) button.getValues<-tkbutton(ttframe,text="Get values",command=getVal) tkgrid(comboBox,button.getValues) tkgrid(ttframe) tkgrid(tklabel(tt,text="")) tkfocus(tt) 23 24-06-2010 22:50, Greg Snow: > Create and pack a combo box (possibly with dummy entries), then when you want to dynamically change the options call tkconfigure( comboboxobject, values = vectorwithvalues ) > > I think that should work, but have not tested it specifically for your case (my tkexamp function in the TeachingDemos package does something like this, but not after an entry has been filled). https://stat.ethz.ch/pipermail/r-sig-gui/2010-June/001059.html 24 require(tcltk) tt <- tktoplevel() ## Cria uma variavel com o valor "inicial" SliderValue <- tclVar("50") SliderValueLabel <- tklabel(tt, text=as.character(tclvalue(SliderValue))) tkgrid(tklabel(tt,text="Slider Value : "), SliderValueLabel, tklabel(tt,text="%")) ## Vincula a variavel ao nome tkconfigure(SliderValueLabel, textvariable=SliderValue) ## Cria o slider slider <- tkscale(tt, from=100, to=0, showvalue=F, variable=SliderValue, resolution=1, orient="vertical") tkgrid(slider) tkfocus(tt) 25 x <- rnorm(100) hist(x, prob=TRUE) lines(density(x, bw=0.3), lwd=2, col='red') rug(x) 0.0 0.1 0.2 Density 0.3 0.4 Histogram of x -2 -1 0 1 x 2 3 26 aula12_tcltk_exemplo02.R 27 density(x, bw = "nrd0", adjust = 1, kernel = c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine"), weights = NULL, window = kernel, width, give.Rkern = FALSE, n = 512, from, to, cut = 3, na.rm = FALSE, ...) 28 require(tcltk) tt <- tktoplevel() tkgrid(tklabel(tt,text="Here is a centered string of text.")) tkgrid(tklabel(tt,text="Left"),sticky="w") tkgrid(tklabel(tt,text="Right"),sticky="e") tkgrid(tklabel(tt,text=" ")) # Blank line tkgrid(tklabel(tt,text=" ")) # Blank line tkgrid(tklabel(tt,text="Here is a much longer string of text, which takes up two columns."),columnspan=2) LeftLabel <- tklabel(tt,text="Left") # Here, Left and Right labels RightLabel <- tklabel(tt,text="Right") # are in separate rows. tkgrid(LeftLabel,RightLabel) tkgrid.configure(LeftLabel,sticky="w") tkgrid.configure(RightLabel,sticky="e") LeftLabel2 <- tklabel(tt,text="LeftAligned") RightLabel2 <- tklabel(tt,text="RightAligned") tkgrid(RightLabel2,LeftLabel2) # Here, Left and Right labels are in the same row tkgrid.configure(RightLabel2,sticky="e") tkgrid.configure(LeftLabel2,sticky="w") tkgrid(tklabel(tt,text=" ")) # Blank line tkgrid(tklabel(tt,text=" ")) # Blank line tkgrid(tklabel(tt,text="This sentence takes up two rows,\n but only one column"),rowspan=2) tkfocus(tt) 29 require(tcltk) library(tkrplot) ## Define o tamanho horizontal e vertical ## da area de desenho Myhscale <- 1.5 # Horizontal scaling Myvscale <- 1.5 # Vertical scaling plotFunction <- function() { x <- -100:100 y <- x^2 plot(x,y,main="A parabola",bg="white") } tt <- tktoplevel() ## Define o titulo da interface tkwm.title(tt, "A parabola") ## Cria a area de plotagem img <- tkrplot(tt, fun = plotFunction, hscale=Myhscale, vscale=Myvscale) tkgrid(img) 30 It is worth noting that tkrplot places the graph on the clipboard (in Windows or X11) before it plots it on the window. This means that once a graph has been plotted, it can easily be pasted into another program. However, if a second graph is plotted, the first graph will be lost from the clipboard, so the software developer may wish to include a "Copy to Clipboard" button or menu item on the tkrplot graph window, so that the user can come back to it later and copy it to the clipboard. This can be done using the tkrreplot function as follows: 31 require(tcltk) library(tkrplot) Myhscale <- 1.5 Myvscale <- 1.5 # Horizontal scaling # Vertical scaling plotFunction <- function() { params <- par(bg="white") x <- -100:100 y <- x^2 plot(x,y,main="A parabola") par(params) } tt <- tktoplevel() tkwm.title(tt,"A parabola") img <- tkrplot(tt,fun=plotFunction,hscale=Myhscale,vscale=Myvscale) CopyToClip <- function() { tkrreplot(img) } copy.but <- tkbutton(tt,text="Copy to Clipboard",command=CopyToClip) tkgrid(img) tkgrid(copy.but) 32 tt = tktoplevel() ## Especificando a funcao do botao destroi = function() {tkdestroy(tt)} ## Lendo a imagem em formato "gif" img = tkimage.create("photo", file = "2014WCup.gif") ## Finalmente criamos o botao: botao = ttkbutton(tt, image = img, command = destroi) ## Colocamos o botao na janela tkgrid(botao) 33 tkbutton(parent, ...) tkcanvas(parent, ...) tkcheckbutton(parent, ...) tkentry(parent, ...) ttkentry(parent, ...) tkframe(parent, ...) tklabel(parent, ...) tklistbox(parent, ...) tkmenu(parent, ...) tkmenubutton(parent, ...) tkmessage(parent, ...) tkradiobutton(parent, ...) tkscale(parent, ...) tkscrollbar(parent, ...) tktext(parent, ...) tktoplevel(parent = .TkRoot, ...) ttkbutton(parent, ...) ttkcheckbutton(parent, ...) ttkcombobox(parent, ...) ttkframe(parent, ...) ttkimage(parent, ...) ttklabel(parent, ...) ttklabelframe(parent, ...) ttkmenubutton(parent, ...) ttknotebook(parent, ...) ttkpanedwindow(parent, ...) ttkprogressbar(parent, ...) ttkradiobutton(parent, ...) ttkscrollbar(parent, ...) ttkseparator(parent, ...) ttksizegrip(parent, ...) ttktreeview(parent, ...) 34 rm(list=ls(all=TRUE)) library(tcltk) tt <- tktoplevel() tkwm.title(tt,"ttknotebook example") tkgrid(tklabel(tt,text="Uso de ttknotebook:")) Notebook <- ttknotebook(tt) frame01 <- tkframe(Notebook) texto01 <-tklabel(frame01, text="Texto para a 1a opcao") tkgrid(texto01) frame02 <- tkframe(Notebook) texto02 <-tklabel(frame02, text="Texto para a 2a opcao") tkgrid(texto02) # Add frames as new "folders" of the notebook. tkadd(Notebook, frame01, text="opcao 1") tkadd(Notebook, frame02, text="opcao 2") tkgrid(Notebook) 35 tcltk_Evaluating_R_code.R Evaluating R Code From A Text Window in R TclTk.pdf 36 require(tcltk) tt <- tktoplevel() # Create a menu topMenu <- tkmenu(tt) # Add it to the 'tt' window tkconfigure(tt, menu = topMenu) # Add it to the 'tt' window fileMenu <- tkmenu(topMenu, tearoff = FALSE) tkadd(fileMenu, "command", label = "Quit", command = function() tkdestroy(tt)) tkadd(topMenu, "cascade", label = "File", menu = fileMenu) tkfocus(tt) R TclTk - Menus.pdf 37 require(tcltk) tt <- tktoplevel() topMenu <- tkmenu(tt) tkconfigure(tt, menu = topMenu) fileMenu <- tkmenu(topMenu, tearoff = FALSE) openRecentMenu <- tkmenu(topMenu, tearoff = FALSE) # Our cascaded menu tkadd(openRecentMenu, "command", label = "Recent File 1", command = function() tkmessageBox( message = "I don't know how to open Recent File 1", icon = "error")) tkadd(openRecentMenu, "command", label = "Recent File 2", command = function() tkmessageBox( message = "I don't know how to open Recent File 2", icon = "error")) tkadd(fileMenu, "cascade", label = "Open recent file", menu = openRecentMenu) tkadd(fileMenu, "command", label = "Quit", command = function() tkdestroy(tt)) tkadd(topMenu, "cascade", label = "File", menu = fileMenu) tkfocus(tt) 38 tearoff allows you to detach menus for the main window creating floating menus. If you create a menu you will see dotted lines at the top when you click a top menu item. If you click those dotted lines the menu tears off and becomes floating. 39 tt <- tktoplevel() img = tkimage.create("photo", file = "Print.gif") tkpack(mb <- tkmenubutton(tt, image = img)) m <- tkmenu(mb) tkconfigure(mb, menu=m) for(i in c("red","blue","green")) tkadd(m, "radio", label=i, variable="color", value=i) 40 ## Capture the event "Destroy" (e.g. Alt-F4 in Windows) ## and when this happens, assign 2 to done. tkbind(tt,"<Destroy>",function() tclvalue(done)<-2) Binding Events to Functions and Generating Events in R TclTk.pdf 41 require(tcltk) tt <- tktoplevel() labelText <- tclVar("This is a text label") label1 <- tklabel(tt,text=tclvalue(labelText)) tkconfigure(label1,textvariable=labelText) tkgrid(label1) ChangeText <- function() tclvalue(labelText) <- "This text label has changed!" ChangeText.but <- tkbutton(tt,text="Change text label",command=ChangeText) tkgrid(ChangeText.but) tkconfigure(ChangeText.but ,state="disabled") tkconfigure(ChangeText.but ,state="active") 42 require(tcltk) ## Para mudarmos o ícone TK que fica no canto superior esquerdo da janela, ## podemos utilizar dois formatos de imagem: BITMAP ou ÍCONE (.xbm || .ico). ## Caso se deseja um ícone colorido, pode-se utilizar imagens no formato de ícone, ## Para ler a imagem bitmap, utilizamos a função abaixo. Os parâmetros já foram ## repassados em outra aula. É importante lembrar que imagens .bmp não abrem. ## Elas devem estar no formato X11 bitmap, ou seja, .xbm tt = tktoplevel() tkwm.iconbitmap(tt,file.choose()) 0 – Mudando icone.R 43 Adding a Pop-Up Menu to a Text Window: R TclTk - Menus.pdf Modal dialog: R TclTk - Modal dialog.pdf Tktext: Text windows in R TclTk.pdf Color-Selection Widget: Using the Color-Selection Widget.pdf Data Entry and Calendar: The Date Entry and Calendar Widgets.pdf Wait Cursor: The Wait Cursor in R TclTk.pdf 44 ## Caso se deseja avisar ao usuário que o programa está em ## execução, pode-se modificar a forma do cursor, assim ## como é feito no Windows. require(tcltk) tt <- tktoplevel() tkconfigure(tt,cursor="X_cursor") 45 ## O cursor normal é tkconfigure(tt,cursor="arrow") ## Todos os cursores possíveis são: X_cursor arrow based_arrow_down based_arrow_up boat bogosity bottom_left_corner bottom_right_corner bottom_side bottom_tee box_spiral center_ptr circle clock coffee_mug cross cross_reverse crosshair diamond_cross Dot mouse pencil pirate plus question_arrow right_ptr right_side dotbox double_arrow draft_large draft_small draped_box exchange fleur gobbler gumby hand1 hand2 heart icon iron_cross left_ptr left_side left_tee leftbutton ll_angle lr_angle man middlebutton right_tee rightbutton rtl_logo ‣sailboat ‣sb_down_arrow ‣sb_h_double_arrow ‣sb_left_arrow ‣sb_right_arrow ‣sb_up_arrow ‣sb_v_double_arrow ‣shuttle ‣sizing ‣spider ‣spraycan ‣star ‣target ‣tcross ‣top_left_arrow ‣top_left_corner ‣top_right_corner ‣top_side ‣top_tee ‣trek ‣ul_angle ‣umbrella ‣ur_angle ‣watch ‣xterm 46 http://www.tkdocs.com/ 47 demo("tkcanvas", package="tcltk") demo("tkdensity", package="tcltk") demo("tkttest", package="tcltk") 48 # create a main window mw <- tktoplevel() # a menu consists of a horizontal menubar, # with associated submenus ##### first create the horizontal menubar mb <- tkframe(mw, relief = 'raised', bd = 2) # now put in the menubar some menubuttons m_file <- tkmenubutton(mb, text = "File", underline = 0) # pack everything from the menubar tkpack(mb, side = "top", fill = "x") tkpack(m_file, side = "left") 49