2013-04-29 161 views
1

我在將wxpython中的textCtrl數據從一個類傳遞到另一個類時存在問題。我嘗試使用傳遞變量的實例方法,但如果我使用init _function,它只與程序開始時相關,並且不考慮初始啓動後對文本控制框的任何更改。嘗試了更新()或刷新(),它也沒有工作。在wxpython中將變量從一個類傳遞到另一個類

這裏是代碼簡化。

class DropTarget(wx.DropTarget): 


    def __init__(self,textCtrl, *args, **kwargs): 
      super(DropTarget, self).__init__(*args, **kwargs) 
      self.tc2=kwargs["tc2"] 
      print self.tc2 


class Frame(wx.Frame): 

    def __init__(self, parent, tc2): 
    self.tc2 = wx.TextCtrl(self, -1, size=(100, -1),pos = (170,60))#part number 

def main(): 

    ex = wx.App() 
    frame = Frame(None, None) 
    frame.Show() 
    b = DropTarget(None, kwarg['tc2']) 
    ex.MainLoop() 

if __name__ == '__main__': 
    main() 

以下傳遞變量的方法給了我一個錯誤。任何幫助表示讚賞。

回答

0
import wx 
class DropTarget(wx.DropTarget): 


    def __init__(self,textCtrl, *args, **kwargs): 
      self.tc2 = kwargs.pop('tc2',None) #remove tc2 as it is not a valid keyword for wx.DropTarget 
      super(DropTarget, self).__init__(*args, **kwargs) 

      print self.tc2 


class Frame(wx.Frame): 

    def __init__(self, parent, tc2): 
     #initialize the frame 
     super(Frame,self).__init__(None,-1,"some title") 
     self.tc2 = wx.TextCtrl(self, -1, size=(100, -1),pos = (170,60))#part number 

def main(): 

    ex = wx.App(redirect=False) 
    frame = Frame(None, None) 
    frame.Show() 
    #this is how you pass a keyword argument 
    b = DropTarget(frame,tc2="something") 
    ex.MainLoop() 

if __name__ == '__main__': 
    main() 

有在你的代碼至少有幾個錯誤...它至少使框架現在

1

這是不是最優雅的解決這個問題,但我也有類似的問題。如果您將文本轉儲到臨時文本文件,則可以隨時將其恢復。所以它會是這樣的:

tmpFile = open("temp.txt",'w') 
tmpFile.write(self.tc2.GetValue()) 
tmpFile.close() 

#when you want the string back in the next class 
tmpFile = open("temp.txt",'r') 
string = tmpFile.read() 
tmpFile.close() 
os.system("del temp.txt") #This just removes the file to clean it up, you'll need to import os if you want to do this 
相關問題