Attach click-event to Figure
39 次查看(过去 30 天)
显示 更早的评论
I want to update a Figure in a loop and attach a mouse-click-event. The following code works fine:
Function:
function OnMouse(hObject,~)
axes_handle = gca;
pt = get(axes_handle, 'CurrentPoint');
clicked_x=pt(1,1)
clicked_y=pt(1,2)
Main:
im = rand(500,500);
f=figure(1);
set(f,'WindowButtonDownFcn',@mytestcallback)
imshow(im)
But if I update the figure in a loop, the click is (nearly) never detected:
for i = 1:100
im = rand(500,500);
f=figure(1);
set(f,'WindowButtonDownFcn',@mytestcallback)
imshow(im)
%pause(1)
%pause(0.001)
end
Including a pause of 0.5 seconds solves this problem, but I cannot afford to make pause-time > 5 ms. How can I update my figure through a loop and attach a click-event which always will be detected?
0 个评论
回答(1 个)
Walter Roberson
2018-8-18
f=figure(1);
set(f,'WindowButtonDownFcn',@mytestcallback)
for i = 1:100
im = rand(500,500);
imshow(im)
drawnow(); %allows display to update _and_ allows button callback to be processed
end
1 个评论
Brian Wolin
2019-5-1
编辑:Brian Wolin
2019-5-1
I found that when running Walter's code, I get unusual behavior of when the callback executes or not. When clicking on the image, the callback executes maybe 25% of the time. When clicking inside the figure, but outside the image, the callback executes every time.
Any ideas why this might be the case and/or how to ensure the callback executes every time when clicking on the image/axes?
Here is my specific the callback function code, but I don't think this part matters for the behavior I describe.
function mytestcallback(src,~)
pt = get(gca,'CurrentPoint');
fprintf('Clicked: %d %d\n', pt(1,1),pt(1,2));
end
Edit: Also note that this behavior only manifests while the loop is running. Afterwards, clicking on the image is just as reliable as clicking elsewhere.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!