2014-10-27 80 views
0

回調另一個uicontrol的我寫了這樣的代碼在Matlab:傳遞編輯字符串uicontrol在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 

我想通過從編輯uicontrol到按鈕的回調文本。當我這樣做時,傳遞的值是在聲明uicontrol時設置的舊值。 所以即,我運行GUI並在編輯中的值爲5。我將它覆蓋爲20,但按下按鈕後,正在傳遞的值仍然是5

這種方法有什麼問題?它如何以不同的方式完成? 預先感謝您!

回答

1

在我看來,使用圖形用戶界面的最佳選擇是使用GUI的句柄結構,其中除了(這是最酷的部分)之外,每個uicontrols都與相關的屬性一起存儲,無論您想要什麼存儲在其中,例如變量。

所以我修改了你的代碼,以利用句柄結構。我並不完全清楚你想要什麼,但在我的例子中,按鈕用於更新第一個編輯框內容的第二個編輯框的內容。這是非常基本的,但它應該可以幫助您獲得手柄和手柄結構的感覺。如果有什麼不清楚的,請告訴我!

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 

您可以通過同樣的方式,我實現了PushButtonCallback加入您的回調函數(test_script)自定義此GUI。希望我明白你想要什麼:)

+0

太棒了!我正在尋找類似的東西:)我想我需要的是這行: 'guidata(handles.figure,句柄);' – monkog 2014-10-27 20:13:14

+0

那麼偉大!是的,這是重要的路線;每當將某些內容更改爲句柄結構時使用它,並且需要更新它。請注意,我已將您的符號從'window ...'更改爲'句柄...',但它們完全相同。 :) – 2014-10-27 20:17:18