How to close a MATLAB GUI by using count down timer?

조회 수: 2 (최근 30일)
Dongyan Zhu
Dongyan Zhu 2020년 2월 5일
댓글: Geoff Hayes 2020년 2월 19일
Does anyone konw how to close the GUI by using a timer, e.g. after 10 seconds the current GUI-window will be closed. In addition I can see the counting down number. Thank you all!

채택된 답변

Geoff Hayes
Geoff Hayes 2020년 2월 5일
Dongyan - the solution will differ depending upon how you have created your GUI (GUIDE, programmatically, or App Designer) but the general idea will be the same. Your GUI will need a timer that exists for the lifetime of the GUI (so the timer cannot be a local variable within some function or method). At some point (pushbutton callback for example), you will initialize a timer with a period (one second), number of tasks to execute (10), and a callback function (that will fire as per your one second period). See Create object to schedule execution of MATLAB commands for details. If your GUI is built with GUIDE, then the following code could be put in whichever function callback that needs to start the timer
handles.timer = timer('Name','MyTimer', ...
'Period',1, ...
'StartDelay',1, ...
'TasksToExecute',10, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@timerCallback,handles.figure1});
guidata(hObject,handles);
start(handles.timer);
Note how we assign the timer to the handles structure and then call guidata to save that change. Also note how we pass in to the callback the handle to the figure. We do this so that the timer callback can access the GUI to either update the countdown text or to close the GUI. This code may look like
function [] = timerCallback(hTimer,~,guiHandle)
if ~isempty(guiHandle)
% get the handles
handles = guihandles(guiHandle);
% get the current task number (1,2,3,...,10)
tasksExecuted = get(hTimer, 'TasksExecuted');
tasksToExecute = get(hTimer, 'TasksToExecute');
% update the text control with the seconds remaining (note the tasksExecuted counts upwards)
% close the GUI
if tasksExecuted == tasksToExecute
close(guiHandle);
end
end
The above is untested so there might be some gotchas especially around closing the GUI.
  댓글 수: 2
Dongyan Zhu
Dongyan Zhu 2020년 2월 10일
편집: Dongyan Zhu 2020년 2월 19일
thx I have tried by myself and it works;)
Geoff Hayes
Geoff Hayes 2020년 2월 19일
Glad that it worked out!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by