How to close a figure used for keypress function?
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Brezelbayer
il 7 Feb 2023
Commentato: Brezelbayer
il 7 Feb 2023
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 Commenti
Jan
il 7 Feb 2023
@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.
Risposta accettata
Benjamin Kraus
il 7 Feb 2023
Modificato: Benjamin Kraus
il 7 Feb 2023
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 Commenti
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!