R gSignalConnect - r

I'm trying to learn how to signalConnect buttons to labels. For example, I've made a button labeled "+" and created a label initialized to "0". I would like the button to adjust the label by adding one every time the button is clicked. I have constructed the button and the window for it. My question is, how do I use the gSignalConnect() function to perform this?
Thanks,
Joe
-- Here is my code
win <- gtkWindow(show = FALSE)
win$Resize( width = 700, height = 500)
win$SetTitle(title = "Measurement GUI")
frame <- gtkFixedNew()
win$add(frame)
plus<-gtkButtonNewWithLabel("+")
plus$setSizeRequest(80,35)
frame$put(plus, 10, 50)
label <-gtkLabelNew("0")
frame$put(label, 100, 80)
win$ShowAll()

Try
callback <- function(btn, ...) {
old <- as.numeric(label$getText())
label$setText(old + 1)
}
gSignalConnect(plus, "clicked", callback)
To use gSignalConnect, you will need to know which signals (and their signatures) are available for your widget. ?gtkButton will give this information.

Related

How to build a simple widget or app in jupyter notebook/lab to interactively extract a substring from text?

I want iterate over a list of string, output the string as plain text in jupyter lab then interactively highlight a substring to get easily the start index of the substring and the length. The goal is to do a quick annotation of text and get the coordinates of the substring.
Is it easy or even possible to do something like this with jupyter notebook (lab)? If then How?
I had a look at ipywidgets but couldn't find something for this use case.
Here's an example with the RangeSlider:
import ipywidgets
input_string = 'averylongstring'
widg = ipywidgets.IntRangeSlider(
value = [0, len(input_string)],
min=0, max=len(input_string)
)
output_widg = ipywidgets.Text()
display(widg)
display(output_widg)
def chomp_string(widg):
start,end = tuple(widg['new'])
output_widg.value = input_string[start: end]
widg.observe(chomp_string, names='value')
You can implement this using jp_proxy_widgets. See the following screenshot:
Note that there are warnings about compatibility for selection protocols -- I only tested this on Chrome on a Mac. Also I don't know why the indices are off by one
(select_callback(startOffset+1, endOffset+1);)
Please see https://github.com/AaronWatters/jp_proxy_widget for more information
Edit: Here is the pastable text as requested:
import jp_proxy_widget
select_widget = jp_proxy_widget.JSProxyWidget()
txt = """
Never gonna give you up.
Never gonna let you down.
Never gonna run around and
desert you.
"""
selected_text = None
def select_callback(startOffset, endOffset):
global selected_text
selected_text = txt[startOffset: endOffset]
print ("Selected", startOffset, endOffset, repr(selected_text))
select_widget.js_init("""
// (Javascript) Add a text area.
element.empty()
$("<h3>please select text:</h3>").appendTo(element);
var textarea = $('<textarea cols="50" rows="5">' + txt + "</textarea>").appendTo(element);
// Attach a select handler that calls back to select_callback.
var select_handler = function(event) {;
var target = event.target;
var startOffset = target.selectionStart;
var endOffset = target.selectionEnd;
select_callback(startOffset+1, endOffset+1);
};
textarea[0].addEventListener('select', select_handler);
""", txt=txt, select_callback=select_callback)
# display the widget
select_widget.debugging_display()

How to get scroll up vs. down in R

I am using getGraphicsEventEnv to get events over an R plot. Previously, scroll up or down were encoded in the event handler but now, the test code posted on a related bug fix returns an empty whether it is scroll up or scroll down.
Is there a new way to get those events?
example code:
mousemove <- function (buttons, x, y){
cat("mousemove")
print(buttons)
NULL
}
mouseclick <- function (buttons, x, y){
cat("mouseclick")
print(buttons)
NULL
}
mouserelease <- function (buttons, x, y){
cat("mouserelase")
print(buttons)
NULL
}
keystroke <- function (key){
cat("keystroke")
print(key)
NULL
}
if (identical(version$os, "linux-gnu")){
x11(type = "Xlib")
} else {
x11()
}
par(mar = c(0, 0, 0, 0))
plot.new()
getGraphicsEvent(onMouseMove = mousemove, onMouseDown = mouseclick, onMouseUp = mouserelease, onKeybd = keystroke)
On scroll this selects both mouseclick and mouserelease on a loop but with no buttons given, impossible to use. Before, on X11, we had special "buttons" returned for "scroll up" and "scroll down". To me this is a regression, hopefully replaced by a feature somewhere but where is the feature?

