How to close a figure used for keypress function?
5 次查看(过去 30 天)
显示 更早的评论
Hi,
I'm using the KeyPressFnc to capture user-feedback in a small test. The use of KeyPressFnc requires to open a (dummy) figure. To complete the test (aka run the code clean from top to bottom) I have to close the figue. So far I have not found a way to close the figure after the user feedback was captured.
How do I close the figure (correctly), so I reach the end of the test and get my 'End of Test' statement?
function parent % outer function
disp('This is the outer function')
hkey = figure;
set(hkey,'KeyPressFcn',@UserFeedback);
disp('Make your choice: Press left or right arrow key')
waitfor(hkey);
UserFeedback
disp('End of Test')
function UserFeedback(~,evnt) % inner function
if strcmpi(evnt.Key,'leftarrow')
disp('You chose option 1: leftarrow key.')
close(hkey)
elseif strcmpi(evnt.Key,'rightarrow')
disp('You chose option 2: rightarrow key.')
close(hkey)
else
disp('Invalid Key, please press left or right arrow key for evaluation.')
return
end
disp('This was the inner function')
end % inner function
end % outer function
3 个评论
Jan
2023-2-7
@Brezelbayer: What is the problem with the shown code? Closing hkey looks correct, if hkey is a shared variable in a nested function. I'd prefer delete(hkey) but this might be a question of taste.
As W.J. said, it is unclear why you call UserFeedback() again.
采纳的回答
Benjamin Kraus
2023-2-7
编辑:Benjamin Kraus
2023-2-7
As @W. J. stated, your code seems to run fine if you just remove the call to UserFeedback from after the call to waitfor.
Alternatively, have you tried the input function? It won't work if you need to capture left arrow and right arrow, but it does allow you to capture user input without needing to create a separate figure, or deal with KeyPressFcn or callbacks.
If you stick with your approach, you can clean-up your code a little by using the first input to UserFeedback, like this:
function askForUserFeedback % outer function
disp('This is the outer function')
hkey = figure;
set(hkey,'KeyPressFcn',@UserFeedback);
disp('Make your choice: Press left or right arrow key')
waitfor(hkey);
disp('End of Test')
function UserFeedback(fig,evnt) % inner function
if strcmpi(evnt.Key,'leftarrow')
disp('You chose option 1: leftarrow key.')
close(fig)
elseif strcmpi(evnt.Key,'rightarrow')
disp('You chose option 2: rightarrow key.')
close(fig)
else
disp('Invalid Key, please press left or right arrow key for evaluation.')
return
end
disp('This was the inner function')
end % inner function
end % outer function
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!