Reputation: 1638
Is there a way to create two toggle buttons in a Matlab GUI such that one toggles the other? In other words, if button A is on, how can I create a button B that when turned on makes A go off?
Upvotes: 1
Views: 8497
Reputation: 9313
I have version R2009a, so I don't know if this works for you or not:
I defined two push buttons with guide
(with default names). When the first is clicked it is disabled (Enable: Off), its Value set to 1 and its String to On; the second push button is set to the other state. A similar behavior is given to the other button.
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
set(handles.pushbutton1,'Value',1,'String','On','Enable','Off')
set(handles.pushbutton2,'Value',0,'String','Off','Enable','On')
get(handles.pushbutton1)
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
set(handles.pushbutton1,'Value',0,'String','Off','Enable','On')
set(handles.pushbutton2,'Value',1,'String','On','Enable','Off')
If you want to toggle the behavior of button2 according to the state of button1 then do the following:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% this toggles button1 between 0 and 1 and its label between 'On' and 'Off'
p = 1-get(handles.pushbutton1,'Value');
set(handles.pushbutton1,'Value',p)
if p==0
set(handles.pushbutton1,'String','Off')
else
set(handles.pushbutton1,'String','On')
end
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% Behavior of button2 is dependent on state of button1
p = get(handles.pushbutton1,'Value');
if p==0
% Do this when button1 has its label to 'Off' (and Value to 0)
else
% This will execute when button1 has a Value of 1 (and its label showing 'On')
end
Is this what you need?
Upvotes: 0
Reputation: 1638
This is my code:
function button1_Callback(hObject, eventdata, handles)
if get(hObject,'Value')==1
%do something here
else
%do something else (in my case delete a video object)
If I now put a second button and use the command
set(handles.button1,'Value',0)
The result is that my first button toggles but the command after the else
is not executed.
Is there a way to execute that command as well?
Upvotes: 1