コード例 #1
0
ファイル: Window.py プロジェクト: IrwantoCia/Python-Scraper
    def __init__(self):
        self.version = 'V 1.0.0'
        self.root = tk.Tk()
        self.root.title('Olshop Scrapper ' + self.version)

        self.frame1 = tk.Frame(self.root)
        self.frame1.grid(row=0, column=0, sticky='snew')
        
        #Label Frame
        self.west = LabelFrame(self.frame1, text=' Source ')
        self.west.grid(column=0, row=0, sticky='wn', padx=5, pady=5)
        self.east = LabelFrame(self.frame1, text=' Excel ')
        self.east.grid(column=1, row=0, sticky='wn', padx=5, pady=5)

        #Making Source form
        self.src = []
        for i in range(6):
            self.src.append(Io.source(self.west, i, 0))
            
        #Output form
        self.outputName = Io.output(self.east, 1, 0)
        self.outputName.button.configure(state='disabled')
        self.excel = Io.excelInput(self.east, 3, 0)
        self.excel.sheet.bind('<<ComboboxSelected>>',self.check)
        self.work = calc(self.frame1, 1, 0, self.compare, self.load)
        self.work.proccess.configure(state='disabled')
        
        self.root.mainloop()
コード例 #2
0
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W + E)
コード例 #3
0
ファイル: controller.py プロジェクト: sdsc/sandbox-tweeteor
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W+E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W+E)
コード例 #4
0
ファイル: payment.py プロジェクト: tylerjw/jim_tracker
    def __init__(self, master, customers, payments, output_text, refresh):
        Frame.__init__(self, master)

        self.refresh = refresh
        self.master = master
        self.output_text = output_text
        self.customers = customers
        self.payments = payments

        self.pname = StringVar()
        self.pnames = []
        self.mname = StringVar()
        self.mnames = []
        self.date = StringVar()
        self.nmonths = StringVar()
        self.punches = StringVar()

        self.nmonths.set('1')
        self.punches.set(str(10))
        self.date.set(strftime("%m/%d/%Y"))

        self.columnconfigure(0,weight=1)

        # Monthly Customers
        monthly_lf = LabelFrame(self, text="Monthly Customers Payment")
        monthly_lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')
        
        Label(monthly_lf,text="Name:").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(monthly_lf,text="Date:").grid(row=0,column=3,sticky='e',padx=(10,0),pady=(10,2))
        Label(monthly_lf,text="# Months:").grid(row=1,column=0,columnspan=2,sticky='e',padx=(10,0),pady=(2,10))
        self.mname_cb = Combobox(monthly_lf,textvariable=self.mname,width=20,values=self.mnames,
            state='readonly')
        self.mname_cb.grid(row=0,column=1,columnspan=2,sticky='ew',pady=(10,2))
        Entry(monthly_lf,textvariable=self.date,width=15).grid(row=0,column=4,sticky='ew',padx=(0,10),pady=(10,2))
        Entry(monthly_lf,textvariable=self.nmonths).grid(row=1,column=2,sticky='ew',pady=(2,10))
        Button(monthly_lf,text='Submit',command=self.monthly_payment).grid(row=1,column=4,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(5):
            monthly_lf.columnconfigure(i,weight=1)

        # Punch Card Customers
        puch_lf = LabelFrame(self, text="Punch Card Customers (Purchace Card)")
        puch_lf.grid(padx=5,pady=5,row=1,column=0,sticky='ew')

        Label(puch_lf,text="Name:").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(puch_lf,text="Punches:").grid(row=0,column=2,sticky='e',pady=(10,2))
        self.pname_cb = Combobox(puch_lf,textvariable=self.pname,width=20,values=self.pnames,state='readonly')
        self.pname_cb.grid(row=0,column=1,sticky='ew',pady=(10,2))
        Entry(puch_lf,textvariable=self.punches,width=15).grid(row=0,column=3,sticky='ew',padx=(0,10),pady=(10,2))
        Button(puch_lf,text='Submit',command=self.new_punchcard).grid(row=3,column=3,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(4):
            puch_lf.columnconfigure(i,weight=1)

        self.update_names()
コード例 #5
0
    def initUI(self):

        self.MPDInitialize()
        self.parent.title("RaspiPlayer")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        #self.columnconfigure(1, weight=1)
        #self.columnconfigure(3, pad=7)
        #self.rowconfigure(3, weight=1)
        #self.rowconfigure(5, pad=7)

        #self.CurrentSongInfo()
        self.poll()

        titleframe = LabelFrame(self, width=200, height=70)
        titleframe.grid(row=0, column=0, columnspan=2)
        titleframe.grid_propagate(0)
        titlelbl = Label(titleframe,
                         text="RaspPi Player",
                         font=('Garamond', (20), 'bold'))
        titlelbl.grid(row=0, column=0)

        PreviousButton = Button(self,
                                text="Previous",
                                command=self.PreviousClick)
        PreviousButton.grid(row=2, column=0)

        PlayButton = Button(self, text="Play", command=self.PlayClick)
        PlayButton.grid(row=2, column=1, padx=4)

        StopButton = Button(self, text="Stop", command=self.StopClick)
        StopButton.grid(row=2, column=2)

        PauseButton = Button(self, text="Pause", command=self.PauseClick)
        PauseButton.grid(row=2, column=3, padx=4)

        NextButton = Button(self, text="Next", command=self.NextClick)
        NextButton.grid(row=2, column=4)

        UploadButton = Button(self, text="Upload", command=self.UploadClick)
        UploadButton.grid(row=2, column=5, padx=4)

        VolumeBar = Scale(self,
                          from_=0,
                          to=100,
                          orient="horizontal",
                          label="Volume",
                          command=self.VolumeBar)
        VolumeBar.grid(row=2, column=6, padx=5)
        VolumeBar.set(50)
コード例 #6
0
ファイル: TRAMapp.py プロジェクト: alessioferrari/tram
    def initUI(self):
      
        self.parent.title("TRAM")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        #Model Text
        self.t = Text(self, borderwidth=3, relief="sunken")
        self.t.config(font=("consolas", 12), undo=True, wrap='word')
        self.t.grid(row=0, column=0, padx=2, pady=2, sticky=(N, W, E, S))
        
        
        
        #Search Panel
        searchPanel = LabelFrame(self, text="Find your model")
        searchPanel.grid(row=0, column=1, padx=2, pady=2, sticky=N) 
        
        Label(searchPanel, text="Model name").grid(row=0, column=0, padx=2, pady=2, sticky=W)
        
        searchQueryEntry = Entry(searchPanel, textvariable=self.searchQuery)
        searchQueryEntry.grid(row=0, column=1, padx=2, pady=2, sticky=W)
        
        Label(searchPanel, text="Transformation").grid(row=1, column=0, padx=2, pady=2, sticky=W)
        preferredTransformation = StringVar()
        box = Combobox(searchPanel, textvariable=preferredTransformation, state='readonly')
        box['values'] = ('Any...', 'Object Change', 'Object Extension', 'Specialization', 'Functionality Extension', 'System Extension', 'Soft Simplification', 'Hard Simplification')
        box.current(0)
        box.grid(row=1, column=1, padx=2, pady=2, sticky=W)
        
        findButton = Button(searchPanel, text="Find", command = self.__findModels)
        findButton.grid(row=2, column=1, padx=2, pady=2, sticky=E)
        
        #Listbox with recommendations
        recommendationPanel = LabelFrame(self, text="Recommended models (transformations)")
        recommendationPanel.grid(row=0, column=1, padx=2, pady=2, sticky=(W,E,S))
        self.l = Listbox(recommendationPanel)
        self.l.pack(fill=BOTH, expand=1)
        
        #Button frame
        transformButtonPanel = Frame(recommendationPanel)
        transformButtonPanel.pack(fill=BOTH, expand=1)
        
        viewButton = Button(transformButtonPanel, text="View", command = self.__loadSelectedModel)
        viewButton.grid(row=1, column=0, padx=2, pady=2)
        
        transformButton = Button(transformButtonPanel, text="Transform", command = self.__transformModel)
        transformButton.grid(row=1, column=2, padx=2, pady=2)
コード例 #7
0
ファイル: reports.py プロジェクト: tylerjw/jim_tracker
    def __init__(self,master,customers,payments,output_text):
        Frame.__init__(self,master)
        self.customers = customers
        self.payments = payments
        self.master = master
        self.output_text = output_text

        self.year_months = find_years_months(getcwd()) # use cwd, this should be set

        self.year = StringVar()
        self.month = StringVar()
        self.years = sorted(self.year_months.keys())
        self.months = []

        lf = LabelFrame(self, text="Generate Report")
        lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')

        Label(lf,text="Year: ").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(lf,text="Month: ").grid(row=1,column=0,sticky='e',padx=(10,0),pady=2)

        self.year_cb = Combobox(lf,textvariable=self.year,width=12,values=self.years,state='readonly')
        self.month_cb = Combobox(lf,textvariable=self.month,width=12,values=self.months,state='readonly')
        
        self.year_cb.grid(row=0,column=1,sticky='w',padx=(0,10),pady=(10,2))
        self.month_cb.grid(row=1,column=1,sticky='w',padx=(0,10),pady=2)

        btn = Button(lf,text="Save Report",command=self.report,width=30)
        btn.grid(row=2,column=0,columnspan=2,sticky='n',pady=(2,10),padx=10)

        #configure the grid to expand
        self.columnconfigure(0,weight=1)
        lf.rowconfigure(0,weight=1)
        lf.rowconfigure(1,weight=1)
        lf.columnconfigure(0,weight=1)
        lf.columnconfigure(1,weight=1)

        self.year_cb.bind('<<ComboboxSelected>>',self.year_selected)

        self.update() #update the values
コード例 #8
0
ファイル: Window.py プロジェクト: IrwantoCia/Python-Scraper
class window(object):
    def __init__(self):
        self.version = 'V 1.0.0'
        self.root = tk.Tk()
        self.root.title('Olshop Scrapper ' + self.version)

        self.frame1 = tk.Frame(self.root)
        self.frame1.grid(row=0, column=0, sticky='snew')
        
        #Label Frame
        self.west = LabelFrame(self.frame1, text=' Source ')
        self.west.grid(column=0, row=0, sticky='wn', padx=5, pady=5)
        self.east = LabelFrame(self.frame1, text=' Excel ')
        self.east.grid(column=1, row=0, sticky='wn', padx=5, pady=5)

        #Making Source form
        self.src = []
        for i in range(6):
            self.src.append(Io.source(self.west, i, 0))
            
        #Output form
        self.outputName = Io.output(self.east, 1, 0)
        self.outputName.button.configure(state='disabled')
        self.excel = Io.excelInput(self.east, 3, 0)
        self.excel.sheet.bind('<<ComboboxSelected>>',self.check)
        self.work = calc(self.frame1, 1, 0, self.compare, self.load)
        self.work.proccess.configure(state='disabled')
        
        self.root.mainloop()
        
    def check(self, event): 
        self.work.update_status('Getting cell information...')
        self.workingSheet = self.wb.get_sheet_by_name(self.excel.sheet.get())
        self.excel.sku['values'] = [self.workingSheet.cell(row=1, column=i).value \
                                    for i in range(1, self.workingSheet.max_column, 1)\
                                    if self.workingSheet.cell(row=1, column=i).value != None]
        self.excel.sku.current(0) 
        self.excel.stock['values'] = [self.workingSheet.cell(row=1, column=i).value \
                                    for i in range(1, self.workingSheet.max_column, 1)\
                                    if self.workingSheet.cell(row=1, column=i).value != None]
        self.excel.stock.current(0)
        self.work.proccess.configure(state='active')
        self.work.status.set('Done.')  
        
    def load(self):
        self.work.update_status('Scrapping HTML...')
        self.scSoup = []
        #Get HTML into soup
        for url in self.src:
            if url.getFile() == '':
                continue
            scFile = open(url.getFile())
            self.scSoup.append(bs4.BeautifulSoup(scFile.read(), "html.parser"))
        
        #Opening Excel from excel input
        self.work.update_status('Getting excel sheet...')
        self.wb = openpyxl.load_workbook(self.excel.getFile(), data_only=True)
        self.excel.sheet['values'] = self.wb.get_sheet_names()
        self.excel.sheet.current(0)
        self.check(self)
        
    def compare(self):  
        self.columnSku = 0
        self.startColumnSku = self.workingSheet.max_column #start writing from last column + 1
        self.columnStock = 0
        self.startColumnStock = self.workingSheet.max_column+1 #start writing from last column + 1
        self.work.update_status('Getting column...')
        
        for name in self.excel.sku['values']:#getting sku ceolumn number
            self.columnSku += 1
            if name == self.excel.sku.get():
                break
        for name in self.excel.stock['values']:#getting stok ceolumn number
            self.columnStock += 1
            if name == self.excel.stock.get():
                break
            
        self.work.update_status('Please wait, proccessing...')
        self.workingSheet.cell(row=1, column=self.startColumnSku).value = 'SKU'
        self.workingSheet.cell(row=1, column=self.startColumnStock).value = 'Stock'
        
        for i in range(2, self.workingSheet.max_row+1, 1):#Getting each of cell in sku column
            y = 1
            for soup in self.scSoup:#check it with every soup available
                sku = soup.select('tr > td')
                stock = soup.select(' .stockOnSales')
                for index in range(3, len(sku), 11):
                    if self.workingSheet.cell(row=i, column=self.columnSku).value == sku[index].getText():
                        self.workingSheet.cell(row=i, column=self.startColumnSku).value = 'TRUE'
                        if (self.workingSheet.cell(row=i, column=self.columnStock).value) != (int(stock[y].getText())):
                            self.workingSheet.cell(row=i, column=self.startColumnStock).value = int(stock[y].getText())
                        else: self.workingSheet.cell(row=i, column=self.startColumnStock).value = '-'
                        break
                    y += 1
                break    
                        
        self.wb.save(self.excel.getFile())
        self.outputName.path.set(self.excel.getFile())
        self.outputName.button.configure(state='active')
        self.work.status.set('Complete.')
    
    '''                 
コード例 #9
0
ファイル: customer.py プロジェクト: tylerjw/jim_tracker
    def __init__(self, master, customers, output_text, refresh):
        Frame.__init__(self, master)
        self.output_text = output_text
        self.refresh = refresh
        self.root = master
        self.customers = customers

        self.name = StringVar() #edit customer
        self.names = []
        self.ncd = NewCustomerDialog(self.root, self.customers, self.refresh, edit=True)

        self.fname = StringVar()
        self.lname = StringVar()
        self.mname = StringVar()
        self.payment = StringVar()
        self.date = StringVar()
        self.iconname="New Customer"

        lf = LabelFrame(self, text="New Customer")
        lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')
        
        ### dialog content        
        Label(lf, text="Name: ").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(lf, text="Type: ").grid(row=1,sticky='e',pady=2,padx=(10,0))
        Label(lf, text="Date: ").grid(row=1,column=2,sticky='e',ipady=2,padx=(10,0))

        self.fname_en = Entry(lf, width=20, textvariable=self.fname)
        self.mname_en = Entry(lf, width=4, textvariable=self.mname)
        self.lname_en = Entry(lf, width=20, textvariable=self.lname)
        self.payment_cb = Combobox(lf, textvariable=self.payment, width=12,
                                   values=("Drop In", "Punch Card", "Monthly", "Inactive"))
        self.date_en = Entry(lf, width=15, textvariable=self.date)
        
        self.fname_en.grid(row=0,column=1,sticky='ew',pady=(10,2))
        self.mname_en.grid(row=0,column=2,sticky='ew',pady=(10,2))
        self.lname_en.grid(row=0,column=3,sticky='ew',padx=(0,10),pady=(10,2))
        self.payment_cb.grid(row=1,column=1,sticky='ew')
        self.date_en.grid(row=1,column=3,columnspan=2,sticky='ew',padx=(0,10))
        
        ### buttons
        Button(lf, text='Reset Values', width=15,
               command=self.reset_values).grid(row=3,column=0,columnspan=2,sticky='ew',padx=10,pady=(2,10))
        Button(lf, text='Submit', width=15,
               command=self.add_customer).grid(row=3,column=3,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(4):
            lf.columnconfigure(i, weight=1)

        # edit customer
        lf = LabelFrame(self, text="Edit Customer")
        lf.grid(padx=5,pady=5,row=1,column=0,sticky='ew')

        Label(lf, text="Name: ").grid(row=0,column=0,sticky='e',pady=10,padx=(10,0))
        self.name_cb = Combobox(lf, textvariable=self.name, width=30, values=self.names)
        self.name_cb.grid(row=0,column=1,sticky='ew',pady=10)
        Button(lf, text="Edit",width=15,command=self.edit).grid(row=0,column=2,sticky='ew',padx=10,pady=10)

        for i in range(3):
            lf.columnconfigure(i,weight=1)
        self.columnconfigure(0,weight=1)

        self.fname_en.focus_set() #cursor goes here when frame is created
        self.update_names()
        self.reset_values() #zero out all values in new customer
コード例 #10
0
def createSettings(self,frame,d):


    #name frame
    row = 0
    col = 0

    
    lblFrame = Frame(frame)
    lblFrame.grid(row=row,column=col,columnspan=5,sticky=W+E,pady=0,padx=5)

    frame.columnconfigure(col, weight=1)
    frame.rowconfigure(row, weight=0)

    row = 0
    col = 0

    Label(lblFrame, text="Script Name").grid(row=row,column=col,sticky=W) 
    lblFrame.columnconfigure(col, weight=0)
    lblFrame.rowconfigure(row, weight=0)
    

    row = 0
    col = 1
    
    entryMain = Entry(lblFrame)
    entryMain.grid(row=row,column=col,sticky=W+E,columnspan=5)
    self.entryName = entryMain
    lblFrame.columnconfigure(col, weight=1)
    lblFrame.rowconfigure(row, weight=0)


    #python plugin script file
    row = 1
    col = 0
    mainGroup = LabelFrame(frame,text="Python Script File", padding="5 5 5 5")
    mainGroup.grid(row=row,column=col,columnspan=5,sticky=W+E+N,pady=5,padx=5)
          


    row = 0
    col = 0
    mainGroup.columnconfigure(col, weight=1)
    mainGroup.rowconfigure(row, weight=0)  
    
    entryMain = Entry(mainGroup)
    entryMain.grid(row=row,column=col,columnspan=4,sticky=W+E)
    entryMain.bind("<Return>",self.entryFileEvent)
    self.entryFile = entryMain


    row = 0
    col = 4
    btnMainBrowse = Button(mainGroup,text="Browse")
    btnMainBrowse.grid(row=row,column=col,columnspan=1,sticky=W+E,padx=5,pady=2.5)
    self.btnBrowse = btnMainBrowse

    
    row = 1
    col = 0   
    Label(mainGroup, text="Plugin Class").grid(row=row,column=col,sticky=E)
    self.cbPluginClass = comboBox([],mainGroup,col+1,row)
    mainGroup.columnconfigure(col, weight=0)
    row = 2
    col = 0   
    Label(mainGroup, text="GUI Class").grid(row=row,column=col,sticky=E)
    self.cbGuiClass = comboBox([],mainGroup,col+1,row)

    col = 1
    mainGroup.columnconfigure(1, weight=1)
    mainGroup.columnconfigure(2, weight=1)
    mainGroup.columnconfigure(3, weight=1)  
   

    row=1
    col=4
    
    button = Button(mainGroup,text="Edit Script File")
    button.grid(row=row,column=col,sticky=W+E,padx=5,pady=2.5)
    self.btnEditScript = button

    row = 2
    col = 4
    button = Button(mainGroup,text="Open Contaning Folder")
    button.grid(row=row,column=col,sticky=W+E,padx=5,pady=2.5)
    self.btnOpenFolder = button
コード例 #11
0
    def initUI(self):
        self.width = 700
        self.height = 350
        self.left = 0
        self.right = 0
        
        
        self.parent = Tk()
        self.parent.attributes("-topmost", 1)
        
        self.getHWNDS()
        r = self.winPos(self.obshwnd)
        self.centerOverOBS(r)

        self.parent.geometry("%sx%s+%s+%s" % (self.width,self.height,int(self.left),int(self.top)))
        
        self.parent.focus()
        self.parent.wm_title("Python Script Manager")
       

        #title label frame
        row = 0
        col = 0
        self.parent.columnconfigure(col,weight=1) 
        self.parent.rowconfigure(row,weight=0)
        
        titleFrame = Frame(self.parent)   
        titleFrame.grid(row=row,column=col,sticky=W+E,pady=5,padx=10)      

        row = 0
        col = 0
        labelfont = ('bold', 15)
        Label(titleFrame, text="Python Script Manager",font=labelfont).grid(row=row,column=col,sticky=W)

        titleFrame.columnconfigure(row,weight=1)
        titleFrame.rowconfigure(col,weight=0)
        
       
        #sidebyside frame
        row = 1
        col = 0
        self.parent.rowconfigure(row,weight=1)
        self.parent.columnconfigure(col,weight=1)
        
        sidebyside = Frame(self.parent)
        sidebyside.grid(row=row,column=col,sticky=W+E+N+S,pady=0,padx=5)

        
        
        #listbox frame
        row = 0
        col = 0
        sidebyside.rowconfigure(row,weight=1)
        sidebyside.columnconfigure(col,weight=1)        
        
        leftFrame = Frame(sidebyside)
        leftFrame.grid(row=row,column=col,sticky=W+E+N+S,pady=5,padx=5)

        #listbox
        row = 0
        col = 0
        self.listbox = Listbox(leftFrame)
        self.listbox.grid(row=row,column=col,columnspan=5,sticky=W+E+N+S)
        listboxReload(self.listbox,getScriptNames(self.scriptDict))
        self.listbox.bind('<<ListboxSelect>>',self.listboxSelectionEevent)

        leftFrame.columnconfigure(col,weight=1)
        leftFrame.rowconfigure(row,weight=1)

        

        row=1
        col=0
        buttonFrame = Frame(leftFrame)   
        buttonFrame.grid(row=row,column=col,sticky=W,pady=0,padx=0)

        row=0
        col=0
        #btnAdd
        button = Button(buttonFrame,text="Add")
        button.grid(row=row,column=col,sticky=E)        
        self.btnAdd = button
        self.btnAdd.config(command=self.btnAddEvent)

        #btnRemove
        button = Button(buttonFrame,text="Remove")
        button.grid(row=row,column=col+1,sticky=W)
        self.btnRemove = button
        self.btnRemove.config(command=self.btnRemoveEvent)
        
       
        #settings frame

        row = 0
        col = 1
        sidebyside.rowconfigure(row,weight=1)
        sidebyside.columnconfigure(col,weight=10)


        rightFrame = Frame(sidebyside)
        rightFrame.grid(row=row,column=col,sticky=W+E+N+S,pady=5,padx=5)

        

        row = 0
        col = 0
        rightFrame.columnconfigure(col,weight=1)
        rightFrame.rowconfigure(row,weight=1)
                
        self.frmSettings = LabelFrame(rightFrame,text="Settings", padding="5 5 5 5")
        self.frmSettings.grid(row=row,column=col,sticky=W+E+N+S,pady=0,padx=0) 
        
 
        self.frmSettings.columnconfigure(col,weight=1)
        self.frmSettings.rowconfigure(row,weight=1)


        d = createScriptDict()
        createSettings(self,self.frmSettings,d)


        row=1
        col=0
        
        buttonFrame = Frame(rightFrame)   
        buttonFrame.grid(row=row,column=col,sticky=W,pady=0,padx=0)        
        
    
        row = 0
        col = 0
        button = Button(buttonFrame,text="Save")
        button.grid(row=row,column=col)
        self.btnSave = button
        self.btnSave.config(command=self.btnSaveEvent)
    


    








        #ok cancel buttons
        row = 2
        col = 0
        self.parent.columnconfigure(col,weight=1)
        self.parent.rowconfigure(row,weight=0)
        
        bottomframe = Frame(self.parent)   
        bottomframe.grid(row=row,column=col,sticky=W+E,pady=5,padx=10)

        row = 0
        col = 0
        
        bottomframe.columnconfigure(col,weight=1)
        bottomframe.rowconfigure(row,weight=0)
        
        logFrame = Frame(bottomframe)   
        logFrame.grid(row=row,column=col,sticky=W,pady=0,padx=0)
        logFrame.rowconfigure(row,weight=0)

        row=0
        col=0
        #btnOpenLogs
        button = Button(logFrame,text="Open Logs",command=self.btnOpenLogsEvent)
        button.grid(row=row,column=col,sticky=E,padx=0,pady=0)        
        self.btnOpenLogs = button
 

        row = 0
        col = 1
        

        bottomframe.columnconfigure(col,weight=1)
        bottomframe.rowconfigure(row,weight=0)

        ccFrame = Frame(bottomframe)   
        ccFrame.grid(row=row,column=col,sticky=E,pady=0,padx=5)
        ccFrame.rowconfigure(row,weight=0)

        row=0
        col=0
        
        button = Button(ccFrame,text="Create",command=self.btnCreateEvent)
        button.grid(row=row,column=col,sticky=E,padx=10,pady=0)
        self.btnCreate = button

        button = Button(ccFrame,text="Cancel",command=self.btnCancelEvent)
        button.grid(row=row,column=col+1,sticky=W,padx=0,pady=0) 
        self.btnCancel = button
       

        
        self.clearSettings()
        self.parent.after(1,self.lockWindow)
        self.parent.mainloop()

        self.unlockWindow()
コード例 #12
0
class ScriptManager:
    def __init__(self,sourceData):
        self.sourceData = sourceData


        self.jsonPath = OBS.GetAppDataPath()+"/pluginData/Python/scripts.json"        
        self.scriptDict = loadJSON(self.jsonPath)
        self.currentDict = []
        self.selectedScript = None
        
        print(getScriptNames(self.scriptDict))

        self.initUI()

    def initUI(self):
        self.width = 700
        self.height = 350
        self.left = 0
        self.right = 0
        
        
        self.parent = Tk()
        self.parent.attributes("-topmost", 1)
        
        self.getHWNDS()
        r = self.winPos(self.obshwnd)
        self.centerOverOBS(r)

        self.parent.geometry("%sx%s+%s+%s" % (self.width,self.height,int(self.left),int(self.top)))
        
        self.parent.focus()
        self.parent.wm_title("Python Script Manager")
       

        #title label frame
        row = 0
        col = 0
        self.parent.columnconfigure(col,weight=1) 
        self.parent.rowconfigure(row,weight=0)
        
        titleFrame = Frame(self.parent)   
        titleFrame.grid(row=row,column=col,sticky=W+E,pady=5,padx=10)      

        row = 0
        col = 0
        labelfont = ('bold', 15)
        Label(titleFrame, text="Python Script Manager",font=labelfont).grid(row=row,column=col,sticky=W)

        titleFrame.columnconfigure(row,weight=1)
        titleFrame.rowconfigure(col,weight=0)
        
       
        #sidebyside frame
        row = 1
        col = 0
        self.parent.rowconfigure(row,weight=1)
        self.parent.columnconfigure(col,weight=1)
        
        sidebyside = Frame(self.parent)
        sidebyside.grid(row=row,column=col,sticky=W+E+N+S,pady=0,padx=5)

        
        
        #listbox frame
        row = 0
        col = 0
        sidebyside.rowconfigure(row,weight=1)
        sidebyside.columnconfigure(col,weight=1)        
        
        leftFrame = Frame(sidebyside)
        leftFrame.grid(row=row,column=col,sticky=W+E+N+S,pady=5,padx=5)

        #listbox
        row = 0
        col = 0
        self.listbox = Listbox(leftFrame)
        self.listbox.grid(row=row,column=col,columnspan=5,sticky=W+E+N+S)
        listboxReload(self.listbox,getScriptNames(self.scriptDict))
        self.listbox.bind('<<ListboxSelect>>',self.listboxSelectionEevent)

        leftFrame.columnconfigure(col,weight=1)
        leftFrame.rowconfigure(row,weight=1)

        

        row=1
        col=0
        buttonFrame = Frame(leftFrame)   
        buttonFrame.grid(row=row,column=col,sticky=W,pady=0,padx=0)

        row=0
        col=0
        #btnAdd
        button = Button(buttonFrame,text="Add")
        button.grid(row=row,column=col,sticky=E)        
        self.btnAdd = button
        self.btnAdd.config(command=self.btnAddEvent)

        #btnRemove
        button = Button(buttonFrame,text="Remove")
        button.grid(row=row,column=col+1,sticky=W)
        self.btnRemove = button
        self.btnRemove.config(command=self.btnRemoveEvent)
        
       
        #settings frame

        row = 0
        col = 1
        sidebyside.rowconfigure(row,weight=1)
        sidebyside.columnconfigure(col,weight=10)


        rightFrame = Frame(sidebyside)
        rightFrame.grid(row=row,column=col,sticky=W+E+N+S,pady=5,padx=5)

        

        row = 0
        col = 0
        rightFrame.columnconfigure(col,weight=1)
        rightFrame.rowconfigure(row,weight=1)
                
        self.frmSettings = LabelFrame(rightFrame,text="Settings", padding="5 5 5 5")
        self.frmSettings.grid(row=row,column=col,sticky=W+E+N+S,pady=0,padx=0) 
        
 
        self.frmSettings.columnconfigure(col,weight=1)
        self.frmSettings.rowconfigure(row,weight=1)


        d = createScriptDict()
        createSettings(self,self.frmSettings,d)


        row=1
        col=0
        
        buttonFrame = Frame(rightFrame)   
        buttonFrame.grid(row=row,column=col,sticky=W,pady=0,padx=0)        
        
    
        row = 0
        col = 0
        button = Button(buttonFrame,text="Save")
        button.grid(row=row,column=col)
        self.btnSave = button
        self.btnSave.config(command=self.btnSaveEvent)
    


    








        #ok cancel buttons
        row = 2
        col = 0
        self.parent.columnconfigure(col,weight=1)
        self.parent.rowconfigure(row,weight=0)
        
        bottomframe = Frame(self.parent)   
        bottomframe.grid(row=row,column=col,sticky=W+E,pady=5,padx=10)

        row = 0
        col = 0
        
        bottomframe.columnconfigure(col,weight=1)
        bottomframe.rowconfigure(row,weight=0)
        
        logFrame = Frame(bottomframe)   
        logFrame.grid(row=row,column=col,sticky=W,pady=0,padx=0)
        logFrame.rowconfigure(row,weight=0)

        row=0
        col=0
        #btnOpenLogs
        button = Button(logFrame,text="Open Logs",command=self.btnOpenLogsEvent)
        button.grid(row=row,column=col,sticky=E,padx=0,pady=0)        
        self.btnOpenLogs = button
 

        row = 0
        col = 1
        

        bottomframe.columnconfigure(col,weight=1)
        bottomframe.rowconfigure(row,weight=0)

        ccFrame = Frame(bottomframe)   
        ccFrame.grid(row=row,column=col,sticky=E,pady=0,padx=5)
        ccFrame.rowconfigure(row,weight=0)

        row=0
        col=0
        
        button = Button(ccFrame,text="Create",command=self.btnCreateEvent)
        button.grid(row=row,column=col,sticky=E,padx=10,pady=0)
        self.btnCreate = button

        button = Button(ccFrame,text="Cancel",command=self.btnCancelEvent)
        button.grid(row=row,column=col+1,sticky=W,padx=0,pady=0) 
        self.btnCancel = button
       

        
        self.clearSettings()
        self.parent.after(1,self.lockWindow)
        self.parent.mainloop()

        self.unlockWindow()



    def btnAddEvent(self):
        self.clearSettings()
        
    def btnSaveEvent(self):
        name = self.entryName.get()        
        print (name)
        self.saveSettings(name)


    def getHWNDS(self):
        self.obshwnd = OBS.GetMainWindow()
        self.hwndTkinter =  self.parent.winfo_id()

    def centerWindow(self):
        self.winPos(self.parent.winfo_id())
    

    def winPos(self,hwnd):
        f = ctypes.windll.user32.GetWindowRect
        rect = ctypes.wintypes.RECT()
        DWMWA_EXTENDED_FRAME_BOUNDS = 9
        f(ctypes.wintypes.HWND(hwnd),
          ctypes.byref(rect)
          )
        return rect
    
    def centerOverOBS(self,r):
        obsWidth = r.right-r.left
        obsHeight = r.bottom-r.top
        self.left = r.left + (obsWidth/2) - (self.width/2)
        self.top = r.top + (obsHeight/2) - (self.height/2)
        

    def lockWindow(self):
        #ctypes.windll.user32.SetWindowLongA(self.hwndTkinter,-8,self.obshwnd)
        #ctypes.windll.user32.SetParent(self.hwndTkinter, self.obshwnd)
            
        ctypes.windll.user32.SetActiveWindow(self.hwndTkinter)
        ctypes.windll.user32.EnableWindow(self.obshwnd,False)
        

    def unlockWindow(self):        
        ctypes.windll.user32.EnableWindow(self.obshwnd,True)
        ctypes.windll.user32.SetActiveWindow(self.obshwnd)


    def listboxSelectionEevent(self,evt):
        self.clearSettings()
        print("Select")
        w = evt.widget
        index = int(w.curselection()[0])
        value = w.get(index)
        d = self.scriptDict[value]
        self.loadSettings(d,value)
        

    def loadSettings(self,d,name):
        self.clearSettings()
        self.entryName.insert(0,name)
        self.entryFile.insert(0,d['file'])
        file = d['file']
        print ("osetuh"+ file)
        if file is not None:
            classes = getClasses(d['file'])
            print (classes)
            if  not classes:
                self.cbPluginClass['values']= ['']
                self.cbGuiClass['values']= ['']
                self.cbPluginClass.current(0)
                self.cbGuiClass.current(0)
            else:
                print (classes.index(d['mainClass']))
                self.cbPluginClass['values']= classes
                self.cbPluginClass.current(classes.index(d['mainClass']))
                self.cbGuiClass['values']= classes
                self.cbGuiClass.current(classes.index(d['guiClass']))
        else:
            file= OBS.GetAppDataPath()+"/pluginData/Python"
           
        print ("LoadSettings" + file)
        self.btnBrowse.config(command=lambda arg=os.path.dirname(file):self.btnBrowseEvent(arg))
        self.btnOpenFolder.config(command=lambda arg=os.path.dirname(file): openContaningFolder(arg))
        self.btnEditScript.config(command=lambda arg=file: openFileWithDefaultOSApp(arg))
        
    def clearSettings(self):
        self.entryName.delete(0,END) 
        self.entryFile.delete(0,END)
        self.btnBrowse.config(command=None)
        self.cbPluginClass['values'] = ['']
        self.cbGuiClass['values'] = ['']
        self.cbPluginClass.current(0)
        self.cbGuiClass.current(0)
        self.btnEditScript.config(command=None)
        self.btnOpenFolder.config(command=None)
        self.btnBrowse.config(command=lambda file= OBS.GetAppDataPath()+"/pluginData/Python" :self.btnBrowseEvent(file))

    def saveSettings(self,name):

        #check if dict exists
        d = self.scriptDict.get(name)
        if d is None:
            d= createScriptDict()

        d['guiClass']= self.cbGuiClass.get()
        d['file'] = self.entryFile.get()
        d['mainClass']= self.cbPluginClass.get()
        if validateSettings(d['file'],name,d['guiClass'],d['mainClass']) == False:
            self.listbox.focus_set()
            return True
        #add to dict
        self.scriptDict[name] = d
        print (d)
        #reload listbox
        listboxReload(self.listbox,getScriptNames(self.scriptDict))
        #save to json
        saveJSON(self.scriptDict,self.jsonPath)

    def updateClasses(self,file):
        classes = getClasses(file)        
        if  not classes:
            self.cbPluginClass['values']= ['']
            self.cbGuiClass['values']= ['']
            self.cbPluginClass.current(0)
            self.cbGuiClass.current(0)
        else:
            self.cbPluginClass['values']= classes
            self.cbPluginClass.current(0)
            self.cbGuiClass['values']= classes
            self.cbGuiClass.current(0)

    def btnRemoveEvent(self):
        #remove the selected item from list box.
        w = self.listbox
        try:
            index = int(w.curselection()[0])
            value = w.get(index)
            del self.scriptDict[value]
            self.clearSettings()
            listboxReload(self.listbox,getScriptNames(self.scriptDict))
        except:
            pass
        
    def entryFileEvent(self,event):
        path = self.entryFile.get()
        self.updateComboBoxes(path)

    def btnBrowseEvent(self,file):
        print ("btnbrowsefile " + file)
        if file is None:
            #path = askopenfilename(parent=self.parent,initialdir=("C:\\"))
            path = askopenfilename(parent=self.parent,initialdir=(OBS.GetAppDataPath()+"/pluginData/Python"))
        else:
            path = askopenfilename(parent=self.parent,initialdir=(file))
        if path == '':
            #user cancled do nothing.
            return
        self.updateComboBoxes(path)
            
    def updateComboBoxes(self,path):
        #need to update comboboxes, edit and open contatining folder.
        self.updateClasses(path)
        self.entryFile.delete(0,END)
        self.entryFile.insert(0,path)

        self.btnOpenFolder.config(command=lambda arg=os.path.dirname(path): openContaningFolder(arg))
        self.btnEditScript.config(command=lambda arg=path: openFileWithDefaultOSApp(arg))

    def btnCancelEvent(self):
        self.parent.destroy()

    
    def btnCreateEvent(self):
        file = self.entryFile.get()
        pluginClass = self.cbPluginClass.get()
        guiClass = self.cbGuiClass.get()
        name = " "
        if validateSettings(file,name,guiClass,pluginClass) == True:
            self.sourceData.SetString(u"PythonFile",u(file))
            self.sourceData.SetString(u"PythonPluginClass",u(pluginClass))
            self.sourceData.SetString(u"PythonGUIClass",u(guiClass))
            self.sourceData.SetInt(u"Debug",0)
            self.btnCancelEvent()
    
    def btnOpenLogsEvent(self):
        stdErr = OBS.GetAppDataPath()+"/pluginData/Python/stdErr.txt"        
        stdOut = OBS.GetAppDataPath()+"/pluginData/Python/stdOut.txt"        
        openFileWithDefaultOSApp(stdErr)
        openFileWithDefaultOSApp(stdOut)
コード例 #13
0
    def CurrentSongInfo(self):
        def OnPlayListClick(event):
            newsongtitle = PlayList.get(PlayList.curselection())
            for i in range(0, int(length)):
                try:
                    if (songlist[i]['title'] == newsongtitle):
                        newsongindex = i
                        break
                except KeyError:
                    if (songlist[i]['artist'] == newsongtitle):
                        newsongindex = i
                        break

            rpi.playid(songlist[newsongindex]['id'])
            rpi.update()

        def ftime(time):
            time = int(time)
            return str(int(time / 60)) + ':' + '%.2d' % int(time % 60)

        self.currentsong = StringVar(self)
        rpi.update()
        cs = rpi.currentsong()
        ss = rpi.status()
        try:
            artist = cs['artist']
        except KeyError:
            artist = '**'
        try:
            album = cs['album']
        except KeyError:
            album = '**'
        try:
            title = cs['title']
        except KeyError:
            title = '**'
        #track = cs['track']
        try:
            num = str(int(ss['song']) + 1)
        except KeyError:
            num = ''
        length = ss['playlistlength']
        try:
            cur_time = ftime(ss['time'].split(':')[0])
        except KeyError:
            cur_time = "0:00"
        # total time
        try:
            total_time = ftime(cs['time'])
        except KeyError:
            total_time = "0:00"
        self.currentsong.set(artist + ' - ' + title + '\n' + album + '\n' +
                             num + '/' + length + '\n\n' + cur_time + '/' +
                             total_time)
        lblframe = LabelFrame(self, text="Now Playing", width=600, height=100)
        lblframe.grid(row=1, column=0, columnspan=7, pady=40)
        #lblframe.grid(row=0, column=1)
        lblframe.grid_propagate(0)
        lbl = Label(lblframe,
                    textvariable=self.currentsong,
                    font=('Tahoma', (9)))
        lbl.grid(row=1, column=0)
        lbl.grid_propagate(0)

        PlayList = Listbox(self, width=80)
        PlayList.grid(row=3, column=1, columnspan=5, padx=20)

        songlist = rpi.playlistid()
        for i in range(0, int(length)):
            try:
                PlayList.insert(i, songlist[i]['title'])
            except KeyError:
                PlayList.insert(i, songlist[i]['artist'])
            if (len(cs) != 0):
                if (cs['id'] == songlist[i]['id']):
                    PlayList.itemconfig(i,
                                        background='blue',
                                        foreground='white')

        PlayList.bind('<<ListboxSelect>>', OnPlayListClick)
コード例 #14
0
ファイル: tkinter.py プロジェクト: imressed/pythonway
    def __init__(self, model):
        self.model = model
        self.model_config = self.model.get_config()
        self.channels_num = 0
        self.channels_amount = 0

        self.root = Tk()
        self.root.resizable(width=FALSE, height=FALSE)
        self.root.title("RaaS. event_proxy configurator")
        #: self.root.iconbitmap('resourse/vit.ico')
        self.config_route = self.model.get_config_route()

        self.panelFrame = Frame(self.root, height=60)
        self.canvas = Canvas(self.root, borderwidth=0)
        self.textFrame = Frame(self.canvas, height=340, width=600)
        self.mainFrame = LabelFrame(self.root, width=200, text="Main:",
                                    height=340, relief=RAISED, borderwidth=1)
        self.chanelFrame = LabelFrame(self.root, width=370, text="Channels:",
                                      height=340, relief=RAISED, borderwidth=1)

        #: self.vsb = Scrollbar(self.root, orient="horizontal",
        #:                     command=self.canvas.xview)
        #:self.canvas.configure(xscrollcommand=self.vsb.set)
        #:self.vsb.pack(side="bottom", fill="x")
        self.canvas.pack(side="bottom", fill="both", expand=True)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        self.root.protocol("WM_DELETE_WINDOW", self.quit_handler)

        self.tabs = Notebook(self.root)
        self.in_channel_text = []
        self.out_port_text = []
        self.out_channel_text = []

        self.c = self.model.get_channels().keys()
        self.channels_len = len(self.model.get_channels())
        #:print self.model.get_channels()
        self.panelFrame.pack(side='top', fill='x')
        self.textFrame.pack(side='bottom', fill='both', expand=1)
        self.mainFrame.place(x=10, y=60)
        self.chanelFrame.place(x=220, y=60)
        self.tabs.place(x=230, y=80)

        x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2
        y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2
        self.root.geometry("+%d+%d" % (x-150, y-150))

        for i in range(self.channels_len):
            self.channels_num += 1
            self.channels_amount += 1

            self.f1 = Frame(self.tabs, height=290, width=350)
            self.tabs.add(self.f1, text='Channel {0}'.format(i + 1))

            self.in_channel = Label(self.f1, text="In channel")
            self.out_port = Label(self.f1, text="Out port")
            self.out_channel = Label(self.f1, text="Out channel")

            self.in_channel_text.append(Entry(self.f1, width=20, bd=3))
            self.in_channel_text[i].insert(0, self.c[i])

            self.out_port_text.append(Entry(self.f1, width=20, bd=3))
            self.out_port_text[i].insert(0, self.model.get_channels()[
                self.c[i]].out_port)

            self.out_channel_text.append(Entry(self.f1, width=20, bd=3))
            self.out_channel_text[i].insert(0, self.model.get_channels()[
                self.c[i]].out_channel)

            self.in_channel.place(x=5, y=10)
            self.in_channel_text[i].place(x=5, y=30)

            self.out_port.place(x=5, y=50)
            self.out_port_text[i].place(x=5, y=70)

            self.out_channel.place(x=5, y=90)
            self.out_channel_text[i].place(x=5, y=110)

            self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format(
                self.channels_amount),
                                     command=
                                     lambda: self.del_channel(i))
            self.del_ch_btn.bind("<Button-1>")
            self.del_ch_btn.place(x=5, y=140, width=100, height=30)

        self.server_host_label = Label(self.root, text="Server host")
        self.server_port_label = Label(self.root, text="Server port")
        self.raas_port_label = Label(self.root, text="Raas port")
        self.encoding_label = Label(self.root, text='Encoding')
        self.levenshtein_distance_label = Label(self.root,
                                                text='Levenshtein distance')
        self.window_time_label = Label(self.root, text='Window time')

        self.server_host_entity = Entry(self.root, width=20, bd=3)
        self.server_host_entity.insert(0, self.model_config['server_host'])

        self.server_port_entity = Entry(self.root, width=20, bd=3)
        self.server_port_entity.insert(0, self.model_config['server_port'])

        self.raas_port_entity = Entry(self.root, width=20, bd=3)
        self.raas_port_entity.insert(0, self.model_config['raas_port'])

        self.encoding_entry = Entry(self.root, width=20, bd=3)
        self.encoding_entry.insert(0, self.model_config['encoding'])

        self.levenshtein_distance_entry = Entry(self.root, width=20, bd=3)
        self.levenshtein_distance_entry.insert(0, self.model_config[
            'levenshtein_distance'])

        self.window_time_entry = Entry(self.root, width=20, bd=3)
        self.window_time_entry.insert(0, self.model_config['window_time'])

        self.var = IntVar()
        self.cfg_debug = self.model_config['debug']
        if self.cfg_debug == 'True':
            self.var.set(1)
        else:
            self.var.set(0)
        self.check_debug = Checkbutton(self.root, text='Debug',
                                       variable=self.var)

        self.filter_var = IntVar()
        self.cfg_use_filter = self.model_config['use_filter']
        if self.cfg_use_filter == 'True':
            self.filter_var.set(1)
        else:
            self.filter_var.set(0)
        self.check_use_filter = Checkbutton(self.root, text='Use filter',
                                            variable=self.filter_var)

        self.addBtn = Button(self.panelFrame, text='Add channel')
        self.saveBtn = Button(self.panelFrame, text='Save')
        self.quitBtn = Button(self.panelFrame, text='Quit')

        self.saveBtn.bind("<Button-1>", self.SaveFile)
        self.quitBtn.bind("<Button-1>", self.Quit)
        self.addBtn.bind("<Button-1>", self.add_channel)

        self.saveBtn.place(x=10, y=10, width=40, height=40)
        self.quitBtn.place(x=60, y=10, width=40, height=40)
        self.addBtn.place(x=220, y=10, width=80, height=40)

        self.server_host_label.place(x=20, y=80)
        self.server_host_entity.place(x=20, y=100)

        self.server_port_label.place(x=20, y=120)
        self.server_port_entity.place(x=20, y=140)

        self.raas_port_label.place(x=20, y=160)
        self.raas_port_entity.place(x=20, y=180)

        self.encoding_label.place(x=20, y=200)
        self.encoding_entry.place(x=20, y=220)

        self.check_debug.place(x=20, y=250)
        self.f = Frame(self.root, height=1, width=190, bg='grey')
        self.f.place(x=15, y=275)

        self.levenshtein_distance_label.place(x=20, y=280)
        self.levenshtein_distance_entry.place(x=20, y=300)

        self.window_time_label.place(x=20, y=320)
        self.window_time_entry.place(x=20, y=340)

        self.check_use_filter.place(x=20, y=370)
コード例 #15
0
ファイル: tkinter.py プロジェクト: imressed/pythonway
class View(Toplevel):
    def __init__(self, model):
        self.model = model
        self.model_config = self.model.get_config()
        self.channels_num = 0
        self.channels_amount = 0

        self.root = Tk()
        self.root.resizable(width=FALSE, height=FALSE)
        self.root.title("RaaS. event_proxy configurator")
        #: self.root.iconbitmap('resourse/vit.ico')
        self.config_route = self.model.get_config_route()

        self.panelFrame = Frame(self.root, height=60)
        self.canvas = Canvas(self.root, borderwidth=0)
        self.textFrame = Frame(self.canvas, height=340, width=600)
        self.mainFrame = LabelFrame(self.root, width=200, text="Main:",
                                    height=340, relief=RAISED, borderwidth=1)
        self.chanelFrame = LabelFrame(self.root, width=370, text="Channels:",
                                      height=340, relief=RAISED, borderwidth=1)

        #: self.vsb = Scrollbar(self.root, orient="horizontal",
        #:                     command=self.canvas.xview)
        #:self.canvas.configure(xscrollcommand=self.vsb.set)
        #:self.vsb.pack(side="bottom", fill="x")
        self.canvas.pack(side="bottom", fill="both", expand=True)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        self.root.protocol("WM_DELETE_WINDOW", self.quit_handler)

        self.tabs = Notebook(self.root)
        self.in_channel_text = []
        self.out_port_text = []
        self.out_channel_text = []

        self.c = self.model.get_channels().keys()
        self.channels_len = len(self.model.get_channels())
        #:print self.model.get_channels()
        self.panelFrame.pack(side='top', fill='x')
        self.textFrame.pack(side='bottom', fill='both', expand=1)
        self.mainFrame.place(x=10, y=60)
        self.chanelFrame.place(x=220, y=60)
        self.tabs.place(x=230, y=80)

        x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2
        y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2
        self.root.geometry("+%d+%d" % (x-150, y-150))

        for i in range(self.channels_len):
            self.channels_num += 1
            self.channels_amount += 1

            self.f1 = Frame(self.tabs, height=290, width=350)
            self.tabs.add(self.f1, text='Channel {0}'.format(i + 1))

            self.in_channel = Label(self.f1, text="In channel")
            self.out_port = Label(self.f1, text="Out port")
            self.out_channel = Label(self.f1, text="Out channel")

            self.in_channel_text.append(Entry(self.f1, width=20, bd=3))
            self.in_channel_text[i].insert(0, self.c[i])

            self.out_port_text.append(Entry(self.f1, width=20, bd=3))
            self.out_port_text[i].insert(0, self.model.get_channels()[
                self.c[i]].out_port)

            self.out_channel_text.append(Entry(self.f1, width=20, bd=3))
            self.out_channel_text[i].insert(0, self.model.get_channels()[
                self.c[i]].out_channel)

            self.in_channel.place(x=5, y=10)
            self.in_channel_text[i].place(x=5, y=30)

            self.out_port.place(x=5, y=50)
            self.out_port_text[i].place(x=5, y=70)

            self.out_channel.place(x=5, y=90)
            self.out_channel_text[i].place(x=5, y=110)

            self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format(
                self.channels_amount),
                                     command=
                                     lambda: self.del_channel(i))
            self.del_ch_btn.bind("<Button-1>")
            self.del_ch_btn.place(x=5, y=140, width=100, height=30)

        self.server_host_label = Label(self.root, text="Server host")
        self.server_port_label = Label(self.root, text="Server port")
        self.raas_port_label = Label(self.root, text="Raas port")
        self.encoding_label = Label(self.root, text='Encoding')
        self.levenshtein_distance_label = Label(self.root,
                                                text='Levenshtein distance')
        self.window_time_label = Label(self.root, text='Window time')

        self.server_host_entity = Entry(self.root, width=20, bd=3)
        self.server_host_entity.insert(0, self.model_config['server_host'])

        self.server_port_entity = Entry(self.root, width=20, bd=3)
        self.server_port_entity.insert(0, self.model_config['server_port'])

        self.raas_port_entity = Entry(self.root, width=20, bd=3)
        self.raas_port_entity.insert(0, self.model_config['raas_port'])

        self.encoding_entry = Entry(self.root, width=20, bd=3)
        self.encoding_entry.insert(0, self.model_config['encoding'])

        self.levenshtein_distance_entry = Entry(self.root, width=20, bd=3)
        self.levenshtein_distance_entry.insert(0, self.model_config[
            'levenshtein_distance'])

        self.window_time_entry = Entry(self.root, width=20, bd=3)
        self.window_time_entry.insert(0, self.model_config['window_time'])

        self.var = IntVar()
        self.cfg_debug = self.model_config['debug']
        if self.cfg_debug == 'True':
            self.var.set(1)
        else:
            self.var.set(0)
        self.check_debug = Checkbutton(self.root, text='Debug',
                                       variable=self.var)

        self.filter_var = IntVar()
        self.cfg_use_filter = self.model_config['use_filter']
        if self.cfg_use_filter == 'True':
            self.filter_var.set(1)
        else:
            self.filter_var.set(0)
        self.check_use_filter = Checkbutton(self.root, text='Use filter',
                                            variable=self.filter_var)

        self.addBtn = Button(self.panelFrame, text='Add channel')
        self.saveBtn = Button(self.panelFrame, text='Save')
        self.quitBtn = Button(self.panelFrame, text='Quit')

        self.saveBtn.bind("<Button-1>", self.SaveFile)
        self.quitBtn.bind("<Button-1>", self.Quit)
        self.addBtn.bind("<Button-1>", self.add_channel)

        self.saveBtn.place(x=10, y=10, width=40, height=40)
        self.quitBtn.place(x=60, y=10, width=40, height=40)
        self.addBtn.place(x=220, y=10, width=80, height=40)

        self.server_host_label.place(x=20, y=80)
        self.server_host_entity.place(x=20, y=100)

        self.server_port_label.place(x=20, y=120)
        self.server_port_entity.place(x=20, y=140)

        self.raas_port_label.place(x=20, y=160)
        self.raas_port_entity.place(x=20, y=180)

        self.encoding_label.place(x=20, y=200)
        self.encoding_entry.place(x=20, y=220)

        self.check_debug.place(x=20, y=250)
        self.f = Frame(self.root, height=1, width=190, bg='grey')
        self.f.place(x=15, y=275)

        self.levenshtein_distance_label.place(x=20, y=280)
        self.levenshtein_distance_entry.place(x=20, y=300)

        self.window_time_label.place(x=20, y=320)
        self.window_time_entry.place(x=20, y=340)

        self.check_use_filter.place(x=20, y=370)

    def del_channel(self, numb):
        rwidth = self.root.winfo_width()
        rheight = self.root.winfo_height()
        if self.channels_num > 6:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() - 65)
            self.root.geometry("%dx%d" % (rwidth - 65, rheight))

        if self.channels_num == 6:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() - 20)
            self.root.geometry("%dx%d" % (rwidth - 20, rheight))

        dvar = self.tabs.tabs().index(self.tabs.select())

        self.in_channel_text.pop(dvar)
        self.out_channel_text.pop(dvar)
        self.out_port_text.pop(dvar)
        self.channels_num -= 1
        self.tabs.forget(self.tabs.select())

        tabs_list = self.tabs.tabs()
        self.root.update()

    def add_channel(self, env):
        if self.channels_num > 15:
            tkMessageBox.showerror('Error',
                                   'You can not add more than 16 channels')
            return False

        rwidth = self.root.winfo_width()
        rheight = self.root.winfo_height()

        if self.channels_num == 5:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() + 20)
            self.root.geometry("%dx%d" % (rwidth + 20, rheight))

        if self.channels_num > 5:
            self.chanelFrame.config(width=self.chanelFrame.winfo_width() + 65)
            self.root.geometry("%dx%d" % (rwidth + 65, rheight))

        self.f1 = Frame(self.tabs, height=290, width=350)
        self.tabs.add(self.f1,
                      text='Channel {0}'.format(self.channels_amount + 1))

        self.in_channel = Label(self.f1, text="In channel")
        self.out_port = Label(self.f1, text="Out port")
        self.out_channel = Label(self.f1, text="Out channel")

        self.in_channel_text.append(Entry(self.f1, width=20, bd=3))

        self.out_port_text.append(Entry(self.f1, width=20, bd=3))

        self.out_channel_text.append(Entry(self.f1, width=20, bd=3))

        self.in_channel.place(x=5, y=10)
        self.in_channel_text[self.channels_num].place(x=5, y=30)

        self.out_port.place(x=5, y=50)
        self.out_port_text[self.channels_num].place(x=5, y=70)

        self.out_channel.place(x=5, y=90)
        self.out_channel_text[self.channels_num].place(x=5, y=110)

        self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format(
            self.channels_num + 1),
                                 command=
                                 lambda: self.del_channel(self.channels_num))
        self.del_ch_btn.bind("<Button-1>")
        self.del_ch_btn.place(x=5, y=140, width=100, height=30)

        self.channels_num += 1
        self.channels_amount += 1

    def Quit(self, env):
        if tkMessageBox.askyesno('Quit', 'Whant to save config before quit?'):
            self.SaveFile(env)
        self.root.destroy()

    def quit_handler(self):
        if tkMessageBox.askyesno('Quit', 'Whant to save config before quit?'):
            self.save_handler()
        self.root.destroy()

    def validate_int(self, var, text, channel):
        if not var.isdigit():
            tkMessageBox.showerror("Error",
                                   "Error in {1}. Value of field '{0}' must be int.".format(text, channel))
            return False
        return True

    def validate_empty(self, var, text):
        if not var:
            tkMessageBox.showerror("Error",
                                   "Field {0} must be not empty.".format(text))
            return False
        return True

    def validate_channels(self):
        if not self.channels_num:
            tkMessageBox.showerror("Error",
                                   "You must add at least one channel")
            return False
        return True

    def validate_change_field(self):
        self.validating_config = self.model.get_updated_config()
        self.flag = False
        if self.server_host_entity.get() != str(self.validating_config['server_host']):
            self.flag = True
        if self.server_port_entity.get() != str(self.validating_config['server_port']):
            self.flag = True
        if self.raas_port_entity.get() != str(self.validating_config['raas_port']):
            self.flag = True
        if self.encoding_entry.get() != str(self.validating_config['encoding']):
            self.flag = True
        if str(self.levenshtein_distance_entry.get()) != str(self.validating_config['levenshtein_distance']):
            self.flag = True
        if str(self.window_time_entry.get()) != str(self.validating_config['window_time']):
            self.flag = True
        self.tmp = IntVar()
        if self.validating_config['debug'] == 'True':
            self.tmp.set(1)
        else:
            self.tmp.set(0)
        if self.tmp.get() != self.var.get():
            self.flag = True
        self.tmp_filter = IntVar()
        if self.validating_config['use_filter'] == 'True':
            self.tmp_filter.set(1)
        else:
            self.tmp_filter.set(0)
        if self.tmp_filter.get() != self.filter_var.get():
            self.flag = True
        #TODO: add validating of channels
        if self.channels_num != self.channels_amount or self.channels_len != self.channels_num:
            return True
        for i in range(self.channels_num):
            if self.in_channel_text[i].get() != str(self.c[i]):
                self.flag = True
            if self.out_port_text[i].get() != str(self.model.get_channels()[
                self.c[i]].out_port):
                self.flag = True
            if self.out_channel_text[i].get() != str(self.model.get_channels()[
                self.c[i]].out_channel):
                self.flag = True
        return self.flag

    def validate_all(self):
        #if not self.validate_change_field():
        #    return False
        if not self.validate_channels():
            return False
        if not self.validate_empty(self.server_host_entity.get(),
                                   'Server host'):
            return False
        if not self.validate_empty(self.encoding_entry.get(), 'Encoding'):
            return False
        if not self.validate_empty(self.levenshtein_distance_entry.get(),
                                   'Levenshtein distance'):
            return False
        if not self.validate_int(self.server_port_entity.get(), 'Server port',
                                 ''):
            return False
        if not self.validate_int(self.raas_port_entity.get(), 'Raas port', ''):
            return False
        if not self.validate_int(self.levenshtein_distance_entry.get(),
                                 'Levenshtein distance', ''):
            return False
        if not self.validate_int(self.window_time_entry.get(), 'Window time',
                                 ''):
            return False
        for i in range(self.channels_num):
            if not self.validate_int(self.in_channel_text[i].get(),
                                     'In channel',
                                     ' Channel {0}'.format(i + 1)):
                return False
            if not self.validate_int(self.out_port_text[i].get(), 'Out port',
                                     ' Channel {0}'.format(i + 1)):
                return False
            if not self.validate_int(self.out_channel_text[i].get(),
                                     'Out channel',
                                     ' Channel {0}'.format(i + 1)):
                return False
        return True

    def SaveFile(self, env):
        self.save_handler()

    def save_handler(self):
        if not self.validate_all():
            return False

        config = ConfigParser.RawConfigParser()
        config.add_section('Main')
        config.set('Main', 'server_host', self.server_host_entity.get())
        config.set('Main', 'server_port', self.server_port_entity.get())
        config.set('Main', 'raas_port', self.raas_port_entity.get())
        result = 'False'
        if self.var.get():
            result = 'True'
        config.set('Main', 'debug', result)
        config.set('Main', 'encoding', self.encoding_entry.get())
        config.set('Main', 'levenshtein_distance',
                   self.levenshtein_distance_entry.get())
        config.set('Main', 'window_time', self.window_time_entry.get())
        result_filter = 'False'
        if self.filter_var.get():
            result_filter = 'True'
        config.set('Main', 'use_filter', result_filter)

        for i in range(self.channels_num):
            config.add_section('Channel{0}'.format(i + 1))
            config.set('Channel{0}'.format(i + 1), 'in_channel',
                       self.in_channel_text[i].get())
            config.set('Channel{0}'.format(i + 1), 'out_port',
                       self.out_port_text[i].get())
            config.set('Channel{0}'.format(i + 1), 'out_channel',
                       self.out_channel_text[i].get())

        with open(self.config_route, 'wb') as configfile:
            config.write(configfile)
        tkMessageBox.showinfo("Info", "Successfully saved.")

    def run(self):
        self.root.mainloop()