MATLAB Answers

How to use GUI to change a value of a variable and use that variable in a script

조회 수: 41(최근 30일)
Nora Khaled
Nora Khaled 21 Aug 2017
Commented: Nora Khaled 22 Aug 2017
Hi!
I have a program that opens a GUI while its running, the thing is I want the user to press one of the buttons on the GUI. the user selection should change the value of the variable. and then the main program continue running after the GUI.
my problem is that I don't know how to make a button event and how to get the value of the variable back to the main program?

  댓글 수: 2

Adam
Adam 21 Aug 2017
gives an example. You can also do it in GUIDE, using the OutputFcn and a modal GUI utilising uiwait to ensure the OutputFcn only triggers when you close the dialog.

로그인 to comment.

답변 수 (2)

Jan
Jan 21 Aug 2017
You can either use GUIDE or create the GUI prgrammatically by code. Perhaps a simple inputdlg, questdlg or listdlg is sufficient already. See
doc inputdlg
doc questdlg
doc listdlg
Creating an own dialog and obtaining a value is easy also:
function Reply = myFirstGUI
FigH = figure('Position', [100, 100, 400, 300], ...
'Menubar', 'none');
ButtonH = uicontrol('Style', 'PushButton', 'String', 'Click me!', ...
'Position', [20, 20, 360, 30], ...
'Callback', {@myCallback, FigH});
disp('Waiting for the figure to close...');
uiwait(FigH);
disp('Waiting was resumed...');
delete(FigH);
Reply = '???' % You did not explain, how the GUI creates the value to be replied
end
function myCallback(ButtonH, EventData, FigH)
disp('Button was pressed.');
uiresume(FigH);
end
Now call this from the main function:
Reply = myFirstGUI();

Walter Roberson
Walter Roberson 21 Aug 2017
Example:
faster_button = uicontrol('style','push', 'UserData', 0, 'callback', @faster);
and
function faster(hObject, event)
current_speed = get(hObject, 'UserData');
current_speed = current_speed + 10;
set(hObject, 'UserData', current_speed);
and
while true
current_speed = get(faster_button, 'UserData');
x = x + current_speed;
scatter(x, current_speed);
hold on;
pause(1); %also triggers drawing
end
Note here that pushing the button does not force the script to change the value it is using: the script has to ask what the current value is.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by