how to stop Vpython from being unresponsive

Im fairly new to Vpython and Ive created a simulation for circular motion. I tried adding controls to the simulation and so far I am able to pause the simulation but when i do pause it, the entire control panel becomes unresponsive and i am unable to resume the simulation. Does anyone know why this may be or how i can fix this?
def playorpause(self, goorno):
self.pause = goorno
def actual_sim(self):
c = controls() # Create controls window
# Create a button in the controls window:
# b = Button(pos=(-50, 0), width=60, height=60, text="Pause", action=lambda: self.change)
# play = Button(pos=(50, 0), width=60, height=60, text="Play", command = self.play_sim)
b = button(pos=(-50, 0), width=60, height=60, text='Pause', action=lambda: self.playorpause(True))
play = button(pos=(50,0), width = 60, height = 60, text = "play", action =lambda: self.playorpause(False))
def loop():
#### simulation code
if self.pause == False:
loop()
I'm not sure, because I don't really understand your code, but a repetitive loop needs to include a rate statement. Otherwise the program will lock up, unable to output anything.

kivy button ID's within functions

I am working on a fantasy football type app for a school project.
We have created a scrollview with a list of characters in a team within it, each assigned to a button. on press of the button a new scrollview displaying a second list of 'inactive character buttons' is displayed, allowing the user to press one to swap the first and second character from team to team.
our issue comes from a difficulty in managing to 'locate' which button is pressed in order to tell our swap function which two characters to swap on the list. Is it possible to retain the id of a button and call it into a new function on press of said button?
Our code is a bit messy, but is displayed bellow:
class SMApp(App):
teamlist = []
idvar = ""
btnlist = []
def popupfunc(self, event):
"""
creates a popup asking if the user wishes to swap a character from team to subs
then proceeds to allow user to choose who swaps
"""
def subscroll(self):
"""
opens scroll list of substitute characters in a popup
"""
sublist = []
curs.execute('SELECT * FROM Subs')
for row in curs:
sublist.append([row[0], row[2]])
layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
for i in range(len(sublist)):
btn = Button(text=str(sublist[i][0]), size_hint_y=None, height=40)
layout.add_widget(btn)
lbl = Label(text=str(sublist[i][1]), size_hinty=None, height=40)
layout.add_widget(lbl)
root = ScrollView(size_hint=(None, None), size=(400, 400))
root.add_widget(layout)
popup2 = Popup(content=root, size=(7, 10), size_hint=(0.55, 0.8), title="list of subs")
popup2.open()
box = BoxLayout()
btn1 = Button(text='yeah ok')
btn2 = Button(text='nope')
popup1 = Popup(content=box, size=(10, 10), size_hint=(0.3, 0.3), title="add to team?")
btn2.bind(on_press=popup1.dismiss)
btn1.bind(on_press=subscroll)
box.add_widget(btn1)
box.add_widget(btn2)
popup1.open()
def build(self):
curs.execute('SELECT * FROM Team')
for row in curs:
self.teamlist.append([row[0], row[2]])
layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
for i in range(len(self.teamlist)):
btn = Button(text=str(self.teamlist[i][0]), size_hint_y=None, height=40, id=str(i))
btn.bind(on_press=self.popupfunc)
self.btnlist.append(btn)
layout.add_widget(btn)
lbl = Label(text=str(self.teamlist[i][1]), size_hinty=None, height=40)
layout.add_widget(lbl)
for item in self.btnlist:
print item.id
root = ScrollView(size_hint=(None, None), size=(400, 400),
pos_hint={'center_x':.5, 'center_y':.5})
root.add_widget(layout)
return root
if __name__ == '__main__':
SMApp().run()
Each of the btn = Button(...) you create is a different object, therefore you can tell which is pressed. The thing is what way you'll choose.
You can use:
str(your button) and get a specific object address(?) like 0xAABBCCEE
bad, don't do that
Button(id='something', ...)
ids from kv language
or create own widget with a property for specific identificator. Then you'd use a loop for the parent's children which would check for identificator and do something:
for child in layout.children:
if child.id == 'something':
# do something
And it seems you'd need this loop inside your subscroll, or access that layout some other way.

