【问题标题】:Passing Edit uicontrol string to callback of another uicontrol in Matlab将 Edit uicontrol 字符串传递给 Matlab 中另一个 uicontrol 的回调
【发布时间】:2014-10-28 04:18:25
【问题描述】:

我在 Matlab 中写了这样的代码:

function[] = gui_function()
window.value1 = uicontrol('style', 'edit', ...
                          'string', '5', ...
                          'callback', @is_number);
window.computeButton = uicontrol('style', 'push', ...
    'callback', {@test_script, str2double(get(window.value1, 'string'))});
end

function[] = test_script(varargin)
value1 = varargin{3};
end

我想将 Edit uicontrol 中的文本传递给 Button 的回调。当我按照以下方式进行操作时,传递的值是在声明 uicontrol 时设置的旧值。 所以即。我运行 GUI,编辑中的值为 5。我将其覆盖为 20,但按下按钮后,正在传递的值仍然是 5

这种方法有什么问题?如何以不同的方式完成? 提前谢谢!

【问题讨论】:

    标签: matlab callback


    【解决方案1】:

    在我看来,使用 GUI 时最好的选择是使用 GUI 的句柄结构,其中除了(这是很酷的部分)您想要存储的任何内容之外,每个 uicontrol 及其相关属性都存储在其中在其中,例如变量。

    所以我修改了您的代码以使用句柄结构。我不完全清楚您想要什么,但在我的示例中,按钮用于使用第一个编辑框的内容更新第二个编辑框的内容。这是非常基本的,但它应该可以帮助您了解句柄和句柄结构。如果有什么不清楚的地方请告诉我!

    function gui_function()
    
    
    ScreenSize = get(0,'ScreenSize');
    
    handles.figure = figure('Position',[ScreenSize(3)/2,ScreenSize(4)/2,400,285]);
    
    
    handles.Edit1 = uicontrol('style', 'edit','Position',[100 150 75 50], ...
        'string', '5');
    
    handles.Edit2 = uicontrol('style', 'edit','Position',[100 80 75 50], ...
        'string', 'Update me');
    
    handles.computeButton = uicontrol('style', 'push','Position',[200 100 75 75],'String','PushMe', ...
        'callback', @PushButtonCallback);
    
    
    guidata(handles.figure, handles); %// Save handles to guidata. Then it's accessible form everywhere in the GUI.
    
    function PushButtonCallback(handles,~)
    
    handles=guidata(gcf); %// Retrieve handles associated with figure.
    
    TextInBox1 = get(handles.Edit1,'String');
    set(handles.Edit2,'String',TextInBox1); %// Update 2nd edit box with content of the first.
    
    %// Do whatever you want...
    guidata(handles.figure, handles); %// DON'T forget to update the handles structure
    

    您可以通过添加函数回调 (test_script) 来自定义此 GUI,方法与我实现 PushButtonCallback 的方式相同。希望我明白你想要什么:)

    【讨论】:

    • 太棒了!我正在寻找类似的东西 :) 我想我需要的是这条线:guidata(handles.figure, handles);
    • 那太好了!是的,这很重要。每当您将某些内容更改为句柄结构并且需要更新它时,请使用它。请注意,我将您的符号从“窗口...”更改为“句柄...”,但完全一样。 :)
    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多