Programming a GUI in multiple files

5 次查看(过去 30 天)
David Schulz
David Schulz 2011-10-10
I am creating a GUI programmatically, and it is getting quite large. All the information and examples I have been able to find about programming a GUI puts all the code in one file. Is there any way to split things up into several file?
For example, is there a way to define the components in one file and define the callbacks in a separate file?

回答(2 个)

Sean de Wolski
Sean de Wolski 2011-10-10
I would recommend keeping all of the callbacks in one file. However, you can easily have each callback call another mfile with the necessary information. e.g.
function some_button_callback(src,evt)
% do something with the event and pi
anotherfile(evt,pi);
  1 个评论
Walter Roberson
Walter Roberson 2011-10-10
I would not especially recommend keeping all of the callbacks in one file: it just adds pointless overhead in my opinion.
Now, adopting a naming convention to clearly indicate a callback file: that can be valuable.

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2011-10-10
Yes, go ahead and split up as appropriate.
Things to keep in mind:
1) MATLAB can only locate the first function in a file from outside of the file, unless that first function specifically makes handles to the other functions available. For example, you could code
function callbacks = GUIcallbacks
callbacks = struct('Pushbutton1', @push1Callback, 'Freds_listbox', @fredlistCB);
end
function push1Callback(hObject, evt, handles)
...
end
function fredlistCB(hObject, evt, handles);
...
end
Then the main routine could call GUIcallbacks to get back a structure of function handles, and could set() the appropriate graphic object property to the appropriate handle.
2) Even if you have everything in one file, if you code callbacks as strings instead of as function handles, then those strings are always evaluated in the base workspace. The base workspace will never be able to find a function that is not the first function in the file (not unless you use a mechanism such as in #1)
3) Using one file per routine referenced from outside the file works fine... unless, that is, you want to start using nested functions.

类别

Help CenterFile Exchange 中查找有关 Printing and Saving 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by