How to close a figure used for keypress function?
조회 수: 2 (최근 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에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!