当另一个按钮处于活动状态时使用计数器更新按钮字符串

Update pushbutton string using counter when another pushbutton is active

我在打开函数中设置句柄:

function Select_A_B_OpeningFcn(hObject, eventdata, handles, varargin)

handles.output = hObject;
handles.string = '';
new_count = 1;
set(handles.counter,'String',num2str(new_count));
if isempty(varargin)
    varargin{1} = 1;
    varargin{2} = 1;
end
A = {'Apple';'Orange';'Bag';'Cowboy'};
handles.pushbutton1text = A;

new_count = str2double(handles.counter.String);
handles.pushbutton1 = handles.pushbutton1text(new_count);

guidata(hObject, handles);

然后我尝试在按下标记为 'Next' 的按钮时将手柄更改为 pushbutton1:

function next_Callback(hObject, eventdata, handles)

current_count = str2double(get(handles.counter, 'String'));
new_count = current_count+1;
set(handles.counter,'String',new_count);
   set(handles.pushbutton1,'String',get(handles.counter,'string');
    guidata(hObject, handles);

当我尝试将手柄设置为 pushbutton1 时出现以下错误: Error using set Conversion to double from cell is not possible.

我尝试了几种方法来修复错误,但都没有成功。我做错了什么?

这是一个程序化的 GUI,它可以做你想做的事,在我看来,它比 understand/debug 简单得多。您可以使用 GUIDE 轻松实现它;按钮回调之前的所有内容都可以放入 GUI Opening_Fcn

我在代码中添加了注释;如果有什么不清楚的地方请告诉我。

function DisplayFruits

clear
clc

hFig = figure('Position',[200 200 300 300]);

handles.A = {'Apple';'Orange';'Bag';'Cowboy'};
handles.counter = 1;

%// Counter text
handles.CounterTitle = uicontrol('Style','text','Position',[50 200 60 20],'String','Counter');

handles.CounterBox = uicontrol('Style','text','Position',[130 200 60 20],'String','1');

%// Content of A
handles.TextTitle = uicontrol('Style','text','Position',[50 170 60 20],'String','Content');

handles.TextBox = uicontrol('Style','text','Position',[130 170 60 20],'String',handles.A{handles.counter});

%// Pushbutton to increment counter/content
handles.PushButton = uicontrol('Style','push','Position',[130 100 80 40],'String','Update counter','Callback',@(s,e) UpdateCallback);

guidata(hFig,handles);

%// Pushbutton callback
    function UpdateCallback      

        %// Update counter
        handles.counter = handles.counter + 1;

        %// If maximum value possible, set back to 1.
        if handles.counter == numel(handles.A)+1;
            handles.counter = 1;
        end

        %// Update text boxes
        set(handles.CounterBox,'String',num2str(handles.counter));

        set(handles.TextBox,'String',handles.A{handles.counter});

        guidata(hFig,handles);
    end
end

GUI 的示例屏幕截图:

当用户按下按钮时,计数器递增,"content box" 更新。

希望对您有所帮助!

附带说明一下,我认为您在上面遇到的错误是由于此命令造成的:

handles.pushbutton1 = handles.pushbutton1text(new_count);

在这里您为按钮分配了一个字符串,但后来您尝试修改它的 String 属性 而 Matlab 不喜欢它。