Getting my buttons to add text to a list

I'm having a problem getting my buttons to actually do something, when one of the buttons on the top left are clicked, I want a text box in the frame below it adding the name of that button to a list but getting really stuck with it, any help would be much appreciated, thank you
Here is my code:
import tkinter
import tkinter as tk
root = tk.Tk()
root.geometry('1000x600')
var=tk.StringVar()
Frame1 = tk.Frame(root)
Frame1.configure(background='light blue',height='300',width='500')
Frame1.grid(sticky="nsew",row='0',column='0')
Frame2 = tk.Frame(root)
Frame2.configure(background='grey',height='300',width='500')
Frame2.grid(sticky="nsew",row='0',column='1')
Frame3 = tk.Frame(root)
Frame3.configure(background='grey',height='300',width='500')
Frame3.grid(sticky="nsew",row='1',column='0')
Frame4 = tk.Frame(root)
Frame4.configure(background='light blue',height='300',width='500')
Frame4.grid(sticky="nsew",row='1',column='1')
def PrintOrder():
LabelOrder = tk.Label(Frame3,text="DONUT ORDER")
LabelOrder.grid(row='0',column='0')
return
Button1 = tk.Button(Frame1,text="Apple Cinnamon",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='0',column='0')
Button2 = tk.Button(Frame1,text="Strawberry",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='0',column='2')
Button3 = tk.Button(Frame1,text="Custard",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='0',column='4')
Button4 = tk.Button(Frame1,text="Sugar Ring",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='2',column='0')
Button5 = tk.Button(Frame1,text="Chocolate Caramel",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='2',column='2')
Button6 = tk.Button(Frame1,text="Lemon Circle",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='2',column='4')
Button7 = tk.Button(Frame1,text="Blueberry Blaster",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='4',column='0')
Button8 = tk.Button(Frame1,text="Strawberry Surprise",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='4',column='2')
Button9 = tk.Button(Frame1,text="Simple Sugar",height='2',width='15',padx=10, pady=5,command=PrintOrder).grid(row='4',column='4')
Label1 = tk.Label(Frame2,text="Donut special 6 for the price of 5",height='5',width='30').grid(row='0',column='0')
Button10 = tk.Button(Frame2,text="SPECIAL",padx=5, pady=5,height='5',width='20').grid(row='2',column='0')
Button11 = tk.Button(Frame3,text="ORDER TOTAL",padx=5, pady=5,height='5',width='20').grid(row='2',column='0')
Button12 = tk.Button(Frame4,text="RUNNING TOTAL",padx=5, pady=5,height='5',width='20').grid(row='2',column='0')
root.mainloop()
The problem is that when you call the PrintOrder function, it doesn't necessarily know what button called it.
To fix this, use a lambda: [see http://effbot.org/zone/tkinter-callbacks.htm, "Passing Arguments to Callbacks"]
Also, you'll need variable strings to work with the list.
Above your PrintOrder function, write this (move the Label creation outside of the function):
LabelContents = tk.StringVar()
LabelOrder = tk.Label(Frame3, textvariable=LabelContents)
LabelOrder.grid(row='0', column='0')
then you can update the text in the label.
So change the PrintOrder function to
def PrintOrder(flavor):
LabelContents.set(LabelContents.get() + '\n' + flavor)
return
This appends the flavor, with a new line, to the label.
then in the button:
Button(text="lemon", command=lambda: PrintOrder("lemon"))
Of course you can modify to fit your program.
For the reasoning behind the lambda, see the link.
Hope that helps!

Resources