Is there any way to tell iPython/Juypter to process any widget events in the middle of a sleep loop?
I've seen the async examples, but they don't make sense to me. Is there a simpler way?
I want to do something like this:
for i in range(3):
button_response = None
clear_output()
display_trial_widget(i, ...)
while not button_response:
# Let iPython handle all widget events...
time.sleep(0.1)
save_response_and_modify_trial()
The trial widget plays some audio, and expects the user to click one of two buttons in response.
Is there something simple I can put in the while loop so that iPython widgets can do their thing? I'm doing this in a Juypter notebook running on MacOSX.
Here is the current UI: Widget UI
Thanks.
OK, that was a dumb question.
A better way is to make everything event based, as was done in this answer.
Python onclick button widget return object
This way a button event causes the next screen to be drawn. No need for a wait loop.
Related
I am designing a GUI using C, Glade, and Gtk.
I have some signals configured in glade to update the labels of various widgets, mainly GtkButton and GtkLabel. The overall functionality is that when a certain radio button is clicked, all button and labels change in response (language selection).
I am using the function gtk_label_set_label(...) in the widgets _draw() function and it works as expected (text changes, g_print occurs (once)).
gboolean on_lblMyLabel_draw(GtkLabel *label, gpointer *user_data) {
gtk_label_set_label(label, "custom text");
g_print("%s\n", "custom text");
return FALSE;
}
However, when I attempt the same from a button,
gboolean on_btnMyButton_draw(GtkButton *button, gpointer *user_data) {
gtk_button_set_label(button, "custom text");
g_print("%s\n", "custom text");
return FALSE;
}
The text does not update, but dissappears, and the g_print() statement prints forever (as if the draw is recursively calling itself).
Funnily, if I move the button code from _draw to _click, it works as expected, however, I need the GUI to redraw itself, so updating on click is impractical.
Is there a way, using _draw() to prevent this?
Is there a better way to do this?
thx!
Is there a way, using _draw() to prevent this?
No, and you shouldn’t be using the draw signal for this either. It has an entirely different purpose, and will be called each time a widgets redraws itself. That’s also the reason why your button is going into an infinite recursion: you changed its label so it figures it needs to be redrawn; that redraw leads to your callback being called, which again changes the label, etc etc
Is there a better way to do this?
Yes, and you mention it yourself already: make sure you do the logic of changing the widgets in the appropriate place (for example, on a click event), and let the GTK widgets take care of redrawing themselves.
Unless you’re doing something very exotic (like not running an event loop, which you automatically get with GtkApplication), this will all work fine.
I don't code so asking for help :-) Hi, I have an issue for a page animation with a couple of interactions. How do I insert a code snippet to tell the browser to either continue or pause the animation, when a user opens/clicks another tab.
Right now, the animation pauses for the first part, but the subsequent interactions keep going. And it's a jumbled mess.
What is the easiest/simple way to do this? Can someone share the full/complete code snippet to accomplish this? I've been searching for hours and can't seem to find the right solution.
I'm using Webflow for the site. Thanks a bunch.
When the user clicks away from a window, certain events are fired off. You can add event handlers to your window object that respond to these events.
You probably want to listen for 'focus' and 'blur' events. JavaScript:
window.addEventListener('blur', function (evt) {
// turn off your animation here
});
window.addEventListener('focus', function (evt) {
// turn on your animation here
});
Documentation on window blur event, window focus event, addEventListener().
I have a simple page that reports all window events, it might be useful:
https://terrymorse.com/coding/windowevents/index.html
I'm working on a custom cross platform UI library that needs a synchronous "ShowPopup" method that shows a popup, runs an event loop until it's finished and automatically cancels when clicking outside the popup or pressing escape. Keyboard, mouse and scroll wheel events need to be dispatched to the popup but other events (paint, draw, timers etc...) need to be dispatched to their regular targets while the loop runs.
Edit: for clarification, by popup, I mean this kind of menu style popup window, not an alert/dialog etc...
On Windows I've implemented this fairly simply by calling GetMessage/DispatchMessage and filtering and dispatching messages as appropriate. Works fine.
I've much less experience with Cocoa/OS X however and finding the whole event loop/dispatch paradigm a bit confusing. I've seen the following article which explains how to implement a mouse tracking loop which is very similar to what I need:
http://stpeterandpaul.ca/tiger/documentation/Cocoa/Conceptual/EventOverview/HandlingMouseEvents/chapter_5_section_4.html
but... there's some things about this that concern me.
The linked article states: "the application’s main thread is unable to process any other requests during an event-tracking loop and timers might not fire". Might not? Why not, when not, how to make sure they do?
The docs for nextEventMatchingMask:untilDate:inMode:dequeue: states "events that do not match one of the specified event types are left in the queue.". That seems a little odd. Does this mean that if an event loop only asks for mouse events then any pressed keys will be processed once the loop finishes? That'd be weird.
Is it possible to peek at a message in the event queue without removing it. eg: the Windows version of my library uses this to close the popup when it's clicked outside, but leaves the click event in the queue so that clicking outside the popup on a another button doesn't require a second click.
I've read and re-read about run loop modes but still don't really get it. A good explanation of what these are for would be great.
Are there any other good examples of implementing an event loop for a popup. Even better would be pseudo-code for what the built in NSApplication run loop does.
Another way of putting all this... what's the Cocoa equivalent of Windows' PeekMessage(..., PM_REMOVE), PeekMessage(..., PM_NOREMOVE) and DispatchMessage().
Any help greatly appreciated.
What exactly is a "popup" as you're using the term? That term means different things in different GUI APIs. Is it just a modal dialog window?
Update for edits to question:
It seems you just want to implement a custom menu. Apple provides a sample project, CustomMenus, which illustrates that technique. It's a companion to one of the WWDC 2010 session videos, Session 145, "Key Event Handling in Cocoa Applications".
Depending on exactly what you need to achieve, you might want to use an NSAlert. Alternatively, you can use a custom window and just run it modally using the -runModalForWindow: method of NSApplication.
To meet your requirement of ending the modal session when the user clicks outside of the window, you could use a local event monitor. There's even an example of just such functionality in the (modern, current) Cocoa Event Handling Guide: Monitoring Events.
All of that said, here are (hopefully no longer relevant) answers to your specific questions:
The linked article states: "the application’s main thread is unable to process any other requests during an event-tracking loop and
timers might not fire". Might not? Why not, when not, how to make
sure they do?
Because timers are scheduled in a particular run loop mode or set of modes. See the answer to question 4, below. You would typically use the event-tracking mode when running an event-tracking loop, so timers which are not scheduled in that mode will not run.
You could use the default mode for your event-tracking loop, but it really isn't a good idea. It might cause unexpected re-entrancy.
Assuming your pop-up is similar to a modal window, you should probably use NSModalPanelRunLoopMode.
The docs for nextEventMatchingMask:untilDate:inMode:dequeue:
states "events that do not match one of the specified event types are
left in the queue.". That seems a little odd. Does this mean that if
an event loop only asks for mouse events then any pressed keys will be
processed once the loop finishes? That'd be weird.
Yes, that's what it means. It's up to you to prevent that weird outcome. If you were to read a version of the Cocoa Event Handling Guide from this decade, you'd find there's a section on how to deal with this. ;-P
Is it possible to peek at a message in the event queue without removing it. eg: the Windows version of my library uses this to close
the popup when it's clicked outside, but leaves the click event in the
queue so that clicking outside the popup on a another button doesn't
require a second click.
Yes. Did you notice the "dequeue:" parameter of nextEventMatchingMask:untilDate:inMode:dequeue:? If you pass NO for that, then the event is left in the queue.
I've read and re-read about run loop modes but still don't really get it. A good explanation of what these are for would be great.
It's hard to know what to tell you without knowing what you're confused about and how the Apple guide failed you.
Are you familiar with handling multiple asynchronous communication channels using a loop around select(), poll(), epoll(), or kevent()? It's kind of like that, but a bit more automated. Not only do you build a data structure which lists the input sources you want to monitor and what specific events on those input sources you're interested in, but each input source also has a callback associated with it. Running the run loop is like calling one of the above functions to wait for input but also, when input arrives, calling the callback associated with the source to handle that input. You can run a single turn of that loop, run it until a specific time, or even run it indefinitely.
With run loops, the input sources can be organized into sets. The sets are called "modes" and identified by name (i.e. a string). When you run a run loop, you specify which set of input sources it should monitor by specifying which mode it should run in. The other input sources are still known to the run loop, but just ignored temporarily.
The -nextEventMatchingMask:untilDate:inMode:dequeue: method is, more or less, running the thread's run loop internally. In addition to whatever input sources were already present in the run loop, it temporarily adds an input source to monitor events from the windowing system, including mouse and key events.
Are there any other good examples of implementing an event loop for a popup. Even better would be pseudo-code for what the built in
NSApplication run loop does.
There's old Apple sample code, which is actually their implementation of GLUT. It provides a subclass of NSApplication and overrides the -run method. When you strip away some stuff that's only relevant for application start-up or GLUT, it's pretty simple. It's just a loop around -nextEventMatchingMask:... and -sendEvent:.
Am building a gui app using wxpython,i have created two separate windows in two different files,i.e app1.py and app2.py,I want to open the 2nd window(app2.py) using a button click on first window(app1.py). How do i achieve this. It would be great if someone can help,Thanks!!
I am assuming you're using wxPython's definition of "window" (i.e. anything that is actually viewable in the GUI), not the regular definition of "separate box with stuff in it and an X button in the corner" (which wxPython calls a "frame")
When I was writing my first wxPython GUI I was faced with a similar probem. I wanted actions in one panel to affect the data shown in another. My first solution was to write methods that blindly passed the request to the panel's parent until it reached the top level (my "main frame", if you will). This worked, but obviously it's a terrible solution.
My second solution was to use wxPython Events, just like catching button presses for a wx.Panel. My idea was I would create a button in one frame and bind wx.EVT_BUTTON with that button's ID in another. I made custom Events and CommandEvents. While trying to implement this solution I discovered that do not propogate and that CommandEvents will only propogate through the parents. So, if left uncaught a CommandEvent will eventually hit your "main frame" but it will never hit the second panel unless that panel happens to be a parent of where the Event came from. Obviously, this won't work for you since the parent can't be hidden but a child be visible. Plus it would leave your main frame cluttered with code and methods to delegate commands.
Finally, I found the answer! wx.lib.pubsub! Basically, you bind the button press in app1.py, just like normal. Now, in the handler you use pubsub to publish a custom message. Next, in the init for app2.py, you use pubsub to subscribe to your custom message (I like having a "message.py" where I declare all my messages as constants). When you subscribe to a message you assign a handler method, just like for events.\
Read this: http://wiki.wxpython.org/WxLibPubSub
Since you said you wanted the window to APPEAR, maybe in the init method for app2.py you call the Hide() method then when you receive the message, call Show().
When I implemented this in my application I was using wxPython2.8. I am now using 2.9 so I don't know if this is still necessary but I found that I need the top import in order to call pubsub.subscribe() and pubsub.sendMessage(). I kept getting errors otherwise. I can't remember how I figured this out, I think I saw it in a code sample and added it in a desperate attempt to make my code work. I suggest you read the documentation I linked above and try to implement your code WITHOUT that import first.
import wx
from wx.lib.pubsub import setupkwargs #I need this to force pubsub to work. I don't know why.
from wx.lib.pubsub import pub
ID_MYBUTTON = wx.NewId()
class App1(wx.Panel):
def __init__(self, parent):
wx.Panel.__init___(self, parent)
button = wx.Button(self, ID_MYBUTTON, "Show App2")
self.Bind(wx.EVT_BUTTON, self.handleButton, id=ID_MYBUTTON
def handleButton(self, event):
pubsub.sendMessage("mybutton.pressed") #send the message
class App2(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent)
self.Hide() #I don't want to be seen yet
pubsub.subscribe(self.gotMessage, "mybutton.pressed") #listen for the message
def gotMessage(self):
self.Show() #Now I want to be seen!
-----EDIT-----
I found this SO question that might help: Creating child frames of main frame in wxPython
Please tell us in detail what you're trying to do? wxPython also has "dialogs" which would be better than a frame if all you're doing is showing the user a message or asking for a bit more information. http://wxpython.org/docs/api/wx.Dialog-class.html
It really depends on what you're trying to accomplish. We can't help you unless you explain what problem you're trying to solve.
-----EDIT AGIAN-----
It's looking like the person asking the question did indeed want a wx.Dialog. For a tutorial, see http://zetcode.com/wxpython/dialogs/ Also see Python WX - Returning user input from wx Dialog
I'm trying to write a kiosk GUI in ruby/gtk on ubuntu. I'm pretty fluent in ruby, but new to writing GUIs and not great with linux.
I'm using a touch screen, and am using our own images for buttons, e.g.
button_image = Gtk::Image.new(Gdk::Pixbuff.new "images/button_image.png")
#button = Gtk::Button.new
#button.add(button_image)
#button.set_relief(Gtk::RELIEF_NONE)
My issue is that when the buttons are pressed or remain selected (or hovered over, although this is less relevant with a touch screen), gtk shows fat, square borders around them. Obviously it's applying gtk's prelight / selected / active lighting to the buttons. I've tried changing the button properties in various ways, and also tryied hacking apart my theme, and while I can modify how the highlighting looks, I can't seem to completely get rid of it. Changing the color of the highlight via my theme is easy, but if I remove my setting there's still a default I can't get rid of.
Does anyone know if there's a way to stop it, or possibly make it transparent? Thanks in advance!
Sounds like you want to use exactly your image for the whole button, instead of putting an image inside the normal GtkButton - but still use all the normal behavior of the button.
The easiest way to do this is to just override the drawing. If you are on gtk2, connect to the "expose-event" signal, do your drawing there, and return true so that the default handler doesn't get run. If you are on gtk3, connect to the "draw" signal and do the same.
I tried meddling with the drawing as Federico suggested, but found that the most direct way to address this was instead to use an event box rather than a button. Event boxes accept clicks just like buttons, but don't respond to selecting, hovering, etc. In ruby, the code looks like this:
image = Gtk::Image.new("myfile.png")
event_box = Gtk::EventBox.new.add(image)
event_box.visible_window = false
event_box.signal_connect("button_press_event") do
puts "Clicked."
end
Most of this is exactly like a button; the *visible_window* method, obviously, keeps the event box from being visible under the button image.