use a push button to close the GUI

I have a GUI that has a pushbutton that gets enabled once a certain condition has been met. I want to use that push button to then close the GUI.
here is my code:
function varargout = WorkingGUI3(varargin)
% WORKINGGUI3 MATLAB code for WorkingGUI3.fig
% WORKINGGUI3, by itself, creates a new WORKINGGUI3 or raises the existing
% singleton*.
%
% H = WORKINGGUI3 returns the handle to a new WORKINGGUI3 or the handle to
% the existing singleton*.
%
% WORKINGGUI3('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in WORKINGGUI3.M with the given input arguments.
%
% WORKINGGUI3('Property','Value',...) creates a new WORKINGGUI3 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before WorkingGUI3_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to WorkingGUI3_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help WorkingGUI3
% Last Modified by GUIDE v2.5 26-Sep-2019 17:02:03
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @WorkingGUI3_OpeningFcn, ...
'gui_OutputFcn', @WorkingGUI3_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before WorkingGUI3 is made visible.
function WorkingGUI3_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to WorkingGUI3 (see VARARGIN)
handles.uipanels = [handles.uipanel1, handles.uipanel2];
set(handles.pushbutton5, 'enable', 'off');
% Choose default command line output for WorkingGUI3
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes WorkingGUI3 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
end
% --- Outputs from this function are returned to the command line.
function varargout = WorkingGUI3_OutputFcn(hObject, eventdata, handles)
delete(instrfind('Port', 'COM3'));
tag = serial('COM3'); %check which port is used
fopen(tag);
BOX = char(zeros(2,14));
TrueValueData = 'C:\RfidChipTrueValues.xlsx';
[~,~,TrueValMat] = xlsread(TrueValueData);
% Creates matrix filled with the correct values,
% indexed by box, which is the first row
% all proceeding rows are the master value
for i=1:inf
for n = 1:2
if i>10
readData = fscanf(tag);
if length(readData)>12
BOX(str2num(readData(8)),1:14)= readData(11:24);
if strcmp(TrueValMat{2,n}, BOX(n,:))
set(handles.uipanels(n), 'BackgroundColor', 'g');
else
set(handles.uipanels(n), 'BackgroundColor', 'r');
end
drawnow
if strcmp(TrueValMat{2,1}, BOX(1,:))...
&& strcmp(TrueValMat{2,2}, BOX(2,:)) == 1
set(handles.pushbutton5, 'enable', 'on');
end
end
end
end
end
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
end
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
closereq();
end
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
end
everythig works fine, the button becomes enabled after my conditions are met, but pressing the button does nothing. I have also used closereq, close(handles.WorkingGUI3), delete(handles.WorkingGUI3). all help is appreciated.

 Respuesta aceptada

Adam Danz
Adam Danz el 26 de Sept. de 2019
Editada: Adam Danz el 26 de Sept. de 2019
Use the close request function
function pushbutton5_Callback(hObject, eventdata, handles)
closereq();
end
Only use gcf() or gca() when there is no other possible way to get the handle to a figure. For GUIDE GUIs, you can get the handle to the figure from the handles input (example: handles.figure1).

24 comentarios

avram alter
avram alter el 26 de Sept. de 2019
Still does not work, I initially tried the close request function, but nothing happened. even when nesting the closing function in the varargout ( and then trying outside th evarargout) function, still, nothing happens.
Adam Danz
Adam Danz el 26 de Sept. de 2019
Editada: Adam Danz el 26 de Sept. de 2019
Are you sure you're putting it in the correct callback function? I only see 1 button callback but it's labeled pushbutton5 which makes me wonder if there are additional push buttons.
Is the button enabled? I see in your opening function you disable the button and it's not enabled until a condition is met (like you mentioned in your question). Are you sure it's enabled (I forget if disabled buttons are invisible or just gray'd-out).
avram alter
avram alter el 26 de Sept. de 2019
Editada: avram alter el 26 de Sept. de 2019
In function varargout I enable it when a certain condition has been met:
if strcmp(TrueValMat{2,1}, BOX(1,:))...
&& strcmp(TrueValMat{2,2}, BOX(2,:)) == 1
set(handles.pushbutton5, 'enable', 'on');
end
so I see when it becomes enabled. I can switch the enable function to
set(handles.pushbutton5, 'Visible, 'on');
but the same thing will happen. The button pops up, pushing it does nothing. I had a punch of other push buttons in my prototyping stage, thats why it says puhbutton5. As of now it is the only one.
Adam Danz
Adam Danz el 26 de Sept. de 2019
Editada: Adam Danz el 26 de Sept. de 2019
Open the m file, put a break on the first line of the button callback function (not the line that declares the function but the first line after that). Then press your button. Is the function executed?
You could also attach the m file and the fig file so I can look at it direclty (with the button enabled).
avram alter
avram alter el 26 de Sept. de 2019
yeah, putting in that break point does nothing.
theres the 2 codes, the colors are kind of eh, but I'll fix that later.
Adam Danz
Adam Danz el 26 de Sept. de 2019
If it does nothing then the callback isn't be invoked. I'll look at it.
avram alter
avram alter el 26 de Sept. de 2019
much appreciated
Adam Danz
Adam Danz el 26 de Sept. de 2019
Editada: Adam Danz el 26 de Sept. de 2019
I see now... First let's understand what went wrong so it doesn't happen again.
The problem
When I open your GUI I get an error "Port: COM3 is not available" because the outputFcn is working with a serial port that apparently isn't available on my machine. The GUI still appears despite the error but when I press the button, the error appears again. I assume this is not a problem for you so I just added a "return" at the top of the function so I could continue troubleshooting.
Then when I pressed the Certify button, another error came up that you should have also seen and reported in this thread:
Unrecognized function or variable 'pushbutton5_Callback'.
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in WorkingGUI3 (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)WorkingGUI3('pushbutton5_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callback.
Your m file does have that function but the GUI doesn't recognize it. This happens when a callback function is added, deleted, or it's name was changed from within the m-file rather than from GUIDE. This is one of the major pains with GUIDE GUIs. All callbacks must be added, removed, and renamed from withing GUIDE.
The solution
Here are the steps to fix this.
  1. Backup the m-file and fig-file in case additional problems arise (you can always download them from your attachment above, too).
  2. Open the m-file.
  3. If the outputFcn is throwing an error (as I shared above), comment that stuff out or remove it for now - that's a separate issue.
  4. This step is optional but recommended. Select the entire m-file (ctrl+a) and smart-indent the code so everything is properly aligned (ctrl+i)
  5. Select the entire pushbutton5_Callback function and delete all of it. That's 7 lines of code including comments.
  6. I see you added "end" to all functions (including the main function). That's not necessary so remove all of the "end"s for the functions: one for the WorkingGUI3_OpeningFcn, one for WorkingGUI3_OutputFcn, and one for the main function on the last line (3 total).
  7. Save the m-file and remove all breaks, if any. To do that, from the editor select Breakpoints > Clear All; then close the m file and the figure.
  8. Open the figure in GUIDE: guide WorkingGUI3
  9. Right click the Certify button and open property inspector.
  10. Select everything in the Callback row on the right and delete it; close the property inspector.
  11. Click file > save (this will probably open the m file again which is OK).
  12. Again from within GUIDE, right click Certify button, select View Callbacks, and then select "Callback". That will add a new callback function to your m-code.
  13. Save the GUIDE and close it.
  14. In the new callback function added to your m-file, you can modify it to add the closereq();
  15. Save the m-file and run the GUI.
avram alter
avram alter el 2 de Oct. de 2019
I really appreciate all the help. problem is that the figure still will not close, even though I followed your directions to the letter. I'll attach the files again, maybe you'll see something. not getting the feval error either.
Adam Danz
Adam Danz el 2 de Oct. de 2019
Editada: Adam Danz el 2 de Oct. de 2019
First of all, congrats on working out the GUIDE problems!
It works for me when I do 2 things.
  1. I'm completely bypassing the WorkingGUI3_OutputFcn() function by placing a return on the first line of the function. Otherwise I get a "Port: COM3 is not available." error. I assum you are not getting this error and your GUI opens without any errors. If you are getting errors when the GUI opened, the closerequest callback to your button may not be properly set.
  2. In the WorkingGUI3_OpeningFcn() function, I'm commenting-out the line that disables the pushbutton5. If the button is disabled, pushing it does nothing.
I have a feeling you've been pushing a disabled button (#2 above).
avram alter
avram alter el 2 de Oct. de 2019
Editada: avram alter el 2 de Oct. de 2019
I have com3 set up, I am not getting this error at all. even when I comment out the disable push button error, still nothing happens. I have my code running so that the button gets enables after certain info comes in through com3. but even if I comment out the line disabling the button, it still does not work.
edit: I built a GUI with only the button, and then it works fine. but from guide, if I then add the rest of my code, the same thing happens.
Good that you're not geting the com3 error.
Two things...
First, I noticed that your pushbutton5 is still not linked to your GUIDE gui. I opened your GUI in GUIDE, right-clicked the button, and selected callback. Then this window popped up (r2019a & b)
191002 141045-GUIDE.png
Close your GUI, open it in GUIDE and do the same thing. When this window appears. select Yes. Then save the gui but before running the gui, add this line of code in your pushbutton5 callback function:
disp('Success')
Then run the GUI and press the button. To confrirm that the callback is linked to the GUI you should see that message in the command window.
Second thing: After doing that, your GUI will not close when you press that button. For whatever reason, prior to this change your GUI closed for me but not anymore. To fix that, you have to add the closereq() to the callback (see my 'answer' above).
That should solve the problem.
Here are some additional steps if the problem persists after those changes:
  1. Are you sure you're saving and re-opening the figure after you make changes?
  2. Are you sure the button is enabled when you're pressing it (it looks different when disabled)?
  3. Have you checked that there aren't multiple m and fig files with the same name and that you're using the updated m and fig files?
Adam Danz
Adam Danz el 2 de Oct. de 2019
"edit: I built a GUI with only the button, and then it works fine. but from guide, if I then add the rest of my code, the same thing happens."
My comment above should fix it, then. Just just need to 1) reconnect the callback function to the GUI and 2) add the closereq function to the callback.
avram alter
avram alter el 2 de Oct. de 2019
Editada: avram alter el 2 de Oct. de 2019
I am using r2017a, and I get no window like that. I did find that I incidentally had multiple files of the same name, so I followed your steps above again. upon adding the callback function in step 12, it does not allow me to save. both the icon and the file>save is greyed out.
when the button gets enabled, the appearance does change. it goes from completely greyed out to its normal appearence. pressing it clearly shows as being depressed, as it has a little broken line outline, and becomes tinged blue.
Adam Danz
Adam Danz el 2 de Oct. de 2019
Editada: Adam Danz el 2 de Oct. de 2019
Attached is your GUI without the problems. Make sure you move all backups to a zip file or to some location that is not on your matlab path.
Remove the "return" in the output funciton and de-comment the disable line in the opening function.
avram alter
avram alter el 2 de Oct. de 2019
I really appreciate all the time you've spent helping me.Unfortunately, as soon as I add back my functions (by removing the return on line 68, and by uncommenting line 55) it immediately stops working,and goes back to not doing anything. I guess I'll move onto a more important problem for now, if you can still help me.
Right now, my code only uses a single serial port, but I need it to use 4. basically, all of them will be sending data at the same time, but only 1 serial port will be used at once. I don't know how to use bytesavailablefcn though.
and again, I really appreciate all the help. maybe I'll come back to that closereq() error, but for now I'm going to call it quits on that problem. if you can help me with the other question, that would be fantastic.
Adam Danz
Adam Danz el 2 de Oct. de 2019
"Unfortunately, as soon as I add back my functions ... it immediately stops working"
If you're using the files I attached, that suggests that the COM3 communication is interfering. I don't know what's going on there but perhaps all callback responses are supressed. I would put a break point at the first line of the WorkingGUI3_OutputFcn function and reopen the GUI. Then step through each line and try to get a sense of anything that would interfere with interaction with the GUI.
Unforunately I know much less about the use of serial ports in Matlab GUIs. You'd have a better chance at getting help if you post a new question which will increase the visibilty of that problem (I doubt many people are following this conversation).
"I really appreciate all the time you've spent "
Glad I could help with parts of it!
avram alter
avram alter el 2 de Oct. de 2019
alright, I'll see what I come up with. thanks again for all the time!
a little bit of an update, I was playing with the button, and I found that using your
disp('Success')
idea worked. the problem is that the word success would only appear after i paused the code. that may be why the cosereq function wasnt responding. do you know anything about that by any chance?
Adam Danz
Adam Danz el 3 de Oct. de 2019
That's because, as I mentioned earlier, your callback function wasn't actually linked to your GUIDE gui. I fixed that and attached your fig and m files which should be functional for you, too, unless you've got duplicate file names that are interfering.
I found an answer on stack overflow. adding
pause(0.01)
under the for 1:inf loop negated the serial interference, and allowed the button to work.
Adam Danz
Adam Danz el 7 de Oct. de 2019
Hmmm.... I wonder if a drawnow() would work instead of the pause().
I didn't have that graphics problem when I ran your repaired GUI.
avram alter
avram alter el 7 de Oct. de 2019
I could try that, but I don't see any need to. I think the reason you aren't having the problem is that the incoming serial data is interfering. Maybe not. I don't know.
Adam Danz
Adam Danz el 7 de Oct. de 2019
Ahhhh..... I see. That's probably it. Thanks for the update!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Interactive Control and Callbacks en Centro de ayuda y File Exchange.

Productos

Versión

R2017a

Preguntada:

el 26 de Sept. de 2019

Comentada:

el 7 de Oct. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by