Behavior of callback function?

2 ビュー (過去 30 日間)
lazymatlab
lazymatlab 2020 年 4 月 4 日
コメント済み: lazymatlab 2020 年 4 月 6 日
Hello,
I wanted to break out of a while-loop when a pushbutton is clicked on a figure, so I wrote the code below.
function callbackTest1
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback','pressed=1');
pressed = 0;
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
end
But, when I click the pushbutton, 'pressed=1' is displayed on command window and it does not get out of while loop.
In addition, it is suggested that 'disp('button pressed')' part can't be reached which I really don't understand.
On the other hand, the code below works as expected.
The only thing changed is that it's a script, not a function. Everything else is the same.
% callbackTest_script
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback','pressed=1');
pressed = 0;
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
Weird thing is that the same suggestion (disp('button pressed') can't be reached) is displayed but it works fine.
Finally, I figured out that I have to write the code like this.
function callbackTest2
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback',@press);
pressed = 0;
function press(~,~)
pressed = 1;
end
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
end
1) Why does callbackTest1 not work while callbackTest_script does?
2) In callbackTest1 and callbackTest_script, why can't "disp..." be reached?
3) Anything else I should know about what's behind the behavior of callback function?
4) Is there a better way to do this than callbackTest2?
Thank you.

採用された回答

Walter Roberson
Walter Roberson 2020 年 4 月 4 日
'Callback','pressed=1'
Callbacks specified as character vectors are evalin('base') and so only affect the base workspace, not local variables.
You need to use one of the techniques to share variables; Share . Your callbackTest2 is an example of using a shared variable.
  1 件のコメント
lazymatlab
lazymatlab 2020 年 4 月 6 日
Thanks! (especially for the faq page!)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by