Это потому, что вы испортили код, сгенерированный GUIDE. Обычно определение функции обратного вызова выглядит так:
function SomeButton_Callback(hObject, eventdata, handles)
Но в своем коде вы пишете
function open1_Callback(filename, hObject, eventdata, handles)
Но руководство по-прежнему отправляет в функцию обратного вызова три аргумента (hObject
, eventdata
и handles
) именно в этом порядке. Итак, MatLab запутался и выдал ошибку.
Вам лучше поместить свое имя файла в структуру handles
в функции *_OpeningFcn
, а затем использовать его оттуда во всех обратных вызовах.
В конце вашего *_OpeningFcn
вы должны добавить следующее:
% Here you may put all the data you need in your GUI
% just be sure to keep all the fields in handles structure from overwriting
% Safe way is to add MyData field and add all the stuff to it
handles.MyData.ListFileName = 'FileName.txt';
% the next two lienes are generated by GUIDE
% Update handles structure
guidata(hObject, handles);
Затем в функции обратного вызова вашей кнопки
function open1_Callback(hObject, eventdata, handles)
% hObject handle to open1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% open the file
fid=fopen(handles.MyData.ListFileName);
% load lines from the file
% and do what is needed
for N=6:1:10
imagename = fgetl(fid);
if ~ischar(imagename), break, end % Meaning: End of File...
[x,map]=imread(imagename);
rgb=ind2rgb(x,map);
ax = handles.(sprintf('axes%d', N));
image(rgb, 'Parent', ax);
set(ax, 'Visible','off');
%xlabel(imagename);
end
% dont' forget to close the file
fclose(fid);
% If your callback function modifies data in handles.MyData structure
% you MUST update it back otherwise subsequent call-backs will not see it
guidata(hObject, handles);
И да, все файлы, которые вы открываете с помощью функции fopen
, должны быть закрыты с помощью fclose
. Вы узнаете это на собственном горьком опыте, когда не сможете обновить свой файл в своем любимом редакторе, потому что его использует другая программа.
См. также (Создание универсальных переменных в графическом интерфейсе MATLAB)
ОБНОВЛЕНО, чтобы отразить обсуждение в комментариях:
Чтобы добиться желаемого поведения, я бы сделал следующее:
В конце вашего *_OpeningFcn
добавьте следующее:
% Here you may put all the data you need in your GUI
% just be sure to keep all the fields in handles structure from overwriting
% Safe way is to add MyData field and add all the stuff to it
handles.MyData.ListFileName = 'FileName.txt';
handles.MyData.FileNames = {}; % here we store all the image names
handles.MyData.Images = {}; % here we store all images
% Now we parse data from the file
fid=fopen(handles.MyData.ListFileName);
for N=6:1:10
imagename = fgetl(fid);
if ~ischar(imagename), break, end % Meaning: End of File...
[x,map]=imread(imagename);
rgb=ind2rgb(x,map);
ax = handles.(sprintf('axes%d', N));
image(rgb, 'Parent', ax);
set(ax, 'Visible','off');
%xlabel(imagename);
% store file name and image itself for later use
handles.MyData.Images{N} = rgb;
handles.MyData.FileNames{N} = imagename;
% we have buttons like open1 open2 open3 etc...
% add some info to the open buttons
% so they will be aware which image they display
btn = handles.(sprintf('open%d', N));
set(btn, 'UserData',N);
end
% dont' forget to close the file
fclose(fid);
% the next two lienes are generated by GUIDE
% Update handles structure
guidata(hObject, handles);
Затем в функции обратного вызова для вашей кнопки открытия выполните следующие действия.
function open1_Callback(hObject, eventdata, handles)
% hObject handle to open1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
N = get(hObject,'UserData');
rgb = handles.MyData.Images{N};
ax = handles.(sprintf('axes%d', N));
% create figure in 'modal' mode, so user have to close it to continue
figure('WindowStyle','modal', 'Name',handles.MyData.FileNames{N} );
% show image
image(rgb, 'Parent', ax);
set(ax, 'Visible','off');
% If your callback function modifies data in handles.MyData structure
% you MUST update it back otherwise subsequent call-backs will not see it
guidata(hObject, handles);
По сути, этот обратный вызов универсален: он должен работать без модификаций для всех ваших открытых кнопок. Вы даже можете изменить функцию обратного вызова кнопок open2
, open3
... в GUIDE на open1_Callback
.
person
anandr
schedule
11.05.2013
open
. Чтобы зритель остался доволен изображением большого размера - person Chethan   schedule 11.05.2013