Passing variables in GUI
조회 수: 7 (최근 30일)
이전 댓글 표시
Dear all,
I am trying to code a GUI but I am new at this. I would like to pass the variables from one function to another, but in some forums it is said that you have to pass the variables as global variables, in another one it is said that you need to use the guidata, etc. and I am a bit confused. The GUI looks like this:
The first callback is:
function KW_Callback(hObject, eventdata, handles)
handles.dKW = str2double(get(hObject,'string'));
guidata(handles.dKW, handles);
and the second callback is:
function SearchPath_Callback(hObject, eventdata, handles)
if exist('handles.dKW', 'var')==1
global Intensities_KW
[idatafile, idatapath] = uigetfile('*.xlsx', 'Select Excel File');
idata=xlsread(fullfile(idatapath, idatafile));
Intensities_KW=loadintensities(handles.dKW, idata);
else
waitfor(msgbox('Bitte erstmal KW eingeben'));
close(gcbf)
GUI
end
I want to pass the variable dKW from the KW function to the other one. I am also not sure if you are allowed to call the variable KW, as the function is called KW, therefore I called it dKW.
I also want to pass the variable Intensities_KW to another functions of the same GUI, how can I do this?
Thanks for your help!
댓글 수: 0
답변 (1개)
Adam
2015년 4월 16일
편집: Adam
2015년 4월 16일
In your first function you should have something more like this:
function KW_Callback(hObject, eventdata, handles)
handles.dKW = str2double(get(hObject,'string'));
guidata( hObject, handles);
It is the handles structure that you are always saving back into the GUI and the GUI in this case is represented by hObject for the purposes of the guidata function. In any callback you can use that line with hObject to save handles back into the GUI.
Never save anything other than handles into guidata though.
Don't use global variables - they are really not worth the hassle they can cause. guidata works for most cases. For those it doesn't there are alternatives of differing degrees of complexity.
As far as variable naming goes, try not to overwrite function names with variable names. If you don't want to call the function then it isn't a problem, you can do it, but it is a good habit to avoid ever doing this. I still fall for it sometimes myself simply because I don't check every variable name I use to see if there is a function with the same name. Obviously in those cases though I know I won't be using the function if there is one since I don't know it even exists!
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!