临时解决方案正在使用:setappdata 和 getappdata。
例子:
function pushbutton1_Callback(hObject, eventdata, handles)
setappdata(0, 'pathname', 'abc');
function pushbutton2_Callback(hObject, eventdata, handles)
pathname = getappdata(0, 'pathname'); % Return 'abc'.
另一个简单的解决方案是在父图形的UserData 成员中传递pathname。
当两个按钮在同一个图中时,hObject.Parent 是图中的handle,UserData 元素是在 GUI 对象之间传递数据的“准备”。
例子:
function pushbutton1_Callback(hObject, eventdata, handles)
hObject.Parent.UserData.pathname = 'abs';
function pushbutton2_Callback(hObject, eventdata, handles)
pathname = hObject.Parent.UserData.pathname; %Value is 'abc'
更多信息请参考:https://www.mathworks.com/help/matlab/creating_guis/share-data-among-callbacks.html
不使用guide工具的完整代码示例:
我在没有使用guide 工具的情况下创建了以下示例,因为没有简单的方法在堆栈溢出中传递guide 的fig 文件。
function TestNoGuide()
clear all
close all
% Create figure
hObject = figure('position', [800 400 260 100], 'Toolbar','none');
% create structure of handles
handles = guihandles(hObject);
handles.hObject = hObject;
handles.pushbutton1 = uicontrol('style', 'pushbutton', 'position',[10 20 100 40], 'string' , 'Button1');
handles.pushbutton2 = uicontrol('style', 'pushbutton', 'position',[150 20 100 40], 'string' , 'Button2');
set(handles.pushbutton1, 'callback', {@pushbutton1_Callback, handles});
set(handles.pushbutton2, 'callback', {@pushbutton2_Callback, handles});
%Save the structure
guidata(hObject);
end
function pushbutton1_Callback(hObject, eventdata, handles)
[filename, pathname] = uigetfile({'*.xlsx;*.xls'});
setappdata(0, 'filename', filename);
setappdata(0, 'pathname', pathname);
end
function pushbutton2_Callback(hObject, eventdata, handles)
filename = getappdata(0, 'filename');
pathname = getappdata(0, 'pathname');
waitfor(warndlg(['filename = ', filename, ' pathname = ', pathname]));
end
检查一下,告诉我它是否在你的机器上工作......