wxpython sample

公司之前上传log都是用脚本的,最近在学wxpython,所以小试牛刀了一下,改了UI界面,效果还不错,记录一下,哈哈哈,wxpython代码如下:

class Mythread(threading.Thread):
    def __init__(self,window):
        super(Mythread,self).__init__()
        self.window = window
        #self.flag = threading.Event()
        #self.flag.clear() #set flag False
        self.__Exit = False

    def run(self):
        self.window.run()
        self.__Exit = True

    def stop(self):
        if self.__Exit:
            os._exit(0)
        else:
            os._exit(1)

class MyApp(wx.App):
    def __init__(self):
        super(MyApp,self).__init__()

class MyFrame(wx.Frame):
    def __init__(self,title,size):
        super(MyFrame,self).__init__(None,wx.ID_ANY,title=title,size=size)
        self.ResetRunningStatus()
        self.FilePath = None
        self.GetAccount()
        self.Center()
        self.InitStatusBar()
        self.InitMenuBar()
        self.InitWindow()

    def InitWindow(self):
        ParentWindow=wx.SplitterWindow(self)
        self.lwindow=wx.Panel(ParentWindow)
        self.rwindow=wx.Panel(ParentWindow)
        ParentWindow.SplitVertically(self.lwindow,self.rwindow,168)#168
        ParentWindow.SetMinimumPaneSize(50)
        self.InitLWindow()
        self.InitRWindow()

    def InitLWindow(self):
        self.lwindow.SetBackgroundColour('#AABBCC')
        LBox = wx.BoxSizer(wx.VERTICAL)

        ####################Name#####################
        nm_staticbox = wx.StaticBox(self.lwindow,-1,'Account:')
        nm_sizer = wx.StaticBoxSizer(nm_staticbox,wx.VERTICAL)
        nm_box = wx.BoxSizer(wx.HORIZONTAL)
        nm_input_box = wx.BoxSizer(wx.HORIZONTAL)

        username = wx.StaticText(self.lwindow,-1,"UserName")
        passwd = wx.StaticText(self.lwindow,-1,"Passwd")
        self.username_input = wx.TextCtrl(self.lwindow,-1,style=wx.TE_LEFT,value=self.default_username,size=(50,20))
        self.passwd_input = wx.TextCtrl(self.lwindow,-1,style=wx.TE_LEFT|wx.TE_PASSWORD,value='12345678',size=(50,20))

        nm_box.Add(username,0,wx.LEFT,1)
        nm_box.Add(passwd,0,wx.LEFT, 15)
        nm_input_box.Add(self.username_input,0,wx.LEFT, 10)
        nm_input_box.Add(self.passwd_input,0,wx.LEFT, 20)

        ##############domain#################
        dm_staticbox = wx.StaticBox(self.lwindow,-1,'Domain:')
        dm_sizer = wx.StaticBoxSizer(dm_staticbox,wx.VERTICAL)
        dm_box = wx.BoxSizer(wx.HORIZONTAL)
        dm_input_box = wx.BoxSizer(wx.HORIZONTAL)

        username = wx.StaticText(self.lwindow,-1,"Domain:")
        passwd = wx.StaticText(self.lwindow,-1,"Project")
        self.domain_input = wx.TextCtrl(self.lwindow,-1,style=wx.TE_LEFT,value=self.default_domain,size=(50,20))
        self.project_input = wx.TextCtrl(self.lwindow,-1,style=wx.TE_LEFT,value=self.default_project,size=(50,20))

        dm_box.Add(username,0,wx.LEFT,1)
        dm_box.Add(passwd,0,wx.LEFT, 15)
        dm_input_box.Add(self.domain_input,0,wx.LEFT, 10)
        dm_input_box.Add(self.project_input,0,wx.LEFT, 20)
        #######################Parameter##########################
        para_staticbox = wx.StaticBox(self.lwindow,-1,'Parameter:')
        para_sizer = wx.StaticBoxSizer(para_staticbox,wx.VERTICAL)
        para_box = wx.BoxSizer(wx.HORIZONTAL)
        prompt_box = wx.BoxSizer(wx.HORIZONTAL)

        para_prompt = wx.StaticText(self.lwindow,-1,'eg.')
        para_prompt_value = wx.StaticText(self.lwindow,-1,'2,3,4-6,9,14')
        para_line = wx.StaticText(self.lwindow,-1,"Line :")
        self.para_line_input = wx.TextCtrl(self.lwindow,-1,style=wx.TE_LEFT,size=(100,20))

        prompt_box.Add(para_prompt,0,wx.LEFT|wx.RIGHT|wx.EXPAND,10)
        prompt_box.Add(para_prompt_value,0,wx.LEFT|wx.RIGHT|wx.EXPAND,5)
        para_box.Add(para_line,0,wx.LEFT|wx.RIGHT|wx.EXPAND)
        para_box.Add(self.para_line_input,0,wx.LEFT|wx.RIGHT|wx.EXPAND,5)

        ##################################################

        nm_sizer.Add(nm_box,0,wx.ALL|wx.CENTER, 1)
        nm_sizer.Add(nm_input_box,0,wx.ALL|wx.CENTER, 1)

        dm_sizer.Add(dm_box,0,wx.ALL|wx.CENTER, 1)
        dm_sizer.Add(dm_input_box,0,wx.ALL|wx.CENTER, 1)

        para_sizer.Add(prompt_box,0,wx.LEFT,5)
        para_sizer.Add(para_box,0,wx.LEFT,5)

        LBox.Add(nm_sizer,0,wx.ALL|wx.LEFT|wx.RIGHT,10)
        LBox.Add(dm_sizer,0,wx.ALL|wx.LEFT|wx.RIGHT,10)
        LBox.Add(para_sizer,0,wx.ALL|wx.LEFT|wx.RIGHT,10)

        startbutton = wx.Button(self.lwindow,label=u'Start',size=(50,30),pos=(0,30))
        self.Bind(wx.EVT_BUTTON,self.ButtonStart,startbutton)
        LBox.Add(startbutton,0,wx.ALL|wx.EXPAND,10)
        self.lwindow.SetSizer(LBox)

    def InitRWindow(self):
        self.rwindow.SetBackgroundColour('#4F9D9D')
        self.logtext = wx.TextCtrl(self.rwindow, style=wx.TE_MULTILINE|wx.TE_RICH2|wx.TE_READONLY)
        self.logtext.SetMaxLength(0)

        self.points=self.logtext.GetFont().GetPointSize()
        self.font=wx.Font(self.points+3,wx.DEFAULT,wx.NORMAL,wx.BOLD,False)
        #self.font=wx.Font(self.points+3,wx.ROMAN,wx.ITALIC,wx.BOLD,True)
        #wx.Font(pointSize,family,style,weight,underline)
        #pointSize:wx.DEFAULT,wx.MODERN,wxROMAN,wx.SCRIPT,wx.SWISS
        #sytle:wx.MORMAL,wx.SLANT,wx.ITALIC
        #weight:wx.NORMAL,wx.LIGHT,wx.BOLD
        #True :underline or not

        statictext=wx.StaticText(self.rwindow,-1,label='Log Area')
        statictext.SetForegroundColour(wx.BLACK)
        #statictext.SetBackgroundColour(wx.WHITE)
        RBox=wx.BoxSizer(wx.VERTICAL)
        RBox.Add(statictext,0,flag=wx.ALL|wx.CENTER,border=2)
        RBox.Add(self.logtext,1,flag=wx.ALL|wx.EXPAND,border=2)
        self.rwindow.SetSizer(RBox)

    def InitMenuBar(self):
        menuBar = wx.MenuBar()
        filemenu = wx.Menu()
        aboutmenu = wx.Menu()

        menuopen = filemenu.Append(wx.ID_OPEN,'Open','打开一个文件')
        filemenu.AppendSeparator()
        menusave = filemenu.Append(wx.ID_SAVE,'Save','保存当前设置')
        filemenu.AppendSeparator()
        menuexit = filemenu.Append(wx.ID_EXIT,'Exit','退出程序')
        menuBar.Append(filemenu,'File')

        menuabout = aboutmenu.Append(wx.ID_ABOUT,'Info','Information')
        menuBar.Append(aboutmenu,'Info')

        self.Bind(wx.EVT_MENU,self.Exit,menuexit)
        self.Bind(wx.EVT_MENU,self.Info,menuabout)
        self.Bind(wx.EVT_MENU,self.Open,menuopen)
        self.Bind(wx.EVT_MENU,self.Save,menusave)

        self.SetMenuBar(menuBar)

    def InitStatusBar(self):
        statusbar = self.CreateStatusBar()
        #statusbar.SetFieldsCount(2)
        #statusbar.SetStatusWidths([-1,-3])

    def GetAccount(self):
        self.nm_file_path = r'C:\\temp'
        if not os.path.exists(self.nm_file_path):
            os.system('mkdir {}'.format(self.nm_file_path))
        self.nm_file_name = 'nm.json'
        self.nm_file = os.path.join(self.nm_file_path,self.nm_file_name)
        if not os.path.exists(self.nm_file):
            self.default_username = 'xiadx'
            self.default_passwd = 'Test'
            self.default_domain = 'DCG'
            self.default_project = 'BKC'
            nm_dict = {'User':self.default_username,
                       'Passwd':self.default_passwd,
                       'Domain':self.default_domain,
                       'Project':self.default_project}
            with open(self.nm_file,'w') as f:
               json.dump(nm_dict,f)
        else:
            with open(self.nm_file,'r') as f:
                nm_dict = json.load(f)
                self.default_username = nm_dict['User']
                self.default_passwd = nm_dict['Passwd']
                self.default_domain = nm_dict['Domain']
                self.default_project = nm_dict['Project']

    def ResetRunningStatus(self):
        self.running_status = True

    def ButtonStart(self,event):
        if self.running_status:
            self.job = Mythread(self)
            self.job.start()
            self.running_status = False
        else:
            self.LogMessage('Job is running')

    def ButtonCancel(self):
        pass

    def LogMessage(self,message,colour='BLACK'):
        self.logtext.SetDefaultStyle(wx.TextAttr(colour,wx.WHITE,self.font))
        self.logtext.AppendText("[{0}]:{1}\n".format(time.strftime('%H:%M:%S'),message))

    def Save(self,event):
        self.default_username = self.username_input.GetValue()
        self.default_passwd = self.passwd_input.GetValue()
        self.default_domain = self.domain_input.GetValue()
        self.default_project = self.project_input.GetValue()
        nm_dict = {'User':self.default_username,
                    'Passwd':self.default_passwd,
                    'Domain':self.default_domain,
                    'Project':self.default_project}
        with open(self.nm_file,'w') as f:
               json.dump(nm_dict,f)

    def Exit(self,event):
        try:
            if self.job:
                self.job.stop()
        except:
            self.Close()

    def Info(self,event):
        self.messageinfo='Author:xiadx\nDate:2019/5/21\nVersion:0.1'
        message = wx.MessageDialog(self,'{}'.format(self.messageinfo),'INFO',wx.OK)
        message.ShowModal()
        message.Destroy()

    def GetParameter(self):
        tmp_line = self.para_line_input.GetValue()
        if tmp_line:
            para_linenumber=[]
            try:
                for i in tmp_line.split(','):
                    if '-' in i:
                        v1 = int(i.split('-')[0])
                        v2 = int(i.split('-')[1])
                        for j in range(v1,v2+1):
                            para_linenumber.append(j)
                    else:
                        para_linenumber.append(int(i))
            except:
                return -1

            if 0 in para_linenumber:
                para_linenumber.remove(0)

            if 1 in para_linenumber:
                para_linenumber.remove(1)

            para_linenumber.sort()

            return para_linenumber
        else:
            return None

    def Open(self,event):
        self.dirname = ''
        dlg = wx.FileDialog(self,'选择文件',self.dirname,'','*.csv*',wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            self.FilePath = os.path.join(self.dirname,self.filename)
            self.LogMessage('File=[{}]\n'.format(self.FilePath),colour='#5151A2')

    def run(self):
        if self.FilePath:
            #self.LogMessage('Wait a few seconds to connect to Server\n',colour='#EAC100')
            global host,query,session
            self.para_line_num=self.GetParameter()
            if self.para_line_num == -1:
                self.LogMessage('Line Error',colour='RED')
                self.ResetRunningStatus()
            else:
                self.LogMessage('Wait a few seconds to connect to HPQC Server...',colour='BLACK')
                host = r'https://www.wxpythontest.com'
                query = HPQCQuery('test2', 'test1')
                session = Session(host, self.default_username,self.default_passwd)
                self.LogMessage('Connect successfully\n',colour='BLACK')
                upload(self.FilePath,self.para_line_num,self.LogMessage)
                self.ResetRunningStatus()
        else:
            self.LogMessage(r'请先选择文件!',colour='RED')
            self.ResetRunningStatus()

if __name__ == '__main__':
    app = MyApp()
    frame = MyFrame(title='Upload Data to HPQC',size=(750,500))
    frame.Show()
    app.MainLoop()

效果图:

 

 

 

posted on 2020-09-03 09:40  骑着蜗牛追太阳  阅读(250)  评论(0编辑  收藏  举报

导航