Why the pushbutton does not work?
6 views (last 30 days)
Show older comments
Sergey Lopatnikov
on 26 Sep 2021
Answered: Sergey Lopatnikov
on 26 Sep 2021
I wrote a simple function which incorporates creation of a figure and pusbutton.
I expected that after pressing the button, the function will provide the answer based on what callcack function of pushbutton is performing:
function [B,success] = TGA_MAIN(X,Y,L,W,Xb,Yb,Lb,Wb, STRING)
global B
B=0,
success=0
Xa=X;
Ya=Y;
La=L;
Wa=W;
p=Xb;
r=Xb;
s=Lb;
t=Wb;
STR=STRING;
handles.load_fig=figure('MenuBar','none','Position',[Xa,Ya,La,Wa])
handles.load_button=uicontrol(handles.load_fig,'style','pushbutton','string',STR,'position',[p,r,s,t])
set(handles.load_button,'callback',{@load_callback,handles})
function load_callback(gcf,event_data,handles)
global B
x=5;
B=x;
success=1;
My expectation was that after I press button, the answer must be q=5,s=1.
However, I see q=0,s=0, which I defined in very beginning of soft.
The pressing of the button changes nothing...
Example of call:
[q,s]=TGA_MAIN(500,400,400,300,120,120,120,50, 'STRING')
result is:
q =
0
s =
0
1 Comment
Rik
on 26 Sep 2021
You shouldn't use globals to share data to a callback. Use the guidata struct instead. For general advice and examples for how to create a GUI, have look at this thread.
Accepted Answer
More Answers (4)
Image Analyst
on 26 Sep 2021
Set a breakpoint in the callback function. Does it stop there? What happens if you step through it line by line?
4 Comments
Image Analyst
on 26 Sep 2021
OK you're doing it the harder way. But the question is the same. Set a breakpoint there and see if you step into that function. Do you?
Sergey Lopatnikov
on 26 Sep 2021
1 Comment
Image Analyst
on 26 Sep 2021
Global does not automatically make a variable global everywhere. Any place that you want a globa variable to be seen, you must have
global B
global success
otherwise they'll be local variables, not the global variables you expected.
Sergey Lopatnikov
on 26 Sep 2021
1 Comment
Image Analyst
on 26 Sep 2021
You posted this as an "Answer", (rather than as a comment to my Answer), so have you answered it?
Is the code in your original post your entire program?
Steven Lord
on 26 Sep 2021
MATLAB is behaving correctly. You create the pushbutton and give it a callback and then immediately exit from the function in which it was created, returning the values of the outputs that they have at that time. By default MATLAB will not wait for you to push the button (and so update the global variable) in the workspace of that function. You could try to make MATLAB wait using something like uiwait so the TGA_MAIN function doesn't return until the figure with that button gets closed or some property updated.
0 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!