2013-12-18 2 views
0

나는 대화 기반 프로그램을 만들기 위해 wxPython을 사용하는 법을 배우고 있습니다. 나는 모두 Python IDLEApatana Studio 3 코드 위에 게재wxPython을 사용하여 대화 상자를 만드는 방법은 무엇입니까?

import wx 

#--------------------------------------------------------------------------- 

class TestPanel(wx.Panel): 
    def __init__(self, parent, log): 
     self.log = log 
     wx.Panel.__init__(self, parent, -1) 

     b = wx.Button(self, -1, "Create and Show a DirDialog", (50,50)) 
     self.Bind(wx.EVT_BUTTON, self.OnButton, b) 


    def OnButton(self, evt): 
     # In this case we include a "New directory" button. 
     dlg = wx.DirDialog(self, "Choose a directory:", 
          style=wx.DD_DEFAULT_STYLE 
          #| wx.DD_DIR_MUST_EXIST 
          #| wx.DD_CHANGE_DIR 
          ) 

     # If the user selects OK, then we process the dialog's data. 
     # This is done by getting the path data from the dialog - BEFORE 
     # we destroy it. 
     if dlg.ShowModal() == wx.ID_OK: 
      self.log.WriteText('You selected: %s\n' % dlg.GetPath()) 

     # Only destroy a dialog after you're done with it. 
     dlg.Destroy() 


#--------------------------------------------------------------------------- 


def runTest(frame, nb, log): 
    win = TestPanel(nb, log) 
    return win 


#--------------------------------------------------------------------------- 




overview = """\ 
This class represents the directory chooser dialog. It is used when all you 
need from the user is the name of a directory. Data is retrieved via utility 
methods; see the <code>DirDialog</code> documentation for specifics. 
""" 


if __name__ == '__main__': 
    import sys,os 
    import run 
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) 

:

나는 (단지 wxPython에 데모에서 복사) 다음 코드를 시도했다. 여기에 내가 가진 것이있다. Python IDLE에서

, 내가있어 :

IDLE Subprocess: no IP port passed in sys.argv.

그리고 Apatana Studio 3에서

, 나는이있어 :

Traceback (most recent call last):
File "C:\Users\User\My Documents\Aptana Studio 3 Workspace\Test Dialogue\main.py", line 61, in import run ImportError: No module named run

는 내가 무슨 생각을 알고있다? 고마워. :)

답변

1

ImportError는 가져 오려는 모듈 (.py 파일)을 찾을 수 없다는 것을 알려주는 Python 인터프리터 (Python 코드를 실행하는 프로그램)입니다. 특히, 61 행에서 가져 오기를 요청한 모듈 "run"을 찾을 수 없다는 오류가 있습니다.

파이썬에서 가져 오기를 수행하면 인터프리터는 모듈에 대한 작업 공간을 검색합니다. 그 중 하나는 현재 디렉토리이고, 나머지는 Python 라이브러리가 설치된 표준 장소입니다. 이 페이지에는 그것에 관한 정보가 있습니다 : http://docs.python.org/2/tutorial/modules.html#the-module-search-path. 명령 줄에서 프로그램을 실행하면 실제로 동일한 ImportError가 발생합니다. Python 오류입니다. Apatana Studio 3 오류가 아닙니다.

"run.py"를 Python 파일이있는 디렉토리에 복사하면 Python 인터프리터는 가져 오기를 요청할 때 쉽게 찾을 수 있습니다. 또 다른 방법은 런타임에 run.py 모듈을 그대로두고 런타임에 sys.path를 변경하거나 모듈 위치를 PYTHONPATH 변수에 추가하는 것입니다 (자세한 정보는 위의 링크 참조).

달성하려는 항목에 run.py 모듈이 필요하지 않습니다. 다음은 run.py 모듈을 가져 오지 않고 코드 예제입니다. 나는 나 자신이 내가 생각 IDLE에서 오류가 무슨 일이 일어나고 있는지 확실하지 않다가

import wx 

# This Log class is copied from the run module 
class Log(object): 
    def WriteText(self, text): 
     if text[-1:] == '\n': 
      text = text[:-1] 
     wx.LogMessage(text) 
    write = WriteText 


class TestPanel(wx.Panel): 
    def __init__(self, parent, log): 
     self.log = Log() 
     wx.Panel.__init__(self, parent, -1) 

     b = wx.Button(self, -1, "Create and Show a DirDialog", (50,50)) 
     self.Bind(wx.EVT_BUTTON, self.OnButton, b) 


    def OnButton(self, evt): 
     # In this case we include a "New directory" button. 
     dlg = wx.DirDialog(self, "Choose a directory:", 
          style=wx.DD_DEFAULT_STYLE 
          #| wx.DD_DIR_MUST_EXIST 
          #| wx.DD_CHANGE_DIR 
          ) 

     # If the user selects OK, then we process the dialog's data. 
     # This is done by getting the path data from the dialog - BEFORE 
     # we destroy it. 
     if dlg.ShowModal() == wx.ID_OK: 
      self.log.WriteText('You selected: %s\n' % dlg.GetPath()) 

     # Only destroy a dialog after you're done with it. 
     dlg.Destroy() 


class Frame (wx.Frame): 
    def __init__(self, parent): 
     wx.Frame.__init__(self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size(300, 150)) 

     panel = TestPanel(self, -1) 



class App(wx.App): 

    def OnInit(self): 
     self.frame = Frame(parent=None) 
     self.frame.Show() 
     self.SetTopWindow(self.frame) 
     return True 

if __name__ == '__main__': 
    app = App() 
    app.MainLoop() 

을 ;-) 할 수있는 더 나은 방법이있을 수 있습니다 내가 wxPython에 새로운 해요 있다고 경고합니다. 이상 하네!

+0

안녕하세요, Ben. 아주 상세한 답변을 해주셔서 감사드립니다. 정말 도움이됩니다. 추가 질문 : 클래스'TestPanel '의 생성자에있는'log'은 무엇입니까? 코드를 실행하면 디렉토리를 선택한 후 오류가 발생합니다 :'Traceback (가장 최근 호출 마지막) : OnButton의 25 번째 줄 "P :/Project Backups/Python Practice/Examples/Demo_Panel2.py"파일 self.log.WriteText ('% dlg.GetPath())을 선택했습니다. AttributeError :'int '객체에'WriteText '속성이 없습니다. 나는이 오류가'log'를 가리키고 있다고 생각한다. 고맙습니다. – ChangeMyName

+0

이 코드는 DirDialog의 wxpython 데모 코드에서 복사되며 로그는 데모에서 출력을 표시하는 데 사용됩니다. 로그에 대한 참조는 주석으로 처리 할 수 ​​있습니다. – Yoriz

+0

우수한 sleuthing! run.py 모듈에는 사용자가 선택한 것을 보여주기위한 Log 클래스가 포함되어 있습니다. Yoriz가 말했듯이 로그에 대한 참조를 삭제할 수 있습니다. 위의 예제 코드에 로그 클래스를 추가하여 해당 코드가 어떻게 적용되는지 확인할 수 있도록했습니다. 그것은 run.py에서 복사되었지만 클래스를 "새로운 스타일"클래스가 아닌 이전 스타일로 변경했습니다 (http://stackoverflow.com/questions/54867/old-style-and-new-style-classes- in-python) TestPanel의 줄을 self.log = log에서 self.log = Log()로 변경했습니다. – Ben

관련 문제