从不同的wxPanel获取TextCtrl的值

时间:2009-11-29 18:39:51

标签: python wxpython

我试图让我的第一个wxWindow应用程序工作,我遇到了以下困难:
我创建wxPanel并添加一个wxNotebook对象。然后我将一个页面添加到从另一个wxPanel对象创建的笔记本中。如何在第二个wxPanel中访问TextCtrl的值?

import wx

class BasicApp(wx.App):
  def OnInit(self):
    frame = BasicFrame(None, -1, "Test App")
    panel = BasicPanel(frame, -1);
    frame.Show(True)
    self.SetTopWindow(frame)
    return True;

class BasicFrame(wx.Frame):
  def __init__(self, parent, ID, title):
    wx.Frame.__init__(self, parent, ID, title,
                     wx.DefaultPosition, wx.Size(400, 300))
    self.CreateStatusBar()

class BasicPanel(wx.Panel):
  def __init__(self, parent, id):
    wx.Panel.__init__(self, parent, id)

    self.lblText1 = wx.StaticText(self, -1, "Text1:");
    self.txtText1 = wx.TextCtrl(self, 1001, "Text1", size = wx.Size(140, -1));
    self.line1 = wx.BoxSizer(wx.HORIZONTAL);
    self.line1.Add(self.lblText1, 0, wx.EXPAND);
    self.line1.Add(self.txtText1, proportion=1, flag=wx.LEFT, border=5);

    self.nb = wx.Notebook(self, -1);
    tab1 = Tab1(self.nb, -1);
    self.nb.AddPage(tab1, "Tab1");

    self.sizer = wx.BoxSizer(wx.VERTICAL)
    self.sizer.Add(self.line1, 0, wx.EXPAND)
    self.sizer.Add(self.nb, 1, wx.EXPAND)

    self.SetSizer(self.sizer)
    self.SetAutoLayout(1)
    self.sizer.Fit(self)
    self.Show(1)

class Tab1(wx.Panel):
  def __init__(self, parent, id):
    wx.Panel.__init__(self, parent, id);

    self.lblText2 = wx.StaticText(self, -1, "Text2:");
    self.txtText2 = wx.TextCtrl(self, 1101, "Text2", size = wx.Size(140, -1));
    self.line1 = wx.BoxSizer(wx.HORIZONTAL);
    self.line1.Add(self.lblText2, 0, wx.EXPAND);
    self.line1.Add(self.txtText2, 0, wx.EXPAND);

    self.lblMessage = wx.StaticText(self, -1, "Message:");
    self.txtMessage = wx.TextCtrl(self, 1102, "", style = wx.TE_MULTILINE);

    self.cmdCreate = wx.Button(self, 1103, "Create");
    self.cmdCreate.Bind(wx.EVT_BUTTON, self.Create_OnClick)
    self.line3 = wx.BoxSizer(wx.HORIZONTAL);

    self.sizer = wx.BoxSizer(wx.VERTICAL)
    self.sizer.Add(self.line1, 0, wx.EXPAND)
    self.sizer.Add(self.lblMessage, 0, wx.EXPAND)
    self.sizer.Add(self.txtMessage, 1, wx.EXPAND)
    self.sizer.Add(self.cmdCreate, 0, wx.LEFT)

    self.SetSizer(self.sizer)
    self.SetAutoLayout(1)
    self.sizer.Fit(self)
    self.Show(1)
  def Create_OnClick(self, event):
    text1 = "";
    text2 = self.txtText2.GetValue();
    self.txtMessage.SetValue(text1 + " " + text2);

app = BasicApp(0)
app.MainLoop()

更具体地说,我希望能够在Create_OnClick()方法中访问txtText1的值。怎么可以实现呢?

1 个答案:

答案 0 :(得分:2)

一种解决方案是将控件传递给选项卡的构造函数,然后您可以直接引用它。例如:

class Tab1(wx.Panel):
  def __init__(self, parent, id, textCtrl1):
    wx.Panel.__init__(self, parent, id);
    self.textCtrl1 = textCtrl1
  ...
  def Create_OnClick(self, event):
    text1 = self.textCtrl1

另一种解决方案是将Create_OnClick处理程序移动到基本面板,因为它知道所有其他面板(以及它们的子节点)。或者,创建一个单独的控制器类,它知道各种小部件,并且可以拥有代表所有小部件的处理程序。