How to write GUI pushbutton callback function when you have the code(with no GUI)

I have the code for a game that runs well, but I want to add a graphical user interface(GUI) to that. To start with, I created a pushbutton(New Game) and pasted the entire code under the "function pushbutton1_Callback(hObject, eventdata, handles)". I thought I could run the game code by clicking the New Game button, but it didn't work. The error is "Undefined function or variable 'pushbutton1_Callback'." and "Error while evaluating UIControl Callback". So I'm wondering if there are certain special rules in writing callback function. How do you do it when you already have a code? Thank you!!

回答(1 个)

It does not take much.
function MyGame
pushbutton1 = uicontrol('Style', 'push', 'String', 'New game', 'Callback', @pushbutton1_Callback);
function pushbutton1_Callback(hObject, eventdata)
... now put some code for starting the game here
Those two can go into MyGame.m or you can put the function pushbutton1_Callback into pushbutton1_Callback.m as long as it is the first function of that separate .m file.

类别

帮助中心File Exchange 中查找有关 App Building 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by