Example #1
0
class Interface(Frame):
    """界面操作"""

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        """构建界面"""
        self.radio_value = IntVar()

        Label(self, text="网络安全").grid(row=0, column=2, pady=10)
        # 生成label
        Label(self, text="用户名").grid(row=3, column=1, pady=10)
        Label(self, text="密码").grid(row=4, column=1)
        # 生成用户名和密码输入框
        self.name_input = Entry(self)
        self.name_input.grid(row=3, column=2)
        self.password = Entry(self)
        self.password['show'] = '*'
        self.password.grid(row=4, column=2)

        self.radio = Radiobutton(self, text="rsa", variable=self.radio_value, padx=20, value=1)
        self.radio.grid(row=5, column=1)

        self.radio1 = Radiobutton(self, text="des", variable=self.radio_value, padx=20, value=2)
        self.radio1.grid(row=6, column=1)

        self.alert_button = Button(self, text='提交', command=self.submit)
        self.alert_button.grid(row=7, column=1)

    def submit(self):
        """提交处理"""
        name = self.name_input.get() or 'username'
        password = self.password.get() or "password"
        cryption = self.radio_value.get() or "1"
        # 构造传输的数据
        data = name + ',' + password

        cryption = Crypt()
        my_socket = Mysocket()
        # 判断使用des还是rsa
        if cryption == 2:
            data = "des" + data
            need = 8 - (len(data) % 8)
            while need > 0:
                data += " "
                need -= 1
            result = cryption.des_encrypt(data)
            result = "des" + result
        else:
            result = cryption.rsa_encrypt(data)
            result = "rsa" + result
        result = my_socket.make_connect(result)

        if result >= 0:
            tkMessageBox.showinfo('Message', '%s' % '合法用户')
        else:
            tkMessageBox.showinfo('Message', '%s' % '非法用户')
Example #2
0
 def makeKeys(self):
   keyContainer = Frame(self)
   for number in range (0, DICE):
     button = Button(keyContainer, text = str(number+1), command = self.makePress(number))
     button.grid(row = 1,  column=number)
   
   keyContainer.grid(row = 1, column = 0)
Example #3
0
    def __setup_menus(self):
        self.menu = Menu(self.root, relief=FLAT)
        file_menu = Menu(self.menu, tearoff=0)
        file_menu.add_command(label="Add holiday",
                              command=self.holiday_manager.add_holiday_gui)

        file_menu.add_command(label="Reset holidays", command=self.holiday_manager.reset_holidays_gui)
        file_menu.add_command(label="Goto month", command=self.goto_date_gui)
        self.menu.add_cascade(label="File", menu=file_menu)

        # Contains about option, giving application information
        help_menu = Menu(self.menu, tearoff=0)
        help_menu.add_command(label="About", command=self.about_info_gui)
        self.menu.add_cascade(label="Help", menu=help_menu)

        # Display on screen
        self.root.config(menu=self.menu)

        # Toolbar
        toolbar = Frame(self.root)

        # Add holiday button calls add_new_holiday with args to refresh window
        add_holiday = Button(toolbar, text="Add Holiday",
                             command=self.holiday_manager.add_holiday_gui)
        add_holiday.grid(row=0, column=0)
        tooltip.createToolTip(add_holiday, "Adds a new holiday to the calendar")

        # Reset button clears holidays, resets to current date
        reset_holidays = Button(toolbar, text="Reset Holidays", command=self.holiday_manager.reset_holidays_gui)
        reset_holidays.grid(row=0, column=1)
        tooltip.createToolTip(reset_holidays, "Resets all of the user set holidays")

        toolbar.grid(row=0, sticky="W")
 def __init__(self):
     
     self.root.title("Chat")
     self.root.bind("<Escape>", self.terminate)
     self.root.minsize(888, 250) 
     
     self.menubar.add_command(label="Exit", command=self.terminate)
     self.root.config(menu=self.menubar)
     
     self.checkButton.grid(row=0)
     self.checkButton.configure(state="disabled")
     
     
     self.listbox.insert(END, "talk to everyone")    
     self.listbox.grid(row=1, pady=10,padx=5)
     self.listbox.selection_set(first=0)
     self.listbox.bind('<<ListboxSelect>>', self.onListBoxChanged)
     
     self.input.focus()
     self.input.bind('<Return>', self.sendPressed)
     self.input.grid(row=2, column=1)
     
     
     self.text.configure(state="disabled")
     self.text.grid(row=1, column=1,pady=10,padx=10)
     
     button = Button(self.root, text="Enviar", command= lambda: self.sendPressed())
     button.grid(row=2, column=0, pady=10,padx=10)
Example #5
0
class ActuatorFrame(LabelFrame):
    """Provides a bunch of controls for an ActuatorBoard."""
    def __init__(self, master, board, text="Actuators", *args, **kwargs):
        LabelFrame.__init__(self, master, text=text, *args, **kwargs)
        self.board = board
        
        # The listbox contains integers: port numbers we might
        # want to send messages out to through the Board.
        self.listbox = Listbox(self)
        self.listbox.widget.configure(selectmode=EXTENDED)
        self.listbox.grid(row=0, column=0, sticky='nsew')
        for i in range(192, 208, 2):
            self.listbox.add(i)

        self.movement_frame = MovementFrame(self)
        self.movement_frame.grid()

        self.get_status_button = Button(self, text="Get status",
                                        command=bg_caller(self.get_status))
        self.get_status_button.grid()

        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

    def get_status(self):
        for port in self.listbox.get_selected_items():
            status = self.board.get_status(port)
            logger.info("Status of actuator {}: {}".format(port, status))
Example #6
0
    def goto_date_gui(self):
        date_top = Toplevel()
        date_top.title("Enter date")
        date_top.resizable(0, 0)

        # Inputs for month/year
        goto_month = Label(date_top, text="Month:")
        goto_month.grid(row=0, column=0)

        m_entry = Entry(date_top)
        m_entry.grid(row=0, column=1)

        goto_year = Label(date_top, text="Year:")
        goto_year.grid(row=1, column=0)

        y_entry = Entry(date_top)
        y_entry.grid(row=1, column=1)

        def month_jump():
            try:
                month = int(m_entry.get())
                year = int(y_entry.get())

                if 0 < month <= 12 and 1970 <= year < 5000:
                    self.calendar.month = month - 1
                    self.calendar.year = year
                    self.update_calendar()
            except:
                pass

        submit = Button(date_top, text="Submit", command=month_jump)
        submit.grid(column=0, columnspan=3)
Example #7
0
    def initUI(self):

        self.parent.title("Rename file")
        self.pack(fill=BOTH, expand=1)

        originLabel = Label(self, text="File: " + self.filename)
        originLabel.grid(row=0, column=0, columnspan=2)

        renameLabel = Label(self, text="Rename to:")
        renameLabel.grid(row=1, column=0, columnspan=2)

        self.newName = StringVar()
        self.newName.set(self.filename)
        newName = Entry(self, textvariable=self.newName, width=80)
        endpos = self.filename.rfind('.')
        newName.selection_range(0, endpos if endpos > 0 else END)
        newName.grid(row=2, column=0, columnspan=2)
        newName.bind("<Return>", lambda event: self.doRename())
        newName.bind("<Escape>", lambda event: self.parent.destroy())
        newName.focus_set()

        okButton = Button(self, text="OK", command=self.doRename)
        okButton.grid(row=3, column=0)

        cancelButton = Button(self, text="Cancel", command=self.parent.destroy)
        cancelButton.grid(row=3, column=1)
Example #8
0
class ApplyConfirm(Frame):
    def __init__(self, master=None, apply_information=None):
        Frame.__init__(self, master)
        self.apply_information = apply_information
        self.create_widget()
        self.packall()

    def create_widget(self):
        self.title_label = Label(self, text='确定要提交这个申请给上级审核?')
        self.title_label['width'] = 60
        self.apply_sheet_frame = ApplySheetFrame(self, self.apply_information)
        self.confirm_button = Button(self, text='确认')
        def confirm_func():
            if save_apply_information(self.apply_information):
                MessageBox('提交成功', '提交成功, 可以去消息中心查看')
                self.master.apply_confirm_frame.destroy()
                self.master.people_list_frame.pack()
            else:
                MessageBox('提交失败', '出问题拉')
        self.confirm_button['command'] = confirm_func
        self.cancel_button = Button(self, text='取消')
        def cancel_func():
            self.master.apply_confirm_frame.destroy()
            self.master.apply_information_frame.pack()
        self.cancel_button['command'] = cancel_func

    def packall(self):
        self.title_label.grid(pady=5, row=0, column=0, columnspan=2)
        self.apply_sheet_frame.grid(pady=5, row=1, column=0, columnspan=2)
        self.confirm_button.grid(pady=20, row=2, column=0)
        self.cancel_button.grid(pady=20, row=2, column=1)
Example #9
0
class pgmsface(LabelFrame):

    def getPGMfileName(self):
        options = {'filetypes': [('pgm files', '.pgm')]}
        f = askopenfilename(**options)
        g = f.split('/')
        self.filenameVar.set(g[len(g) - 1])
        return f

    def __init__(self, x):
        LabelFrame.__init__(self, x)
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=10)         
        self.config(relief=GROOVE)
        self.config(borderwidth=2)
        self.config(text = "Testing")
        self.config(labelanchor = "n")

        self.loadPGMbutton = Button(self, text="Load PGM")
        self.loadPGMbutton.grid(row=0, column=0)
        
        self.filenameVar = StringVar()
        self.filenameVar.set("*****.pgm")
        
        self.fileNameLabel = Label(self, textvariable=self.filenameVar)
        self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=18)
        self.fileNameLabel.grid(row=0, column=1)

        self.pack()
Example #10
0
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.last_number = 0
        self.total_label_text = IntVar()
        self.number = 0
        self.operation = '+'

        self.result = Label(master, textvariable=self.total_label_text)

        self.add_button = Button(master, text="+", command=self.add)
        self.sub_button = Button(master, text="-", command=self.sub)
        self.clear_button = Button(master, text="c", command=self.clear)
        self.equals_button = Button(master, text="=", command=self.equals)

        #do buttons in a loop
        row = 1
        for number in range(0,10):
            button = Button(master, text=number, command=lambda x=number: self.update_number(x))
            if number == 0:
                button.grid(row=4,column=1)
                print("adding button 0")
            else:
                button.grid(row=row,column=(number-1)%3)
                if number %3 == 0:
                    row += 1

        # LAYOUT
        self.result.grid(row=0,column=0,columnspan=4)
        self.add_button.grid(row=1,column=3)
        self.sub_button.grid(row=2,column=3)
        self.clear_button.grid(row=3,column=3)
        self.equals_button.grid(row=4,column=3)
Example #11
0
    def __init__(self):
        global board
        global is_server
        self.root = Tk()
        self.root.title("Five In A Row")
        self.root.resizable(width=False,height=False)
        self.font = Font(family = "Helvevtca",size=32)
        board = Board()
        self.buttons = {}
        self.reset_btn = None


        for x,y in board.field:
            handler = lambda x=x,y=y : self.send_to_other(x,y)
            button = Button(self.root,font=self.font,state = DISABLED,command = handler,width = 3 , height = 1)
            button.grid(row = y+1 , column = x)
            self.buttons[x,y] = button
       
        handler = lambda : self.surrender()
        self.reset_btn = Button(self.root,text = "surrender",command = handler,state = DISABLED)
        self.reset_btn.grid(row = board.size +2 , column = 0,columnspan=board.size , sticky = "WE")

        self.txv = Label(self.root,text = "Have a nice game!")
        self.txv.grid(row = 0 , column = 0 , columnspan = board.size , sticky = "WE")

        self.ok_btn = Button(self.root,text = "Ok",state = DISABLED,command = self.ok_click)
        self.ok_btn.grid(row = 8 , column = 0  ,columnspan = board.size , sticky = "WE")
Example #12
0
class Timer(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.inicio = self.agora = 15
        self.pendente = None # alarme pendente
        self.grid()
        self.mostrador = Label(self, width=2, anchor='e',
                               font='Helvetica 120 bold',)
        self.mostrador.grid(column=0, row=0, sticky='nswe')
        self.bt_start = Button(self, text='Start', command=self.start)
        self.bt_start.grid(column=0, row=1, sticky='we')
        self.atualizar_mostrador()
        
    def atualizar_mostrador(self):
        self.mostrador['text'] = str(self.agora)            
        
    def start(self):
        if self.pendente:
            self.after_cancel(self.pendente)
        self.agora = self.inicio
        self.atualizar_mostrador()
        self.pendente = self.after(1000, self.tictac)

    def tictac(self):
        self.agora -= 1
        self.atualizar_mostrador()
        if self.agora > 0:
            self.pendente = self.after(1000, self.tictac)
Example #13
0
    def startUI(self):

        self.files = os.listdir(os.getcwd())

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.quit)

        menubar.add_cascade(label="File", menu=fileMenu)

        listbox = Listbox(self.parent, selectmode=SINGLE)
        listbox.pack(fill=BOTH, expand=1)
        # listbox.insert(END, 'bebs')
        for i in self.files:
            listbox.insert(END, i)

        listbox.grid(column=0, columnspan=4, row=0, rowspan=10, sticky=N+S+E+W)


        txt = Text(self.parent)
        txt.grid(column=6, columnspan=8, row=0, rowspan=10, sticky=N+S+E+W)
        # txt.pack(fill=BOTH, expand=1)

        oBtn = Button(text="Open->", command=lambda: self.readContents(listbox, txt))

        oBtn.grid(column=5, row=3)
Example #14
0
class MeasureFrame(LabelFrame):
    def __init__(self, master, tracker, text="Measuring", *args, **kwargs):
        LabelFrame.__init__(self, master, text=text, *args, **kwargs)
        self.tracker = tracker

        self.config_frame = NamedEntryFrame(self, (OBS_INTERVAL,
                                                   NUM_SAMPLES,
                                                   NUM_OBSS),
                                            parsers={OBS_INTERVAL: float,
                                                     NUM_SAMPLES: int,
                                                     NUM_OBSS: int})
        self.config_frame.grid()

        self.save_frame = LabelFrame(self, text="Saving")
        self.dest_selector = FileSelectionFrame(self.save_frame,
                                                ask_mode="save")
        self.dest_selector.grid(row=0, column=0, columnspan=2)
        self.save_button = Button(self.save_frame, text="Save",
                                  command=bg_caller(self.save))
        self.save_button.grid(row=1, column=0)
        self.appending_var = BooleanVar()
        self.append_checkbutton = Checkbutton(self.save_frame, text="Append",
                                              variable=self.appending_var)
        self.append_checkbutton.grid(row=1, column=1)
        self.save_frame.grid()

    def measure(self, only_accurate=True):
        try:
            interval = self.config_frame.get(OBS_INTERVAL)
            samples = self.config_frame.get(NUM_SAMPLES)
            num_obss = self.config_frame.get(NUM_OBSS)
        except ValueError:
            logger.error("Could not parse input fields.")
        data = self.tracker.measure(observation_interval=interval,
                                    samples_per_observation=samples,
                                    number_of_observations=num_obss)
        if only_accurate:
            accurate_data = [point for point in data
                             if point.status == point.DATA_ACCURATE]
            num_invalid = len(data) - len(accurate_data)
            if num_invalid > 0:
                logger.warning("Hiding {} inaccurate data points."
                               .format(num_invalid))
            return accurate_data
        else:
            return data

    def save(self, only_accurate=True):
        dest = self.dest_selector.path_var.get()
        if not dest:
            logger.error("Must select a destination file.")
            return

        data = self.measure(only_accurate=only_accurate)
        w = csv.writer(open(dest, 'a' if self.appending_var.get() else 'w'))
        for point in data:
            w.writerow((point.time, point.position.r,
                        point.position.theta, point.position.phi))

        logger.info("Saved measurements into {!r}".format(dest))
Example #15
0
class AuthPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)

    def setupView(self, title="Test Auth Page", user='', pwd_ori=''):
        userVar = StringVar()
        pwdVar = StringVar()
        userInput = Entry(self,
                          textvariable=userVar,
                          width="30").grid(row=0,
                                           columnspan=2,
                                           sticky="WE")
        pwdInput = Entry(self,
                         textvariable=pwdVar,
                         show="*",
                         width="30").grid(row=1,
                                          columnspan=2,
                                          sticky="WE")
        userVar.set(user)
        pwdVar.set(pwd_ori)
        self.ok = Button(self,
                         text='Next',
                         command=lambda: self.
                         controller.setAuth(self,
                                            userInput.get(),
                                            pwdInput.get()))
        self.ok.grid(row=2, column=1, sticky="W")
        self.cancel = Button(self,
                             text='Cancel',
                             command=lambda: self.controller.quit())
        self.cancel.grid(row=2, column=0, sticky="E")
Example #16
0
    def __init__(self, buttonDownCallback=None, buttonUpCallback=None):
        self.root = Tk()
        self.root.title("8x8")

        self.buttonUpCallback = buttonUpCallback
        self.buttonDownCallback = buttonDownCallback

        self.pixels = []

        for y in xrange(8):
            for x in xrange(8):
                bt = Button(self.root,
                            bg="gray",
                            width=2, height=1,
                            state="disabled")
                self.pixels.append(bt)
                bt.grid(column=x, row=y)

        self.but = Button(self.root, text="#",
                          width=3, height=1)
        self.but.grid(column=3, row=8, columnspan=2)

        self.butColor = Button(self.root, state="disabled", width=3)
        self.butColor.grid(column=1, row=8, columnspan=2)

        self.orgColor = self.butColor.cget("bg")

        self.but.bind("<Button-1>", self._buttonDown)
        self.but.bind("<ButtonRelease-1>", self._buttonUp)
Example #17
0
class encoderface(LabelFrame):

    def __init__(self, x):
        LabelFrame.__init__(self, x)       
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=12)
        self.config(relief=GROOVE)
        self.config(borderwidth=2, padx=5, pady=5)
        self.config(text = "Encoder")
        self.config(labelanchor = "n")

        self.INSTRUCTION = StringVar()
        self.INSTRUCTION.set("Instruction")
        
        self.machinecode = StringVar()
        self.machinecode.set("")

        self.codeEntry = Entry(self, textvariable=self.INSTRUCTION)

        #self.codeEntry.configure(font=("Helvetica", 12), width=40)
        self.codeEntry.configure(width=40)

        self.codeButton = Button(self, text="Compile")

        self.VHPL = Label(self, text="VHPL")

        self.codeButton.grid(row=0, column=0, rowspan=4, sticky="wens")

        self.VHPL.grid(row=0, column=1, sticky="wens")
        self.VHPL.config(relief=GROOVE, borderwidth=2)
        
        self.codeEntry.grid(row=1, column=1, sticky="wens")
        self.codeEntry.config(fg="green", bg="black")
        
        self.pack()
Example #18
0
 def __init__(self):
     """
     Initiation bits.  Make buttons, give them handlers.  You know,
     all the normal stuff.
     """
     self.computer_first = 0  # randint(0, 1)
     self.app = Tk()
     self.app.attributes("-toolwindow", 1)
     self.app.title('Tic Tac Toe')
     self.app.resizable(width=False, height=False)
     self.board = Board()
     self.font = Font(family="Helvetica", size=32)
     self.buttons = {}
     for x, y in self.board.fields:
         handler = lambda x=x, y=y: self.move(x, y)
         button = Button(self.app, command=handler, font=self.font,
                         width=2, height=1)
         button.grid(row=y, column=x)
         self.buttons[x, y] = button
     handler = lambda: self.reset()
     button = Button(self.app, text='reset', command=handler)
     button.grid(row=self.board.size + 1, column=0,
                 columnspan=self.board.size, stick='WE')
     self.update()
     if self.computer_first:
         self.move(randint(0, self.board.size - 1),
                   randint(0, self.board.size - 1))
Example #19
0
	def __init__( self, main, dataInstance, axes ):
		"""Initializes the file saving dialog."""
		self.main = main
		self.dataInstance = dataInstance
		self.axes = axes
		
		self.root = Tk()
		self.root.title( "Save As CSV" )
		self.root.geometry( "350x200" )
		
		Label( self.root, text="Choose options for save." ).grid( row=0, columnspan=2 )
		
		Label(self.root, text="Filename").grid( row=1,column=0, sticky=tk.W )
		self.main.saveFileName = StringVar( self.root )
		fileNameField = Entry( self.root, textvariable=self.main.saveFileName )
		fileNameField.grid(row=1, column=1)
		
		Label( self.root, text="Number of Columns" ).grid( row=2,column=0, sticky=tk.W )
		self.main.numSaveCols = StringVar( self.root )
		self.main.numSaveCols.set( "All" )
		colNumTuple = ( "All", )
		for i in range( len(axes) ):
			colNumTuple += ( str(i+1), )
		w = apply( OptionMenu, ( self.root, self.main.numSaveCols ) + colNumTuple )
		w.grid( row=2, column=1 )
		
		def callback():
			self.root.destroy()
			if self.main.numSaveCols.get() == "All":
				self.main.writeCSVFile()
			else:
				self.columnChooser()
				
		b1 = Button( self.root, text="Confirm", command=callback )
		b1.grid( row=3, columnspan=2 )	
Example #20
0
	def __init__(self, master):
		rows = 10
		columns = 7
		self.d = door(rows, columns)
		master.title("The Fridge")
		self.frame = Frame(master)

		controls = Frame(self.frame)
		self.start = Button(controls,
						text = "Restart",
						width = 6,
						command = self.restart
						)
		self.start.grid(row = 0, column = 4, columnspan = 2, sticky = E)
		self.rowtext = Entry(controls, width = 4)
		self.rowtext.grid(row = 0, column = 0, columnspan = 2, sticky = W)
		self.coltext = Entry(controls, width = 4)
		self.coltext.grid(row = 0, column = 2, columnspan = 2, sticky = E)
		controls.grid(row = 0, column = 0, columnspan = 7)

		self.bttns = []
		for i in xrange(rows):
			for j in xrange(columns):
				cb = Button(self.frame,
						bg = "green" if self.d.plate[i][j].state else "red",
						text = " ",
						command = self.click(self.bttns, self.d, i, j) # coolhack
						)
				cb.grid(row = i+1, column = j)
				self.bttns.append(cb)

		self.frame.grid(column = 0, row = 0)
Example #21
0
	def columnChooser( self ):
		self.root = Tk()
		self.root.title( "CSV Save Options" )
		
		choiceNum = int(self.main.numSaveCols.get())
		
		geomString = '300x'+str(30+(50*choiceNum))+'-80+80'
		self.root.geometry( geomString)
		
		Label( self.root, text="Choose the header you want in each slot.").grid( row=0, columnspan=2 )
		
		axesTuple = tuple( self.axes )
		self.main.saveChoiceList = [ None ]*choiceNum
		
		for i in range( choiceNum ):
			labelString = "Column "+str(i+1)
			rowNum = i+1
			Label( self.root, text=labelString ).grid( row=rowNum, column=0 )
			self.main.saveChoiceList[i] = StringVar( self.root )
			self.main.saveChoiceList[i].set( self.axes[i] )
			w = apply( OptionMenu, ( self.root, self.main.saveChoiceList[i] ) + axesTuple )
			w.grid( row=rowNum, column=1 )
		
		def callback():
			self.root.destroy()
			self.main.writeCSVFile()
		
		b1 = Button( self.root, text="Confirm", command=callback )
		buttonRow = choiceNum+1
		b1.grid( row=buttonRow, columnspan=2 )
Example #22
0
	def clusterCase( self ):
		"""Controls the window used to choose options for a new PCA and clustering
		   visualization."""
		
		self.scatterWin = Tk()
		self.scatterWin.title('Choose Options For Clustering')
		
		winHeight = 150+(self.axisNum.get()*20)
		sizeString = "300x"+str( winHeight )+"-80+80"
		self.scatterWin.geometry( sizeString )
		
		self.main.clusterChoice = StringVar( self.scatterWin )
		self.main.clusterChoice.set( "Normal" )
		clusterChoiceTuple = ( "Normal", "PCA" )
		Label(self.scatterWin, text="Data by which to Cluster").grid(row=0)
		w = apply( OptionMenu, (self.scatterWin, self.main.clusterChoice) + clusterChoiceTuple )
		w.grid( row=0, column=1 )
		
		self.main.clusterNum = IntVar( self.scatterWin )
		self.main.clusterNum.set( 3 )
		clusterNumTuple = ()
		for i in range( 2, 15 ):
			clusterNumTuple += ( (i+1), )
		Label(self.scatterWin, text="Number of Clusters").grid(row=1)
		k = apply( OptionMenu, (self.scatterWin, self.main.clusterNum) + clusterNumTuple )
		k.grid( row=1, column=1 )

		def callback():
			self.scatterWin.destroy()
			self.dataInstance.prepareClusters()
			self.scatterBuild()
		
		b = Button( self.scatterWin, text="Continue", command=callback )
		b.grid( row=2, columnspan=2 )
Example #23
0
	def special1Case( self ):
		self.root = Tk()
		self.root.title('Choose Filter Options')

		filterCount = 2
		
		winHeight = str(30+(130*filterCount))
		self.root.geometry('500x'+winHeight+'-80+80')
		
		self.main.filterList = None
		
		subjectHeader = StringVar( self.root )
		subjectHeader.set( "SubjectID" )
		subjectField = StringVar( self.root )
		imageHeader = StringVar( self.root )
		imageHeader.set( "Image" )
		imageField = StringVar( self.root )
		
		self.main.colorUse = StringVar( self.root )
		self.main.colorUse.set( "Number" )
		self.main.sizeUse = StringVar( self.root )
		self.main.sizeUse.set( "Duration" )
		
		self.main.filterUse = StringVar( self.root )
		self.main.filterUse.set( "Two" )
		
		emptyFilter = StringVar( self.root )
		
		self.main.axesToPlot = [ None, None ]
		self.main.axesToPlot[0] = StringVar( self.root )
		self.main.axesToPlot[0].set( "x" )
		self.main.axesToPlot[1] = StringVar( self.root )
		self.main.axesToPlot[1].set( "y" )
		
		Label(self.root, text="Choose a subject and image to view fixation results.").grid(row=0, columnspan=2)
		Label(self.root, text="Subject:").grid(row=1, column=0, sticky=tk.W)
		Label(self.root, text="Image:").grid(row=2, column=0, sticky=tk.W)

		subjectText = Entry( self.root, textvariable=subjectField )
		subjectText.grid(row=1, column=1)

		imageText = Entry( self.root, textvariable=imageField )
		imageText.grid(row=2, column=1)
		
		subjectFieldList = [ subjectHeader, subjectText, emptyFilter, emptyFilter ]
		imageFieldList = [ imageHeader, imageText, emptyFilter, emptyFilter ]
			
		localFilterList = [ subjectFieldList, imageFieldList ]
			
		def callback():
			"""Handles the button press at the end of the filter function."""
			for i in range( len( localFilterList ) ):
				for j in range( len( localFilterList[0] ) ):
					localFilterList[i][j] = localFilterList[i][j].get()
			self.main.filterList = localFilterList
			self.root.destroy()
			self.scatterBuild()
			
		b1 = Button( self.root, text="View Fixation Results", command=callback )
		b1.grid( row=3, columnspan=2 )
Example #24
0
    def initialize(self):
        self.grid()
        self.entryVariable = StringVar()
        self.entry = Entry(self, textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)

        button = Button(self,text="SPI send", command=self.OnButtonClick)
        button.grid(column=1,row=0)
        
        #ramp = Button(self,text="RAMP", command=self.setlabvar)
        #ramp.grid(column=1,row=1)        

        self.labelVariable = StringVar()
        label = Label(self,textvariable=self.labelVariable,
                              anchor="w",fg="white",bg="blue")
        label.grid(column=0,row=1,columnspan=1,sticky='EW')
        self.labelVariable.set("Start..")
        
        self.slider = Scale(self, from_=0, to=80, orient=HORIZONTAL, 
                            command=self.setlabvar)
        self.slider.grid(column=0, row=2, columnspan=3, sticky='EW')
        
        self.PID = PIDTune(self)
        self.PID.grid(column=0, row=3, columnspan=3, sticky='EW')
        
        self.grid_columnconfigure(0,weight=1)
        self.update()
        #self.geometry(self.geometry()) # caused busy wait?
        self.entry.focus_set()
Example #25
0
def save(squares):
    """
    Handle the save key on the main window.
    """
    def save_button_hit():
        """
        Save key (on local window) was hit.  Save the file name entered.
        """
        text_in = save_entry.get().strip()
        if len(text_in) == 0:
            showwarning('Error', 'File name specified is empty.')
            return
        outfile = os.path.join(savedir, text_in)
        with open(outfile, 'w') as fyle:
            for sqr_info in save_squares:
                fyle.write('%d:%d:%s\n' % tuple(save_squares[sqr_info]))
        top.destroy()
    top = Toplevel()
    top.geometry('180x80+800+200')
    top.title('Save a layout')
    save_squares = squares
    savedir = getdir()
    label1 = Label(top, text='File name')
    save_entry = Entry(top)
    label1.grid(row=0)
    save_entry.grid(row=0, column=1, columnspan=2)
    save_entry.focus_set()
    save_button = Button(top, text='SAVE', pady=3,
            command=save_button_hit)
    sspace = Label(top)
    sspace.grid(row=1)
    save_button.grid(row=2, column=1)
    top.mainloop()
class ParamItem(Frame):
    
    def __init__(self, master, itemList, deleteCount):
        Frame.__init__(self, master)
        self.labelKey = Label(self, text = "Key:")
        self.labelValue = Label(self, text = "Value:")
        self.entryKey = Entry(self, width = 8)
        self.entryValue = Entry(self, width = 20)
        self.deleteCount = deleteCount
        self.itemList = itemList
        self.btnDelete = Button(self, text = "delete", \
            command = self.__internalDelete, padx = 5)
        self.__boxComponents()
    
    def __boxComponents(self):
        self.labelKey.grid(row = 0, column = 0)
        self.entryKey.grid(row = 0, column = 1)
        self.labelValue.grid(row = 0, column = 2)
        self.entryValue.grid(row = 0, column = 3)
        self.btnDelete.grid(row = 0, column = 4)
    
    def __internalDelete(self):
        self.deleteCount.set(self.deleteCount.get() + 1)
        self.itemList.remove(self)
        self.destroy()
    def getKey(self):
        return self.entryKey.get()
    
    def getValue(self):
        return self.entryValue.get()
class FrOptions(LabelFrame):
    def __init__(self, title, txt, dicoprofils):
        LabelFrame.__init__(self, text=title)
        self.listing_profils(dicoprofils)

        # Dropdowm list of available profiles
        self.ddprofils = Combobox(self,
                                  values = dicoprofils.keys(),
                                  width = 35,
                                  height = len(dicoprofils.keys())*20)
        self.ddprofils.current(1)   # set the dropdown list to first element

        # export options
        caz_doc = Checkbutton(self, text = u'HTML / Word (.doc/.docx)',
                                    variable = self.master.opt_doc)
        caz_xls = Checkbutton(self, text = u'Excel 2003 (.xls)',
                                    variable = self.master.opt_xls)
        caz_xml = Checkbutton(self, text = u'XML (ISO 19139)',
                                    variable = self.master.opt_xml)

        # Basic buttons
        self.action = StringVar()
        self.action.set(txt.get('gui_choprofil'))
        self.val = Button(self, textvariable = self.action,
                                relief= 'raised',
                                command = self.bell)
        can = Button(self, text = 'Cancel (quit)',
                                relief= 'groove',
                                command = self.master.destroy)
        # Widgets placement
        self.ddprofils.bind('<<ComboboxSelected>>', self.alter_val)
        self.ddprofils.grid(row = 1, column = 0, columnspan = 3, sticky = N+S+W+E, padx = 2, pady = 5)
        caz_doc.grid(row = 2, column = 0, sticky = N+S+W, padx = 2, pady = 1)
        caz_xls.grid(row = 3, column = 0, sticky = N+S+W, padx = 2, pady = 1)
        caz_xml.grid(row = 4, column = 0, sticky = N+S+W, padx = 2, pady = 1)
        self.val.grid(row = 5, column = 0, columnspan = 2,
                            sticky = N+S+W+E, padx = 2, pady = 5)
        can.grid(row = 5, column = 2, sticky = N+S+W+E, padx = 2, pady = 5)

    def listing_profils(self, dictprofils):
        u""" List existing profilesin folder \data\profils """
        for i in glob(r'../data/profils/*.xml'):
            dictprofils[path.splitext(path.basename(i))[0]] = i
##        if new > 0:
##            listing_lang()
##            load_textes(deroul_lang.get())
##            deroul_profils.setlist(sorted(dico_profils.keys()))
##            fen_choix.update()
        # End of function
        return dictprofils

    def alter_val(self, inutile):
        u""" Switch the label of the validation button contained in basics class
        in the case that a new profile is going to be created"""
        if self.ddprofils.get() == self.master.blabla.get('gui_nouvprofil'):
            self.action.set(self.master.blabla.get('gui_crprofil'))
        else:
            self.action.set(self.master.blabla.get('gui_choprofil'))
        # End of functionFin de fonction
        return self.action
Example #28
0
 def make_seek_button(label, column, frame):
     def jump():
         self.jumpTo(frame)
     b = Button(self.tk_controlFrame,
                text=label,
                command=jump)
     b.grid(row=1, column=column, sticky=W+E)
     return b
Example #29
0
	def __init__( self, width, height ):
		"""Initialize the Main Class for VIOLAS Program"""
		
		self.root = tk.Tk()
		self.desiredFile = None
		self.width = width
		self.height = height
		self.root.title("Welcome")
		w = tk.Message(self.root, 
					   text= " \n\n " +
					   "	Welcome to V.I.O.L.A.S.!\n\n" + 
					" Visual Information Observation, Logging, \n "
					"	   and Analysis System\n\n\n" +
					"  Please choose the desired CSV file you \n" +
					"	   would like to analyze! " +
					" \n\n\n ",
					background='blue', foreground='white', border=0, width=300, font='courier 12 bold')	 
		w.pack()

		fobj = tkFileDialog.askopenfile( parent=self.root, mode='rb', title='Choose a data file...' )
		self.desiredFile = os.path.basename(fobj.name)
		self.fileNameShort = os.path.splitext(self.desiredFile)[0]
		
		self.root.destroy()
		
		self.dataHandler = ds.DataSet( self, filename=fobj.name )
		
		self.root = tk.Tk()
		self.root.title("Configure PCA")
		self.root.geometry( "350x200-80+80" )
		
		self.pcaCut = StringVar( self.root )
		self.pcaCut.set( "Yes" )
		Label(self.root, text="Remove Last Column?").grid(row=0)
		k = apply( OptionMenu, ( self.root, self.pcaCut ) + ( "Yes", "No" ) )
		k.grid( row=0, column=1 )
		
		self.pcaNormalize = StringVar( self.root )
		self.pcaNormalize.set( "No" )
		Label(self.root, text="Normalize Before PCA?").grid(row=1)
		j = apply( OptionMenu, ( self.root, self.pcaNormalize ) + ( "No", "Yes" ) )
		j.grid( row=1, column=1 )
		
		self.varPercent = IntVar( self.root )
		self.varPercent.set( 100 )
		Label(self.root, text="Minimum Percent Variation").grid(row=2)
		l = Entry( self.root, textvariable=self.varPercent )
		l.grid(row=2, column=1)

		def callback():
			self.root.destroy()
			pcaData = self.dataHandler.buildPCA( self.dataHandler.numbData )
			self.vectorHandler = ds.DataSet( self, passData=pcaData )
			print self.eigenList
			self.initializeGUI( width, height )
		
		b = Button( self.root, text="Continue", command=callback )
		b.grid( row=3, columnspan=2 )
Example #30
0
    def netComparer(self):  #Interface
        top = Toplevel()
        top.title("NetworkComparer")

        self.genelistNC = []
        for string in self.queries:
            if "No hit" not in string:
                self.genelistNC.append(string.split("\t"))
        DescriptionLabel = LabelFrame(
            top, text="Select the gene of interest and specify parameters.")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list below.\nThis tool will generate netComp.html file containing a page similar to\nfirst step of NetworkComparer."
        )
        DescriptionLabel.grid(row=0, column=0)
        Description.grid(row=0)
        ParametersLabel = LabelFrame(DescriptionLabel, text="Parameters")
        Steps = Label(ParametersLabel, text="Number of steps")
        ParametersLabel.grid(row=1, column=2)
        Hrr = Label(ParametersLabel, text="HRR cut-off.")
        Steps.grid(row=0)
        Hrr.grid(row=2)
        self.paraSteps = Entry(ParametersLabel)
        self.paraSteps.grid(row=1)
        self.paraSteps.insert(END, 2)
        self.paraHrr = Entry(ParametersLabel)
        self.paraHrr.grid(row=3)
        self.paraHrr.insert(END, 30)
        self.listbox = Listbox(DescriptionLabel,
                               width=40,
                               height=30,
                               exportselection=0)
        probeName = []
        for gene in self.genelistNC:
            self.listbox.insert(END,
                                gene[0] + '   ' + gene[1] + '   ' + gene[3])
        self.listbox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarG = Scrollbar(DescriptionLabel)
        scrollbarG.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarG.config(command=self.listbox.yview)

        NetworkLabel = LabelFrame(
            top, text="Select the networks/species you want to compare.")
        Network = Label(
            NetworkLabel,
            text=
            "Available networks are displayed in the list below. Check/uncheck networks of interest."
        )
        NetworkLabel.grid(row=0, column=1)
        Network.grid(row=0)
        self.networkBox = Listbox(NetworkLabel,
                                  width=40,
                                  height=30,
                                  selectmode=MULTIPLE,
                                  exportselection=0)
        self.networkList = []
        for i in os.listdir("."):
            if ".hrr" in i:
                self.networkBox.insert(END, i)
                self.networkList.append(i)
        self.networkBox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarN = Scrollbar(NetworkLabel)
        scrollbarN.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarN.config(command=self.networkBox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.netComparerPipe)
        button.grid(row=1, column=0, columnspan=5, sticky=E + W)
Example #31
0
my_app = Tk(className='Aplikasi dengan beberapa widget')
L0 = Label(my_app, text='Data Diri', font=('Arial', 24))
L0.grid(row=0, column=0)
L1 = Label(my_app, text='Nama')
L1.grid(row=1, column=0)
E1 = Entry(my_app)
E1.grid(row=1, column=1)
L2 = Label(my_app, text='NIM')
L2.grid(row=2, column=0)
E2 = Entry(my_app)
E2.grid(row=2, column=1)
L3 =Label(my_app, text='Buku Favorit')
L3.grid(row=3, column=0)
E3 = Entry(my_app)
E3.grid(row=3, column=1)
L4 = Label(my_app, text='Idola dikalangan sahabat')
L4.grid(row=4, column=0)
E4 = Entry(my_app)
E4.grid(row=4, column=1)
L5 = Label(my_app, text='Motto')
L5.grid(row=5, column=0)
E5 = Entry(my_app)
E5.grid(row=5, column=1)

def tampil_pesan():
    showinfo('Pesan', 'Hello World')

B = Button(my_app, text='Tutup', command=my_app.quit())
B.grid(row=6, column=1)
my_app.mainloop()
Example #32
0
class Visualiser(Thread):
    """Superclass of both the realtime and offline VTK visualisers
    """
    def __init__(self, source):
        Thread.__init__(self)

        self.source = source

        # Structures for Height Based quantities
        self.height_quantities = []
        self.height_zScales = {}
        self.height_dynamic = {}
        self.height_offset = {}
        self.height_opacity = {}
        self.height_wireframe = {}

        # Structures for colouring quantities
        self.colours_height = {}

        # Structures used for VTK
        self.vtk_actors = {}
        self.vtk_axesSet = False
        self.vtk_drawAxes = False
        self.vtk_mappers = {}
        self.vtk_polyData = {}

        # A list of operations to be performed on the cube axes. Type: [(func, (args))]
        self.conf_axesAlterations = []
        # A list of all polygons to overlay. Type: [([coords], height, (colour)]
        self.conf_overlaidPolygons = []
        # A list of alterations to be performed on the Tk root. Type: [(func, (args))]
        self.conf_tkAlterations = []

    def run(self):
        self.vtk_renderer = vtkRenderer()
        self.setup_gui()
        self.setup_grid()

        # Handle any deferred configuration
        # Overlaid polygons
        for args in self.conf_overlaidPolygons:
            self.overlay_polygon_internal(*args)
        # Draw (and maybe alter) the axes
        if self.vtk_drawAxes:
            self.vtk_axes = vtkCubeAxesActor2D()
            # Perform all of the alterations required, by applying func to the vtk_axes instance (with the given args).
            for func, args in self.conf_axesAlterations:
                func(*((self.vtk_axes, ) + args))
        # Alter the Tk root as necessary.
        for func, args in self.conf_tkAlterations:
            func(*((self.tk_root, ) + args))
        # Finished with deferred configuration.

        # Draw Height Quantities
        for q in self.height_quantities:
            self.update_height_quantity(q, self.height_dynamic[q])
            self.draw_height_quantity(q)

        self.tk_root.mainloop()

    def redraw_quantities(self):
        """Redraw all dynamic quantities.
        """
        # Height quantities
        for q in self.height_quantities:
            if (self.height_dynamic[q]):
                self.update_height_quantity(q, self.height_dynamic[q])
                self.draw_height_quantity(q)
        if self.vtk_drawAxes is True:
            self.draw_axes()

    # --- Axes --- #

    def render_axes(self):
        """Intstruct the visualiser to render cube axes around the render.
        """
        self.vtk_drawAxes = True

    def draw_axes(self):
        """Update the 3D bounds on the axes and add them to the pipeline if not yet connected.
        """
        self.vtk_axes.SetBounds(self.get_3d_bounds())
        if not self.vtk_axesSet:
            self.vtk_axesSet = True
            self.vtk_axes.SetCamera(self.vtk_renderer.GetActiveCamera())
            self.vtk_renderer.AddActor(self.vtk_axes)
            self.vtk_renderer.ResetCamera(self.get_3d_bounds())

    def alter_axes(self, func, args):
        """Attempt to apply the function 'func' with args tuple 'args' to the
        vtkCubeAxesActor2D instance set up by render_axes. This is done this way to ensure
        the axes setup is handled in the visualiser thread.

        Example call:
        from vtk import vtkCubeAxesActor2D
        alter_axes(vtkCubeAxesActor2D.SetNumberOfPoints, (5,))
        """
        self.conf_axesAlterations.append((func, args))

    # --- Height Based Rendering --- #

    def setup_grid(self):
        """Create the vtkCellArray instance that represents the
        triangles. Subclasses are expected to override this function
        to read from their source as appropriate. The vtkCellArray should
        be stored to self.vtk_cells.
        """
        pass

    def render_quantity_height(self,
                               quantityName,
                               zScale=1.0,
                               offset=0.0,
                               opacity=1.0,
                               dynamic=True,
                               wireframe=False):
        """Instruct the visualiser to render a quantity using the
        value at a point as its height.  The value at each point is
        multiplied by z_scale and is added to offset, and if
        dynamic=False, the quantity is not recalculated on each
        update.
        """
        self.height_quantities.append(quantityName)
        self.height_zScales[quantityName] = zScale
        self.height_offset[quantityName] = offset
        self.height_dynamic[quantityName] = dynamic
        self.height_opacity[quantityName] = opacity
        self.height_wireframe[quantityName] = wireframe

    def update_height_quantity(self, quantityName, dynamic=True):
        """Create a vtkPolyData object and store it in
        self.vtk_polyData[quantityName]. Subclasses are expected to override this
        function.
        """
        pass

    def get_3d_bounds(self):
        """Get the minimum and maximum bounds for the x, y and z directions.
        Return as a list of double in the order (xmin, xmax, ymin, ymax, zmin, zmax),
        suitable for passing to vtkCubeAxesActor2D::SetRanges(). Subclasses are expected
        to override this function.
        """
        pass

    def store_height_quantity(self, quantityName, fileName=None):

        if fileName == None:
            fileName = quantityName + '.vtk'

        quantity_polyData = self.vtk_polyData[quantityName]

        import vtk
        w = vtk.vtkPolyDataWriter()
        #print quantity_polyData
        w.SetInput(quantity_polyData)
        w.SetFileName(fileName)
        w.Write()

    def draw_height_quantity(self, quantityName):
        """Use the vtkPolyData and prepare/update the rest of the VTK
        rendering pipeline.
        """
        if self.vtk_mappers.has_key(quantityName):
            mapper = self.vtk_mappers[quantityName]
        else:
            mapper = self.vtk_mappers[quantityName] = vtkPolyDataMapper()
        mapper.SetInput(self.vtk_polyData[quantityName])
        mapper.Update()

        if not self.vtk_actors.has_key(quantityName):
            actor = self.vtk_actors[quantityName] = vtkActor()
            actor.GetProperty().SetOpacity(self.height_opacity[quantityName])
            if self.height_wireframe[quantityName]:
                actor.GetProperty().SetRepresentationToWireframe()
            actor.SetMapper(mapper)
            self.vtk_renderer.AddActor(actor)
        else:
            actor = self.vtk_actors[quantityName]

        if self.colours_height.has_key(quantityName):
            colour = self.colours_height[quantityName]
            if type(colour) == TupleType:
                if type(colour[0]) == FunctionType:
                    # It's a function, so take colour[1] as the
                    # lower bound on the scalar range and
                    # colour[2] as the upper bound on the scalar
                    # range.
                    scalars = vtkFloatArray()

                    map(scalars.InsertNextValue,
                        colour[0](self.build_quantity_dict()))
                    self.vtk_polyData[quantityName].GetPointData().SetScalars(
                        scalars)
                    mapper.SetScalarRange(colour[1:])
                    mapper.Update()
                else:
                    # It's a 3-tuple representing an RGB value.
                    actor.GetProperty().SetColor(colour)
            else:
                actor.GetProperty().SetColor(0.5, 0.5, 0.5)
        else:
            actor.GetProperty().SetColor(0.5, 0.5, 0.5)

    # --- Colour Coding --- #

    def build_quantity_dict(self):
        """Build and return a dictionary mapping quantity name->Numeric array of vertex
        values for that quantity. Subclasses are expected to override
        this function."""
        pass

    def colour_height_quantity(self, quantityName, colour=(0.5, 0.5, 0.5)):
        """Add colouring to a height based quantity.

        The colour parameter can be one of the following:
        - a 3-tuple of values in [0,1] to specify R, G, B values
        - a 3-tuple of values:
          - a function that takes a dictionary mapping quantity name->Numeric array of vertex values.
            This function returns a list of vertex values to be used in the colour coding.
          - a float for the lower bound on the colouring
          - a float for the upper bound on the colouring
        """
        self.colours_height[quantityName] = colour

    # --- Overlaid Polygons --- #

    def overlay_polygon(self, coords, height=0.0, colour=(1.0, 0.0, 0.0)):
        """Add a polygon to the output of the visualiser.

        coords is a list of 2-tuples representing x and y coordinates.
        These are triangulated by vtkDelaunay2D.

        height is the z-value given to all points.

        colour is the colour of the polygon, as a 3-tuple representing
        r, g, b values between 0 and 1."""
        self.conf_overlaidPolygons.append((coords, height, colour))

    def overlay_polygon_internal(self, coords, height, colour):
        """Add a polygon to the output of the visualiser.

        coords is a list of 2-tuples representing x and y coordinates.
        These are triangulated by vtkDelaunay2D.

        height is the z-value given to all points.

        colour is the colour of the polygon, as a 3-tuple representing
        r, g, b values between 0 and 1.

        This function should not be called from outside the visualiser thread.
        Use overlay_polygon instead.
    
        """
        points = vtkPoints()
        for coord in coords:
            points.InsertNextPoint(coord[0], coord[1], height)
        profile = vtkPolyData()
        profile.SetPoints(points)
        delny = vtkDelaunay2D()
        delny.SetInput(profile)
        mesh = vtkPolyDataMapper()
        mesh.SetInput(delny.GetOutput())
        actor = vtkActor()
        actor.SetMapper(mesh)
        actor.GetProperty().SetColor(colour)
        self.vtk_renderer.AddActor(actor)

    # --- Vector Fields --- #

    # --- GUI Setup --- #

    def setup_gui(self):
        self.tk_root = Tk()
        self.tk_root.title("Visualisation")
        self.tk_root.after(100, self.redraw)
        self.tk_root.bind("<Destroy>", self.destroyed)
        self.tk_root.grid_rowconfigure(0, weight=1)
        self.tk_root.grid_columnconfigure(0, weight=1)

        self.tk_renderWidget = vtkTkRenderWidget(self.tk_root,
                                                 width=400,
                                                 height=400)
        self.tk_renderWidget.grid(row=0, column=0, sticky=N + S + E + W)
        self.tk_controlFrame = Frame(self.tk_root)
        self.tk_controlFrame.grid(row=1, column=0, sticky=E + W)
        self.tk_controlFrame.grid_rowconfigure(0, weight=1)
        self.tk_controlFrame.grid_columnconfigure(0, weight=1)

        self.tk_quit = Button(self.tk_controlFrame,
                              text="Quit",
                              command=self.shutdown)
        self.tk_quit.grid(row=0, column=0, sticky=E + W)
        self.tk_renderWidget.GetRenderWindow().AddRenderer(self.vtk_renderer)

    def alter_tkroot(self, func, args):
        """Apply func, with arguments tuple args to the root tk window for this visualiser.
        """
        self.conf_tkAlterations.append((func, args))

    # --- GUI Events --- #

    def destroyed(self, event):
        if event.widget == self.tk_root:
            self.shutdown()

    def redraw(self):
        self.tk_renderWidget.GetRenderWindow().Render()
        self.tk_root.update_idletasks()
        self.tk_root.after(100, self.redraw)

    def shutdown(self):
        self.tk_root.withdraw()
        self.tk_root.destroy()
Example #33
0
    def show(self):
        self.__root.title(CONST.APP_NAME)
        mainFrame = Frame(self.__root)

        top = mainFrame.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        mainFrame.rowconfigure(0, weight=1)
        mainFrame.columnconfigure(0, weight=1)
        mainFrame.grid(sticky='ew')

        # Three Sections: Input-Settings, Output-Settings and Buttons
        inputFrame = LabelFrame(mainFrame, text='Input Settings')
        inputFrame.columnconfigure(2, weight=1)
        inputFrame.grid(column=0, row=0, padx=5, pady=5, sticky='ew')
        outputFrame = LabelFrame(mainFrame, text='Output Settings')
        outputFrame.columnconfigure(2, weight=1)
        outputFrame.grid(column=0, row=1, padx=5, pady=5, sticky='ew')
        miscFrame = LabelFrame(mainFrame, text='Misc Settings')
        miscFrame.columnconfigure(2, weight=1)
        miscFrame.grid(column=0, row=2, padx=5, pady=5, sticky='ew')
        buttonFrame = Frame(mainFrame)
        buttonFrame.columnconfigure(3, weight=1)
        buttonFrame.grid(column=0, row=3, padx=5, pady=5, sticky='ew')

        # Input-Settings
        scribusSourceFileLabel = Label(
            inputFrame, text='Scribus File:', width=15, anchor='w')
        scribusSourceFileLabel.grid(
            column=0, row=0, padx=5, pady=5, sticky='w')
        scribusSourceFileEntry = Entry(
            inputFrame, textvariable=self.__ctrl.getScribusSourceFileEntryVariable())
        scribusSourceFileEntry.grid(
            column=1, columnspan=3, row=0, padx=5, pady=5, sticky='ew')
        scribusSourceFileButton = Button(
            inputFrame, text='⏏', command=self.__ctrl.scribusSourceFileEntryVariableHandler)
        scribusSourceFileButton.grid(
            column=4, row=0, padx=5, pady=5, sticky='e')
        scribusLoadSettingsButton = Button(
            inputFrame, text='↺', command=self.__ctrl.scribusLoadSettingsHandler)  # ⟲ ⟳ ↻ ↺ ⌂ ⌘ ⎗
        scribusLoadSettingsButton.grid(
            column=5, row=0, padx=5, pady=5, sticky='e')

        dataSourceFileLabel = Label(
            inputFrame, text='Data File:', width=15, anchor='w')
        dataSourceFileLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        dataSourceFileEntry = Entry(
            inputFrame, textvariable=self.__ctrl.getDataSourceFileEntryVariable())
        dataSourceFileEntry.grid(
            column=1, columnspan=4, row=1, padx=5, pady=5, sticky='ew')
        dataSourceFileButton = Button(
            inputFrame, text='⏏', command=self.__ctrl.dataSourceFileEntryVariableHandler)
        dataSourceFileButton.grid(column=5, row=1, padx=5, pady=5, sticky='e')

        dataSeparatorLabel = Label(
            inputFrame, text='Data Field Separator:', width=15, anchor='w')
        dataSeparatorLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')
        dataSeparatorEntry = Entry(
            inputFrame, width=3, textvariable=self.__ctrl.getDataSeparatorEntryVariable())
        dataSeparatorEntry.grid(column=1, row=2, padx=5, pady=5, sticky='w')

        fromLabel = Label(
            inputFrame, text='(opt.) use partial data, only from:', anchor='e')
        fromLabel.grid(column=2, row=2, padx=5, pady=5, sticky='e')
        fromEntry = Entry(inputFrame, width=3,
                          textvariable=self.__ctrl.getFromVariable())
        fromEntry.grid(column=3, row=2, padx=5, pady=5, sticky='w')

        toLabel = Label(inputFrame, text='to:', width=3, anchor='e')
        toLabel.grid(column=4, row=2, padx=5, pady=5, sticky='e')
        toEntry = Entry(inputFrame, width=3,
                        textvariable=self.__ctrl.getToVariable())
        toEntry.grid(column=5, row=2, padx=5, pady=5, sticky='w')

        # Output-Settings
        outputDirectoryLabel = Label(
            outputFrame, text='Output Directory:', width=15, anchor='w')
        outputDirectoryLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')
        outputDirectoryEntry = Entry(
            outputFrame, textvariable=self.__ctrl.getOutputDirectoryEntryVariable())
        outputDirectoryEntry.grid(
            column=1, columnspan=4, row=0, padx=5, pady=5, sticky='ew')
        outputDirectoryButton = Button(
            outputFrame, text='⏏', command=self.__ctrl.outputDirectoryEntryVariableHandler)
        outputDirectoryButton.grid(column=5, row=0, padx=5, pady=5, sticky='w')

        outputFileNameLabel = Label(
            outputFrame, text='Output File Name:', width=15, anchor='w')
        outputFileNameLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        outputFileNameEntry = Entry(
            outputFrame, textvariable=self.__ctrl.getOutputFileNameEntryVariable())
        outputFileNameEntry.grid(
            column=1, columnspan=3, row=1, padx=5, pady=5, sticky='ew')

        outputFormatLabel = Label(
            outputFrame, text='Format:', anchor='e')
        outputFormatLabel.grid(column=4, row=1, padx=5, pady=5, sticky='e')
        outputFormatListBox = OptionMenu(outputFrame, self.__ctrl.getSelectedOutputFormat(), *self.__ctrl.getOutputFormatList(),
                                         command=lambda v=self.__ctrl.getSelectedOutputFormat(): self.updateState(v))
        outputFormatListBox.grid(column=5, row=1, padx=5, pady=5, sticky='w')
        
        mergeOutputLabel = Label(
            outputFrame, text='Merge in Single File:', width=17, anchor='w')
        mergeOutputLabel.grid(column=0,  columnspan=2, row=2, padx=5, pady=5, sticky='w')
        mergeOutputCheckbox = Checkbutton(
            outputFrame, variable=self.__ctrl.getMergeOutputCheckboxVariable())
        mergeOutputCheckbox.grid(column=2, row=2, padx=5, pady=5, sticky='w')

        self.keepGeneratedScribusFilesLabel = Label(
            outputFrame, text='Keep Scribus Files:', width=15, anchor='w')
        self.keepGeneratedScribusFilesLabel.grid(
            column=3, columnspan=2, row=2, padx=5, pady=5, sticky='w')
        self.keepGeneratedScribusFilesCheckbox = Checkbutton(
            outputFrame, variable=self.__ctrl.getKeepGeneratedScribusFilesCheckboxVariable(), anchor='w')
        self.keepGeneratedScribusFilesCheckbox.grid(
            column=5, row=2, padx=5, pady=5, sticky='w')

        
        # Misc Settings
        saveLabel = Label(miscFrame, text='Save Settings:',
                          width=12, anchor='w')
        saveLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        saveCheckbox = Checkbutton(
            miscFrame, variable=self.__ctrl.getSaveCheckboxVariable())
        saveCheckbox.grid(column=1, row=1, padx=5, pady=5, sticky='w')

        closeLabel = Label(miscFrame, text='Close dialog on success:',
                          width=20, anchor='w')
        closeLabel.grid(column=3, columnspan=2, row=1, padx=5, pady=5, sticky='e')
        closeCheckbox = Checkbutton(
            miscFrame, variable=self.__ctrl.getCloseDialogVariable())
        closeCheckbox.grid(column=5, row=1, padx=5, pady=5, sticky='e')

        
        # Bottom Buttons
        generateButton = Button(
            buttonFrame, text='✔\nGenerate', width=10, command=self.__ctrl.buttonOkHandler)
        generateButton.grid(column=0, row=0, padx=5, pady=5, sticky='w')
        cancelButton = Button(buttonFrame, text='✘\nCancel',
                              width=10, command=self.__ctrl.buttonCancelHandler)
        cancelButton.grid(column=1, row=0, padx=5, pady=5, sticky='e')
        helpButton = Button(buttonFrame, text='❓\nHelp',
                            width=7, command = lambda: webbrowser.open("https://github.com/berteh/ScribusGenerator/#how-to-use-scribus-generator"))
        helpButton.grid(column=3, row=0, padx=5, pady=5, sticky='e')

        # general layout
        mainFrame.grid()
        self.__root.grid()
class ReversiView:
    """
    Creates window with the reversi board and controls the game using gui.
    """
    def __init__(self, players, board_size=8, w=850, h=410):
        """
        :param w: width of the window
        :param h: height of the window
        """
        self.root = Tk()
        self.board_size = board_size
        self.stone_board = [-1] * self.board_size
        for row in range(self.board_size):
            self.stone_board[row] = [-1] * self.board_size
        self.w = w
        self.h = h
        self.offx = 5
        self.offy = 5
        self.gridw = 410
        self.gridh = 410
        self.gridspacing = 50
        self.ovalDiamPart = 0.8
        self.colors = ["blue", "red"]
        self.root.title("Reversi")

        self.interactive_player_ids = []
        self.interactivePlayers = []

        self.interractivePlayerName = 'Interactive'
        self.possiblePlayers = {
            self.interractivePlayerName: -1,
        }
        for player_name in players.keys():
            self.possiblePlayers[player_name] = players[player_name]

        self.wrong_move = False
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = (ws / 2) - (self.w / 2)
        y = (hs / 2) - (self.h / 2)

        self.root.geometry('%dx%d+%d+%d' % (self.w, self.h, x, y))
        self.draw_game_grid()
        self.draw_game_info_grid()

        self.game_state = GameState.STOPPED

    def set_game(self, game):
        """
        Sets the game to the GUI.
        """
        self.game = game

    def set_board(self, board):
        """
        Sets the game board to the GUI.
        """
        self.board = board

    def draw_stone(self, x, y, color):
        """
        Draw stone on position [x,y] in gui
        :param x: x coordinate of the stone
        :param y: y coordinate of the stone
        :param color: 0 for blue, 1 fro red
        """
        x_coord = (self.gridspacing *
                   x) + (1.0 - self.ovalDiamPart) * self.gridspacing
        y_coord = (self.gridspacing *
                   y) + (1.0 - self.ovalDiamPart) * self.gridspacing
        diameter = self.ovalDiamPart * self.gridspacing
        self.clear_stone(x, y)
        self.stone_board[x][y] = self.grid.create_oval(x_coord,
                                                       y_coord,
                                                       x_coord + diameter,
                                                       y_coord + diameter,
                                                       fill=self.colors[color])

    def clear_stone(self, x, y):
        """
        Delete stone on position [x,y] from the gui
        :param x: x coordinate of the stone
        :param y: y coordinate of the stone
        """
        if self.stone_board[x][y] != -1:
            self.grid.delete(self.stone_board[x][y])
            self.stone_board[x][y] = -1

    def draw_game_info_grid(self):
        """
        Draw control and inform part of game to right side of the window.
        """
        self.info = Canvas(self.root,
                           height=self.h - self.gridh,
                           width=self.w - self.gridw)
        self.info.pack(side="left")

        label_stones = Label(self.info,
                             text="Current stones:",
                             font=("Helvetica", 10))
        label_stones.grid(row=1, column=0)
        label_max_time = Label(self.info,
                               text="Max time:",
                               font=("Helvetica", 10))
        label_max_time.grid(row=2, column=0)

        label_scale = Label(self.info,
                            text='Game speed [ms]:',
                            font=("Helvetica", 10),
                            foreground='black')
        label_scale.grid(row=5, column=0)

        helv36 = font.Font(family="helvetica", size=16, weight='bold')
        self.scale_var = IntVar()
        scale = Scale(self.info,
                      variable=self.scale_var,
                      command=self.sleep_time_change_handler,
                      from_=0,
                      to=1000,
                      resolution=10,
                      width="15",
                      orient=HORIZONTAL,
                      length="225")
        scale.set(200)
        scale.grid(row=5, column=1, columnspan=3)

        self.button = Button(self.info,
                             text="Play",
                             width="20",
                             height="2",
                             command=self.play_button_click_handler)
        self.button['font'] = helv36
        self.button.grid(row=6, column=0, columnspan=4)

        # labels for num stones, max time of move, etc
        self.label_player_stones = [-1, -1]
        self.label_player_max_time = [-1, -1]
        self.labels_inform = [-1, -1]
        self.labels_player_name = [-1, -1]
        self.option_menus = [-1, -1]
        self.option_menus_vars = [-1, -1]

        for i in range(2):
            self.label_player_stones[i] = Label(self.info,
                                                text='2',
                                                font=("Helvetica", 10),
                                                foreground=self.colors[i])
            self.label_player_stones[i].grid(row=1,
                                             column=2 * (i + 1) - 1,
                                             columnspan=2)

            self.label_player_max_time[i] = Label(self.info,
                                                  text="%.2f [ms]" % 0.0,
                                                  font=("Helvetica", 10),
                                                  foreground=self.colors[i])
            self.label_player_max_time[i].grid(row=2,
                                               column=2 * (i + 1) - 1,
                                               columnspan=2)

            self.labels_inform[i] = Label(self.info,
                                          text='',
                                          font=("Helvetica", 10),
                                          foreground='black')
            self.labels_inform[i].grid(row=i + 3, column=0, columnspan=4)

            self.labels_player_name[i] = Label(self.info,
                                               text="Player%d:" % (i),
                                               font=("Helvetica", 12),
                                               foreground=self.colors[i])
            self.labels_player_name[i].grid(row=0, column=2 * i)

            self.option_menus_vars[i] = StringVar(self.root)
            self.option_menus_vars[i].set(self.interractivePlayerName)
            self.option_menus[i] = OptionMenu(self.info,
                                              self.option_menus_vars[i],
                                              *self.possiblePlayers)
            self.option_menus[i].grid(row=0, column=2 * i + 1)

    def draw_game_grid(self):
        """
        Draw empty 8x8 grid on the left side of the window.
        """
        self.grid = Canvas(self.root,
                           bg="white",
                           height=self.gridh,
                           width=self.gridw)
        self.grid.bind("<Button 1>", self.place_stone_click_handler)
        gridsize = self.board_size
        offy = self.offy
        offx = self.offx
        w = self.gridw
        h = self.gridh
        spacing = self.gridspacing
        # line around
        self.grid.create_line(offx, offy, offx, h - offy, w - offx, h - offy,
                              w - offx, offy, offx, offx)

        for x in range(0, gridsize):
            for y in range(0, gridsize):
                array_text = '[' + str(y) + ',' + str(x) + ']'
                self.grid.create_text(offx + (spacing * x) + spacing / 2,
                                      offy + (spacing * y) + spacing / 2,
                                      text=array_text)
        # line rows
        for rowy in range(offy + spacing, h - offy, spacing):
            self.grid.create_line(offx, rowy, w - offx, rowy)

        # line columns
        for colx in range(offx + spacing, w - offx, spacing):
            self.grid.create_line(colx, offy, colx, h - offy)

        self.grid.pack(side="left")

    def sleep_time_change_handler(self, event):
        """
        Called after scale value change, updates the wait time between moves.
        :param event: slider change event
        """
        self.game.sleep_time_ms = self.scale_var.get()

    def play_button_click_handler(self):
        """
        Button listener for Play/Pause/RePlay etc.
        On button click prints slider value and start game.
        """

        # set the players from dropdown menu if game is stopped
        if self.game_state == GameState.STOPPED:
            print("game_state " + str(self.game_state))
            self.interactive_player_ids = []
            for i in range(2):
                print(self.option_menus_vars[i].get())
                if self.option_menus_vars[i].get(
                ) == self.interractivePlayerName:
                    self.interactive_player_ids.append(i)

                    if i == 0:
                        self.game.player1.name = self.interractivePlayerName
                    else:
                        self.game.player2.name = self.interractivePlayerName

                else:
                    if i == 0:
                        player_class = self.possiblePlayers[
                            self.option_menus_vars[i].get()]
                        self.game.player1 = player_class(
                            self.game.player1_color, self.game.player2_color)

                    else:
                        player_class = self.possiblePlayers[
                            self.option_menus_vars[i].get()]
                        self.game.player2 = player_class(
                            self.game.player2_color, self.game.player1_color)

                    self.game.clear_game()

            self.game.current_player = self.game.player1
            self.game.current_player_color = self.game.player1_color
            print('player1 ' + str(self.game.player1_color))
            print('player2 ' + str(self.game.player2_color))

        # play game or start game if interactive
        if len(self.interactive_player_ids) != 0:
            if self.game_state == GameState.STOPPED:
                print("revert this commented out section below")
                #if not self.board.can_play(self.game.current_player, self.game.current_player_color):
                #    self.game.clear_game()
                #    self.button['text'] = 'Play'
                #else:
                self.game_state = GameState.RUNNING
                self.button['text'] = 'RePlay'
                print('can play ', self.interactive_player_ids)
                inform_str = 'Player%d plays' % (
                    self.interactive_player_ids[0])
                self.inform(inform_str, 'green')
                if len(self.interactive_player_ids
                       ) == 1 and self.interactive_player_ids[0] == 1:
                    self.game.play_game(self.interactive_player_ids[0])

            else:
                self.game_state = GameState.STOPPED
                self.button['text'] = 'Play'
                self.game.clear_game()
                # self.game.play_game(self.interactivePlayerId)
        else:
            if self.game_state == GameState.STOPPED or self.game_state == GameState.PAUSED:
                print('start')
                print('player1 ' + str(self.game.player1_color))
                print('player2 ' + str(self.game.player2_color))
                self.button['text'] = 'Pause'
                self.game.sleepTimeMS = self.scale_var.get()
                if self.game_state == GameState.STOPPED:
                    self.game.clear_game()
                self.game.pause(False)
                self.game_state = GameState.RUNNING
                print('player1 ' + str(self.game.player1_color))
                print('player2 ' + str(self.game.player2_color))
                self.game.play_game()
                print('game exited')
                if self.board.can_play(self.game.current_player_color
                                       ) and not self.wrong_move:
                    print('set pause state')
                    self.button['text'] = 'Continue'
                    self.game_state = GameState.PAUSED
                else:
                    print('set stopped state')
                    self.button['text'] = 'RePlay'
                    self.game_state = GameState.STOPPED
                    # self.game.clear_game()

            elif self.game_state == GameState.RUNNING:
                print('pause')
                self.game_state = GameState.PAUSED
                self.game.pause(True)

    def print_score(self):
        """
        Set number of stones for both players.
        """
        stones = self.board.get_score()
        self.print_player_num_stones(0, stones[0])
        self.print_player_num_stones(1, stones[1])

    def print_num_stones(self, stones):
        """
        Set number of stones for both players.
        :param stones: array of player number of stones
        """
        self.print_player_num_stones(0, stones[0])
        self.print_player_num_stones(1, stones[1])

    def print_player_num_stones(self, playerID, stones):
        """
        Set player number of stones.
        :param playerID: 0 for player 1, 1 for player 2
        :param maxTime: maximal time of player
        """
        self.label_player_stones[playerID]['text'] = str(stones)
        self.root.update()

    def print_move_max_times(self, max_times_ms):
        """
        Print maximal times for both players to the gui.
        :param max_times_ms: array of max time needed for move.
        """
        self.print_player_move_max_time(0, max_times_ms[0])
        self.print_player_move_max_time(1, max_times_ms[1])

    def print_player_move_max_time(self, player_id, max_time):
        """
        Set player maximal time.
        :param player_id: 0 for player 1, 1 for player 2
        :param max_time: maximal time of player
        """
        self.label_player_max_time[player_id]['text'] = '%.2f [ms]' % max_time
        self.root.update()

    def print_board_state(self):
        """
        Show the state of the board in gui.
        """
        # self.board.print_board()
        for y in range(self.board.board_size):
            for x in range(self.board.board_size):
                if self.board.board[y][x] == -1:
                    self.clear_stone(x, y)
                else:
                    self.draw_stone(x, y, self.board.board[y][x])
        self.root.update()

    def place_stone_click_handler(self, event):
        """
        For interactive player places stone to mouse click position. 
        :param event: mouse click event
        """
        print("place_stone_click_handler")
        if self.game_state != GameState.STOPPED and\
                len(self.interactive_player_ids) >= 1 and\
                self.game.current_player_color in self.interactive_player_ids:
            pos_move = [
                int((event.y - self.offy) / self.gridspacing),
                int((event.x - self.offx) / self.gridspacing)
            ]

            if self.board.is_correct_move(pos_move,
                                          self.game.current_player_color):

                next_player_id = self.game.play_move(pos_move)
                self.print_board_state()
                self.print_score()
                self.print_move_max_times(self.game.max_times_ms)
                inform_str = 'Player%d plays' % (
                    self.game.current_player_color)
                self.inform(inform_str, 'green')
                if len(self.interactive_player_ids) == 1:
                    self.game.play_game(self.interactive_player_ids[0])

                if next_player_id == -1:
                    self.game_state = GameState.STOPPED
                    self.button['text'] = 'RePlay'
                    self.game.print_final_info()
            else:
                print('incorrect move', pos_move)
                self.inform(
                    'incorrect move to %d %d' % (pos_move[0], pos_move[1]),
                    'red')

    def inform(self, text_strs, color_str):
        """
        Show inform text in gui.
        :param text_strs: string or string array of size 2 that is shown in gui
        :param color_str: color of shown text_strs
        """
        inform_str_all = ['', '']
        if not isinstance(text_strs, list):
            inform_str_all[0] = text_strs
        else:
            inform_str_all = text_strs
        # print(inform_str_all)
        for i in range(2):
            self.labels_inform[i]['text'] = inform_str_all[i]
            self.labels_inform[i]['foreground'] = color_str
        self.root.update()
Example #35
0
    def __init__(self, master):

        self.fname = ""
        #global variables
        self.t1 = StringVar()
        self.t2 = StringVar()
        self.t3 = StringVar()
        self.t4 = StringVar()
        self.t5 = StringVar()
        self.t6 = StringVar()
        self.t7 = StringVar()
        self.t8 = StringVar()
        self.t9 = StringVar()
        self.t10 = StringVar()
        self.t11 = StringVar()
        self.t12 = StringVar()
        self.t13 = StringVar()
        self.t14 = StringVar()
        self.t15 = StringVar()
        self.t16 = StringVar()
        self.t17 = StringVar()
        self.t18 = StringVar()
        self.t19 = StringVar()
        self.t20 = StringVar()
        self.t21 = StringVar()
        self.t22 = StringVar()
        self.t23 = StringVar()
        self.t24 = StringVar()
        self.t25 = StringVar()
        self.t26 = StringVar()
        self.t27 = StringVar()

        self.var1 = StringVar()
        self.var2 = StringVar()
        self.var3 = StringVar()
        self.var4 = StringVar()
        self.var5 = StringVar()
        self.var6 = StringVar()
        self.var7 = StringVar()
        self.var8 = StringVar()
        self.var9 = StringVar()
        self.var10 = StringVar()
        self.var11 = StringVar()
        self.var12 = StringVar()
        self.var13 = StringVar()
        self.var14 = StringVar()
        self.var15 = StringVar()
        self.var16 = StringVar()
        self.var17 = StringVar()
        self.var18 = StringVar()
        self.var19 = StringVar()
        self.var20 = StringVar()
        self.var21 = StringVar()
        self.var22 = StringVar()
        self.var23 = StringVar()
        self.var24 = StringVar()
        self.var25 = StringVar()
        self.var26 = StringVar()
        self.var27 = StringVar()
        #end

        mymaster = Frame(master, name='mymaster')  # create Frame in "root"
        mymaster.pack(fill=BOTH)
        #min and max size of window
        #master.minsize(width=900, height=900)
        #master.maxsize(width=650, height=500)
        #end

        #title of window
        master.title("Aireplay-ng")
        #end

        #for the style of fonts
        self.customFont = tkFont.Font(family="Helvetica", size=12)
        self.myfont = tkFont.Font(family="Helvetica", size=10)
        self.myfont2 = tkFont.Font(family="Helvetica", size=8)
        self.headerfont = tkFont.Font(family="Helvetica",
                                      size=15,
                                      underline=True)
        self.myfontnew = tkFont.Font(family="Helvetica",
                                     size=11,
                                     underline=True)
        #end

        nb = Notebook(mymaster, name='nb')  # create Notebook in "master"
        nb.pack(fill=BOTH, padx=2, pady=3)  # fill "master" but pad sides
        #content frame
        self.frame_content = Frame(nb,
                                   name="frame_content",
                                   bg="lightsteelblue")
        self.frame_content.pack(fill=BOTH, side=TOP, expand=True)
        nb.add(self.frame_content, text="Filter-1")  # add tab to Notebook

        # repeat for each tab
        self.frame_content2 = Frame(nb,
                                    name='frame_content2',
                                    bg="lightsteelblue")
        nb.add(self.frame_content2, text="Filter-2")
        self.frame_content3 = Frame(nb,
                                    name='frame_content3',
                                    bg="lightsteelblue")
        nb.add(self.frame_content3, text="Filter-3")

        self.frame_content7 = Frame(nb,
                                    name='frame_content7',
                                    bg="lightsteelblue")
        nb.add(self.frame_content7, text="Detect Devices")
        self.frame_content5 = Frame(nb,
                                    name='frame_content5',
                                    bg="lightsteelblue")
        nb.add(self.frame_content5, text="output")

        #End

        #frame content 7
        Label(self.frame_content7,
              text='Aireplay-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        btndetect = Button(self.frame_content7,
                           text='Detect',
                           fg="cornflowerblue",
                           command=self.canvas_detect,
                           height=2,
                           width=15,
                           font=self.customFont).grid(row=1,
                                                      column=0,
                                                      padx=5,
                                                      pady=5)

        btndbrowse = Button(self.frame_content7,
                            text='Attach File',
                            fg="cornflowerblue",
                            command=self.browse_file,
                            height=2,
                            width=15,
                            font=self.customFont).grid(row=3,
                                                       column=0,
                                                       padx=5,
                                                       pady=5)
        self.lilnew1 = Listbox(self.frame_content7,
                               bg="black",
                               fg="firebrick",
                               font=self.myfont,
                               selectmode=SINGLE,
                               width=30,
                               height=15)
        self.lilnew1.grid(row=1, column=1, rowspan=3)
        #End

        Label(self.frame_content,
              text='Aireplay-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        Label(self.frame_content,
              text='Filter Options :',
              font=self.myfontnew,
              bg="midnightblue",
              fg="deepskyblue").grid(row=1, column=1)

        Label(self.frame_content5,
              text='Edit Command From Here',
              font=self.myfontnew,
              bg="midnightblue",
              fg="deepskyblue",
              justify=LEFT).grid(row=0, column=0)
        TextCommandBox = Text(self.frame_content5, height=5, width=30)
        TextCommandBox.grid(row=1, column=0, padx=5, pady=5)
        self.output = Text(self.frame_content5,
                           bg="black",
                           fg="firebrick",
                           font=self.myfont,
                           height=20,
                           width=42)
        self.output.grid(row=0, column=1, padx=50, pady=5, rowspan=3)
        btnsubmit = Button(self.frame_content5,
                           width=15,
                           height=2,
                           text="Get Result",
                           fg="cornflowerblue",
                           command=self.mycallback)
        btnsubmit.grid(row=2, column=0)
        btnclear = Button(self.frame_content5,
                          width=15,
                          height=2,
                          text="Clear Output",
                          fg="cornflowerblue",
                          command=self.clearoutput)
        btnclear.grid(row=3, column=0)
        #end
        self.C1 = Checkbutton(self.frame_content, text = "-b", fg="deepskyblue", \
                 onvalue = "-b", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var1)
        self.C1.grid(row=2, column=0, padx=5, pady=5)
        self.t1 = Text(self.frame_content, height=1, width=20)
        self.t1.grid(row=2, column=1, padx=5, pady=5)
        l1 = Label(self.frame_content,
                   text=': MAC address, Access Point',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=2, column=2, padx=5, pady=5)

        self.C2 = Checkbutton(self.frame_content, text = "-d", fg="deepskyblue", \
                 onvalue = "-d", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var2)
        self.C2.grid(row=3, column=0, padx=5, pady=5)
        self.t2 = Text(self.frame_content, height=1, width=20)
        self.t2.grid(row=3, column=1, padx=5, pady=5)
        l2 = Label(self.frame_content,
                   text=': MAC address, Destination',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=3, column=2, padx=5, pady=5)

        self.C3 = Checkbutton(self.frame_content, text = "-s", fg="deepskyblue", \
                 onvalue = "-s", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var3)
        self.C3.grid(row=4, column=0, padx=5, pady=5)
        self.t3 = Text(self.frame_content, height=1, width=20)
        self.t3.grid(row=4, column=1, padx=5, pady=5)
        l3 = Label(self.frame_content,
                   text=': MAC address, Source',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=4, column=2, padx=5, pady=5)

        self.C4 = Checkbutton(self.frame_content, text = "-m", fg="deepskyblue", \
                 onvalue = "-m", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var4)
        self.C4.grid(row=5, column=0, padx=5, pady=5)
        self.t4 = Text(self.frame_content, height=1, width=20)
        self.t4.grid(row=5, column=1, padx=5, pady=5)
        l4 = Label(self.frame_content,
                   text=': minimum packet length',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=5, column=2, padx=5, pady=5)

        self.C5 = Checkbutton(self.frame_content, text = "-n", fg="deepskyblue", \
                 onvalue = "-n", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var5)
        self.C5.grid(row=6, column=0, padx=5, pady=5)
        self.t5 = Text(self.frame_content, height=1, width=20)
        self.t5.grid(row=6, column=1, padx=5, pady=5)
        l5 = Label(self.frame_content,
                   text=': maximum packet length',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=6, column=2, padx=5, pady=5)

        self.C6 = Checkbutton(self.frame_content, text = "-u", fg="deepskyblue", \
                 onvalue = "-u", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var6)
        self.C6.grid(row=7, column=0, padx=5, pady=5)
        self.t6 = Text(self.frame_content, height=1, width=20)
        self.t6.grid(row=7, column=1, padx=5, pady=5)
        l6 = Label(self.frame_content,
                   text=': frame control, type field',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=7, column=2, padx=5, pady=5)

        self.C7 = Checkbutton(self.frame_content, text = "-v", fg="deepskyblue", \
                 onvalue = "-v", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var7)
        self.C7.grid(row=8, column=0, padx=5, pady=5)
        self.t7 = Text(self.frame_content, height=1, width=20)
        self.t7.grid(row=8, column=1, padx=5, pady=5)
        l7 = Label(self.frame_content,
                   text=': frame control, subtype field',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=8, column=2, padx=5, pady=5)

        self.C8 = Checkbutton(self.frame_content, text = "-t", fg="deepskyblue", \
                 onvalue = "-t", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var8)
        self.C8.grid(row=9, column=0, padx=5, pady=5)
        self.t8 = Text(self.frame_content, height=1, width=20)
        self.t8.grid(row=9, column=1, padx=5, pady=5)
        l8 = Label(self.frame_content,
                   text=':  frame control, To DS bit',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=9, column=2, padx=5, pady=5)

        self.C9 = Checkbutton(self.frame_content, text = "-r", fg="deepskyblue", \
                 onvalue = "-r", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var9)
        self.C9.grid(row=10, column=0, padx=5, pady=5)
        self.t9 = Text(self.frame_content, height=1, width=20)
        self.t9.grid(row=10, column=1, padx=5, pady=5)
        l9 = Label(self.frame_content,
                   text=': frame control, From DS bit',
                   font=self.myfont,
                   bg="midnightblue",
                   fg="deepskyblue",
                   justify=LEFT).grid(row=10, column=2, padx=5, pady=5)

        self.C10 = Checkbutton(self.frame_content, text = "-w", fg="deepskyblue", \
                 onvalue = "-w", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var10)
        self.C10.grid(row=11, column=0, padx=5, pady=5)
        self.t10 = Text(self.frame_content, height=1, width=20)
        self.t10.grid(row=11, column=1, padx=5, pady=5)
        l10 = Label(self.frame_content,
                    text=': frame control, WEP bit',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=11, column=2, padx=5, pady=5)

        Label(self.frame_content2,
              text='Aireplay-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)

        #frame content 2
        self.C11 = Checkbutton(self.frame_content2, text = "-x", fg="deepskyblue", \
                 onvalue = "-x", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var11)
        self.C11.grid(row=12, column=0, padx=5, pady=5)
        self.t11 = Text(self.frame_content2, height=1, width=20)
        self.t11.grid(row=12, column=1, padx=5, pady=5)
        l11 = Label(self.frame_content2,
                    text=': number of packets per second',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=12, column=2, padx=5, pady=5)

        self.C12 = Checkbutton(self.frame_content2, text = "-p", fg="deepskyblue", \
                 onvalue = "-p", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var12)
        self.C12.grid(row=13, column=0, padx=5, pady=5)
        self.t12 = Text(self.frame_content2, height=1, width=20)
        self.t12.grid(row=13, column=1, padx=5, pady=5)
        l12 = Label(self.frame_content2,
                    text=': set frame control word (hex)',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=13, column=2, padx=5, pady=5)

        self.C13 = Checkbutton(self.frame_content2, text = "-a", fg="deepskyblue", \
                 onvalue = "-a", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var13)
        self.C13.grid(row=14, column=0, padx=5, pady=5)
        self.t13 = Text(self.frame_content2, height=1, width=20)
        self.t13.grid(row=14, column=1, padx=5, pady=5)
        l13 = Label(self.frame_content2,
                    text=': set Access Point MAC address',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=14, column=2, padx=5, pady=5)

        self.C14 = Checkbutton(self.frame_content2, text = "-c", fg="deepskyblue", \
                 onvalue = "-c", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var14)
        self.C14.grid(row=15, column=0, padx=5, pady=5)
        self.t14 = Text(self.frame_content2, height=1, width=20)
        self.t14.grid(row=15, column=1, padx=5, pady=5)
        l14 = Label(self.frame_content2,
                    text=':  set Destination MAC address',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=15, column=2, padx=5, pady=5)

        self.C15 = Checkbutton(self.frame_content2, text = "-h", fg="deepskyblue", \
                 onvalue = "-h", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var15)
        self.C15.grid(row=16, column=0, padx=5, pady=5)
        self.t15 = Text(self.frame_content2, height=1, width=20)
        self.t15.grid(row=16, column=1, padx=5, pady=5)
        l15 = Label(self.frame_content2,
                    text=': set Source MAC address',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue").grid(row=16, column=2, padx=5, pady=5)

        self.C16 = Checkbutton(self.frame_content2, text = "-e", fg="deepskyblue", \
                 onvalue = "-e", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var16)
        self.C16.grid(row=17, column=0, padx=5, pady=5)
        self.t16 = Text(self.frame_content2, height=1, width=20)
        self.t16.grid(row=17, column=1, padx=5, pady=5)
        l16 = Label(self.frame_content2,
                    text=':  For fakeauth attack or injection test,',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue").grid(row=17, column=2, padx=5, pady=5)

        self.C17 = Checkbutton(self.frame_content2, text = "-j", fg="deepskyblue", \
                 onvalue = "-j", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var17)
        self.C17.grid(row=18, column=0, padx=5, pady=5)
        self.t17 = Text(self.frame_content2, height=1, width=20)
        self.t17.grid(row=18, column=1, padx=5, pady=5)
        l17 = Label(self.frame_content2,
                    text=': arpreplay attack : inject FromDS pkts',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue").grid(row=18, column=2, padx=5, pady=5)

        self.C18 = Checkbutton(self.frame_content2, text = "-g", fg="deepskyblue", \
                 onvalue = "-g", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var18)
        self.C18.grid(row=19, column=0, padx=5, pady=5)
        self.t18 = Text(self.frame_content2, height=1, width=20)
        self.t18.grid(row=19, column=1, padx=5, pady=5)
        l18 = Label(self.frame_content2,
                    text=': change ring buffer size (default: 8)',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue").grid(row=19, column=2, padx=5, pady=5)

        self.C19 = Checkbutton(self.frame_content2, text = "-k", fg="deepskyblue", \
                 onvalue = "-k", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var19)
        self.C19.grid(row=20, column=0, padx=5, pady=5)
        self.t19 = Text(self.frame_content2, height=1, width=20)
        self.t19.grid(row=20, column=1, padx=5, pady=5)
        l19 = Label(self.frame_content2,
                    text=': set destination IP in fragments',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue").grid(row=20, column=2, padx=5, pady=5)

        self.C20 = Checkbutton(self.frame_content2, text = "-I", fg="deepskyblue", \
                 onvalue = "-I", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var20)
        self.C20.grid(row=21, column=0, padx=5, pady=5)
        self.t20 = Text(self.frame_content2, height=1, width=20)
        self.t20.grid(row=21, column=1, padx=5, pady=5)
        l20 = Label(self.frame_content2,
                    text=': set source IP in fragments',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue").grid(row=21, column=2, padx=5, pady=5)
        #frame content 3
        Label(self.frame_content3,
              text='Aireplay-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)


        self.C21 = Checkbutton(self.frame_content3, text = "-o", fg="deepskyblue", \
                 onvalue = "-o", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var21)
        self.C21.grid(row=22, column=0, padx=5, pady=5)
        self.t21 = Text(self.frame_content3, height=1, width=20)
        self.t21.grid(row=22, column=1, padx=5, pady=5)
        l21 = Label(self.frame_content3,
                    text=': number of packets per burst (-1)',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=22, column=2, padx=5, pady=5)

        self.C22 = Checkbutton(self.frame_content3, text = "-q", fg="deepskyblue", \
                 onvalue = "-q", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var22)
        self.C22.grid(row=24, column=0, padx=5, pady=5)
        self.t22 = Text(self.frame_content3, height=1, width=20)
        self.t22.grid(row=24, column=1, padx=5, pady=5)
        l22 = Label(self.frame_content3,
                    text=': seconds between keep-alives (-1)',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=24, column=2, padx=5, pady=5)

        self.C23 = Checkbutton(self.frame_content3, text = "-y", fg="deepskyblue", \
                 onvalue = "-y", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var23)
        self.C23.grid(row=25, column=0, padx=5, pady=5)
        self.t23 = Text(self.frame_content3, height=1, width=20)
        self.t23.grid(row=25, column=1, padx=5, pady=5)
        l23 = Label(self.frame_content3,
                    text=':  keystream for shared key auth',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=25, column=2, padx=5, pady=5)


        self.C24 = Checkbutton(self.frame_content3, text = "-B", fg="deepskyblue", \
                 onvalue = "-B", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var24)
        self.C24.grid(row=26, column=0, padx=5, pady=5)
        self.t24 = Text(self.frame_content3, height=1, width=20)
        self.t24.grid(row=26, column=1, padx=5, pady=5)
        l14 = Label(self.frame_content3,
                    text=': bit rate test (Applies only to test mode)',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=26, column=2, padx=5, pady=5)

        self.C25 = Checkbutton(self.frame_content3, text = "-D", fg="deepskyblue", \
                 onvalue = "-D", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var25)
        self.C25.grid(row=27, column=0, padx=5, pady=5)
        self.t25 = Text(self.frame_content3, height=1, width=20)
        self.t25.grid(row=27, column=1, padx=5, pady=5)
        l25 = Label(self.frame_content3,
                    text=': disables AP detection.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=27, column=2, padx=5, pady=5)

        self.C26 = Checkbutton(self.frame_content3, text = "-F", fg="deepskyblue", \
                 onvalue = "-F", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var26)
        self.C26.grid(row=28, column=0, padx=5, pady=5)
        self.t26 = Text(self.frame_content3, height=1, width=20)
        self.t26.grid(row=28, column=1, padx=5, pady=5)
        l26 = Label(self.frame_content3,
                    text=': chooses first matching packet.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=28, column=2, padx=5, pady=5)

        self.C27 = Checkbutton(self.frame_content3, text = "-R", fg="deepskyblue", \
                 onvalue = "-R", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var27)
        self.C27.grid(row=29, column=0, padx=5, pady=5)
        self.t27 = Text(self.frame_content3, height=1, width=20)
        self.t27.grid(row=29, column=1, padx=5, pady=5)
        l27 = Label(self.frame_content3,
                    text=': disables /dev/rtc usage.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=29, column=2, padx=5, pady=5)
Example #36
0
class VentanaFinal:
    def __init__(self, maestro, tiempo_ahora, directorio):
        self.carpeta = directorio
        months = ("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
                  "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre",
                  "Diciembre")
        month = months[tiempo_ahora.month - 1]
        self.tiempo = tiempo_ahora.strftime('%H.%M')
        self.fecha = "{}{}{}".format(tiempo_ahora.day, month,
                                     tiempo_ahora.year)

        self.top2 = tkToplevel(maestro)
        self.top2.title('Seleccione una pestaña')
        self.top2.geometry("+80+60")
        self.top2.protocol("WM_DELETE_WINDOW", self.cerrar)
        #self.top2.iconbitmap('/home/pi/Desktop/ProgGUI/GUI/resources/ICO/IconoBCT.ico')

        # Inicialización del objeto para el envio del correo
        self.operacion = ''
        self.mailto = sentmail()

        #MARCO3 ESEL LINEZO DONDE SE DIBUJAN LAS PESTAÑAS
        self.marco3 = TTK.Notebook(self.top2)

        # CREAMOS EL MARCO PARA CADA UNA DE LAS PESTAÑAS
        self.page1 = TTK.Frame(self.marco3)
        self.page2 = TTK.Frame(self.marco3)

        # AGREGAMOS EL MARCO A LAS PESTAÑAS Y SU NOMBRE
        self.marco3.add(self.page1, text='Enviar por correo electrónico')
        self.marco3.add(self.page2, text='Guardar / Imprimir / Ver PDF')
        self.marco3.grid()

        # CONTENIDO DE LA PESTAÑA self.page1
        #        self.combo = TTK.Combobox(self.page1, state="readonly", font =('Helvetica'), text = 'Hola', command )
        #        self.combo["values"] = ["Python", "C", "C++", "Java"]
        #        self.combo.grid(row = 0, column = 0)

        self.txtLB = 'Por favor ingrese el correo donde desea recibir el reporte'
        self.state = TTK.Label(self.page1,
                               font=('Helvetica', 15),
                               text=self.txtLB)
        self.state.grid(row=0, column=0, columnspan=11)

        botonQ = self.crearBoton('q')
        botonW = self.crearBoton('w')
        botonE = self.crearBoton('e')
        botonR = self.crearBoton('r')
        botonT = self.crearBoton('t')
        botonY = self.crearBoton('y')
        botonU = self.crearBoton('u')
        botonI = self.crearBoton('i')
        botonO = self.crearBoton('o')
        botonP = self.crearBoton('p')
        botonA = self.crearBoton('a')
        botonS = self.crearBoton('s')
        botonD = self.crearBoton('d')
        botonF = self.crearBoton('f')
        botonG = self.crearBoton('g')
        botonH = self.crearBoton('h')
        botonJ = self.crearBoton('j')
        botonK = self.crearBoton('k')
        botonL = self.crearBoton('l')
        botonNN = self.crearBoton('ñ')
        botonZ = self.crearBoton('z')
        botonX = self.crearBoton('x')
        botonC = self.crearBoton('c')
        botonV = self.crearBoton('v')
        botonB = self.crearBoton('b')
        botonN = self.crearBoton('n')
        botonM = self.crearBoton('m')
        botondot = self.crearBoton('.')
        botonguion = self.crearBoton('-')
        botonguionb = self.crearBoton('_')
        botonErase = self.crearBoton(u"\u232B", escribir=False)
        botonErase['background'] = "red"
        botonErase.grid(row=3, column=11)
        botonEnter = self.crearBoton(u"\u21B5", escribir=False, alto=2)
        botonEnter['background'] = "green"
        botonEnter.grid(row=1, column=11, rowspan=2, sticky='s')

        #Ubicación de los botones
        botones = [
            botonQ, botonW, botonE, botonR, botonT, botonY, botonU, botonI,
            botonO, botonP, botonA, botonS, botonD, botonF, botonG, botonH,
            botonJ, botonK, botonL, botonNN, botonZ, botonX, botonC, botonV,
            botonB, botonN, botonM, botondot, botonguion, botonguionb
        ]
        contador = 0
        for fila in range(1, 4):
            for columna in range(10):
                botones[contador].grid(row=fila, column=columna)
                contador += 1

        self.CBdata = tkText(self.page1,
                             state="disabled",
                             width=60,
                             height=1,
                             font=("Helvetica", 15))
        self.CBdata.grid(row=4, column=0, columnspan=12, sticky='w')

        archimex = TTK.Label(self.page1,
                             font=('Helvetica', 15),
                             text='@archimex.com.mx')
        archimex.grid(row=4, column=8, columnspan=4, sticky='w')

        # CONTENIDO DE LA PESTAÑA self.page2
        self.txtLB2 = 'Seleccione un botón de la acción que desea realizar'
        self.state2 = TTK.Label(self.page2,
                                font=('Helvetica', 15),
                                text=self.txtLB2)
        self.state2.grid(row=0, column=0, columnspan=5)

        self.txtLB2 = 'Guardar archivo en\nuna carpeta específica'
        self.save = BT(self.page2,
                       text=self.txtLB2,
                       font=("Helvetica", 15),
                       command=self.carpetaselec)
        self.save.grid(row=1, column=0)

        self.txtLB2 = 'Ver Archivo\nPDF'
        self.view = BT(self.page2,
                       text=self.txtLB2,
                       font=("Helvetica", 15),
                       command=self.ver_PDF)
        self.view.grid(row=1, column=2)

        self.txtLB2 = 'Imprimir\nreporte'
        self.prPDF = BT(self.page2,
                        text=self.txtLB2,
                        font=("Helvetica", 15),
                        command=self.imprime)
        self.prPDF.grid(row=1, column=4)

    def imprime(self):
        self.top2.iconify()
        # CAMBIAR DIRECTORIO
        answ = tkMessageBox.askyesno(
            "Atención",
            "El archivo se enviará a la impresora ubicada en calidad, ¿Está seguro de continuar?"
        )
        if answ == True:
            #commands.getoutput('lp -d impresora_calidad {}'.format(self.carpeta))
            print 'lp -d impresora_calidad {}'.format(self.carpeta)
        self.top2.deiconify()

    def ver_PDF(self):
        self.top2.iconify()
        commands.getoutput('qpdfview {}'.format(self.carpeta))
        self.top2.deiconify()

    def carpetaselec(self):
        self.top2.iconify()
        directorio = filedialog.askdirectory()
        #docPDF
        if directorio != "":
            self.state2['text'] = 'Seleccionó el directorio ' + directorio
            comando = 'cp {} {}/BCT_informe_{}_{}.pdf'.format(
                self.carpeta, directorio, self.fecha, self.tiempo)
            commands.getoutput(comando)
            print(comando)
        self.top2.deiconify()

    def crearBoton(self, valor, escribir=True, ancho=5, alto=1):
        return BT(self.page1,
                  text=valor,
                  width=ancho,
                  height=alto,
                  font=("Helvetica", 15),
                  command=lambda: self.click(valor, escribir))

    #Controla el evento disparado al hacer click en un botón
    def click(self, texto, escribir):
        #Si el parámetro 'escribir' es True, entonces el parámetro texto debe mostrarse en pantalla. Si es False, no.
        if not escribir:
            #Sólo calcular si hay una operación a ser evaluada y si el usuario presionó '='
            if texto == u"\u21B5" and self.operacion != "":
                correo = str(self.operacion) + '@archimex.com.mx'
                self.mailto.destino(correo)
                self.state['text'] = 'Correo ingresado ' + correo
                self.top2.iconify()
                answ = tkMessageBox.askyesno(
                    "Atención", "Se ingreso el correo " + correo +
                    ", ¿Es correcto el correo ingresado?")
                if answ == True:
                    self.mailto.sent(self.carpeta)
                    self.top2.deiconify()
                    self.state[
                        'text'] = 'Correo enviado correctamente a ' + correo
                print 'Hola desde borrar'
                self.operacion = ''
                self.limpiarPantalla()
            elif texto == u"\u232B":
                self.operacion = ""
                self.limpiarPantalla()
        #Mostrar texto
        else:
            self.operacion += str(texto)
            self.mostrarEnPantalla(texto)
        return

    #Borra el contenido de la pantalla de la calculadora
    def limpiarPantalla(self):
        self.CBdata.configure(state="normal")
        self.CBdata.delete("1.0", tkEND)
        self.CBdata.configure(state="disabled")
        return

    #Muestra en la pantalla de la calculadora el contenido de las operaciones y los resultados
    def mostrarEnPantalla(self, valor):
        self.CBdata.configure(state="normal")
        self.CBdata.insert(tkEND, valor)
        self.CBdata.configure(state="disabled")
        return

    def SaveObj(self, obj):
        self.obj = obj

    def cerrar(self):
        self.top2.iconify()
        respuesta = tkMessageBox.askyesno(
            "Precaución",
            "Usted esta a punto de salir, ¿Desea realizar otra prueba de BCT?. Si selecciona No, se cerrará la ventana"
        )
        if respuesta == True:
            self.obj(False)
            self.top2.destroy()
        else:
            self.top2.quit()
        try:
            self.top2.deiconify()
        except:
            print "Ventana cerrada"


#ventana = TK()
#final = VentanaFinal(ventana)
#ventana.mainloop()
Example #37
0
def open_recipe():

    global Box
    global ingBox
    name = Box.get(ACTIVE)
    protocol_file = name + "protocol"
    '''File=open(protocol_file)
    text=File.read()
    File.close()'''
    openwindow = Tk()
    btn = Button(openwindow, text="save to your computer")
    btn.grid(row=0, column=0)
    label = Label(openwindow, text="Name")
    label.grid(row=1, column=0)
    label1 = Label(openwindow, text="Ingredients")
    label2 = Label(openwindow, text="Preparation Time")
    label3 = Label(openwindow, text="serves:")
    label4 = Label(openwindow, text="Instructions")
    cookit = Button(openwindow, text="cook", command=cook)
    absent = Button(openwindow, text="need to buy", command=go_shopping)
    label1.grid(row=2, column=0)
    label2.grid(row=3, column=0)
    label3.grid(row=4, column=0)
    label4.grid(row=5, column=0)
    cookit.grid(row=6, column=0)
    absent.grid(row=7, column=0)
    box = Text(openwindow, height="1")

    ingBox = Listbox(openwindow, width="107", height="15")

    timeBox = Text(openwindow, height="1")

    serves = Text(openwindow, height="1")

    ins = Text(openwindow, height="10")

    listt = []
    cn = ""
    f = open(protocol_file).readlines()
    nodestart = False
    for i in range(len(f)):
        if "#" in f[i]:
            nodestart = False
            listt.append(cn)
            cn = ""
        if nodestart:
            cn = cn + f[i]
        if "@" in f[i]:
            nodestart = True
    Name = listt[0]
    list_ingred = listt[1].split("\n")
    prepTime = listt[4]
    People = listt[3]
    Instructions = listt[2]
    for k in range(len(Name)):

        box.insert(END, Name[k])

    box.grid(row=1, column=1)

    for q in range(len(list_ingred)):

        ingBox.insert(END, list_ingred[q])

    ingBox.grid(row=2, column=1)

    for w in range(len(prepTime)):

        timeBox.insert(END, prepTime[w])
    timeBox.grid(row=3, column=1)

    for x in range(len(People)):

        serves.insert(END, People[x])

    serves.grid(row=4, column=1)

    for y in range(len(Instructions)):

        ins.insert(END, Instructions[y])

    ins.grid(row=5, column=1)

    openwindow.mainloop()
Example #38
0
class SigBridgeUI(Tk):
    server = None
    server_thread = None

    def __init__(self):
        Tk.__init__(self)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # 2 rows: firts with settings, second with registrar data
        self.main_frame = Frame(self)
        # Commands row doesn't expands
        self.main_frame.rowconfigure(0, weight=0)
        # Logs row will grow
        self.main_frame.rowconfigure(1, weight=1)
        # Main frame can enlarge
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.columnconfigure(1, weight=1)
        self.main_frame.grid(row=0, column=0)

        # Run/Stop button
        self.server_button = Button(self.main_frame,
                                    text="Connect",
                                    command=self.start_server)
        self.server_button.grid(row=0, column=0)

        # Clear button
        self.clear_button = Button(self.main_frame,
                                   text="Clear Log",
                                   command=self.clear_log)
        self.clear_button.grid(row=0, column=1)

        # Logs Widget
        self.log_widget = ScrolledText(self.main_frame)
        self.log_widget.grid(row=1, column=0, columnspan=2)
        # made not editable
        self.log_widget.config(state='disabled')

        # Queue where the logging handler will write
        self.log_queue = Queue.Queue()

        # Setup the logger
        self.uilogger = logging.getLogger('SigBridgeUI')
        self.uilogger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

        # Use the QueueLogger as Handler
        hl = QueueLogger(queue=self.log_queue)
        hl.setFormatter(formatter)
        self.uilogger.addHandler(hl)

        # self.log_widget.update_idletasks()
        self.set_geometry()

        # Setup the update_widget callback reading logs from the queue
        self.start_log()

        # Start server automatically
        self.start_server()

    def clear_log(self):
        self.log_widget.config(state='normal')
        self.log_widget.delete(0.0, END)
        self.log_widget.config(state='disabled')

    def start_log(self):
        # self.uilogger.info("SigBridge Started.")
        self.update_widget()
        # self.control_log_button.configure(text="Pause Log", command=self.stop_log)

    def update_widget(self):
        self.log_widget.config(state='normal')
        # Read from the Queue and add to the log widger
        while not self.log_queue.empty():
            line = self.log_queue.get()
            tag = "error" if " ERROR " in line else 'info'
            self.log_widget.insert(END, line, tag)
            self.log_widget.see(END)  # Scroll to the bottom
            self.log_widget.update_idletasks()
        self.log_widget.tag_config('error', foreground="red")
        self.log_widget.config(state='disabled')
        self.log_widget.after(10, self.update_widget)

    def set_geometry(self):
        # set position in window
        w = 600  # width for the Tk
        h = 300  # height for the Tk

        # get screen width and height
        ws = self.winfo_screenwidth()  # width of the screen
        hs = self.winfo_screenheight()  # height of the screen

        # calculate x and y coordinates for the Tk window
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)

        # set the dimensions of the screen
        # and where it is placed
        self.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def start_server(self):
        try:
            self.server = SigServer(('0.0.0.0', 25), None, self.uilogger)
            self.server_thread = threading.Thread(name='server',
                                                  target=self.server.run)
            self.server_thread.daemon = True
            self.server_thread.start()
            self.server_button.configure(text="Disconnect",
                                         command=self.stop_server)
        except Exception as err:
            self.uilogger.error("Cannot start the server: %s" % err.message)

        # self.label_variable.set(self.entry_variable.get()+"(Started Signal Server)")
        # self.entry.focus_set()
        # self.entry.selection_range(0, END)

    def stop_server(self):
        self.server.shutdown()
        self.server_button.configure(text="Connect", command=self.start_server)
        self.server = None
Example #39
0
    figure = plt.figure(dpi=150, figsize=(4, 4))
    ax = figure.add_subplot(111)
    ax.plot(range(10), [math.sin(x) for x in range(10)])
    #tz = figure.text(0.5,0.975,'The master title',horizontalalignment='center', verticalalignment='top')
    tz = figure.suptitle('The master title')

    ax.set_title('Tk embedding')
    ax.set_xlabel('X axis label')
    ax.set_ylabel('Y label')
    print(tz.get_fontsize())  # 12.0
    print(ax.title.get_fontsize(), ax.xaxis.label.get_fontsize(),
          ax.yaxis.label.get_fontsize())  # 14.4 12.0 12.0

    addScrollingFigure(figure, frame)

    buttonFrame = Frame(root)
    buttonFrame.grid(row=1, column=2, sticky=Tkconstants.NS)
    biggerButton = Button(buttonFrame,
                          text="larger",
                          command=lambda: changeSize(figure, 1.2))
    biggerButton.grid(column=1, row=1)
    smallerButton = Button(buttonFrame,
                           text="smaller",
                           command=lambda: changeSize(figure, 0.833))
    smallerButton.grid(column=1, row=2)
    qButton = Button(buttonFrame, text="quit", command=lambda: sys.exit(0))
    qButton.grid(column=1, row=3)

    root.mainloop()
Example #40
0
class App(object):
    def __init__(self, root, cursor, db):
        self.frame = Frame(root)
        self.frame.configure(background='white')
        self.list_toplevel = {}
        self.cursor = cursor
        self.db = db
        self.child_toplevel = None
        self.frame.pack()
        image = Image.open("photo.jpg")
        image = image.resize((250, 250), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        label = Label(self.frame, image=photo)
        label.grid(row=0, column=0, sticky=W)
        label.image = photo  # keep a reference!
        nou_registre = LabelFrame(self.frame,
                                  text="Nou registre",
                                  fg="Blue",
                                  padx=5,
                                  pady=5)
        nou_registre.configure(background='white')
        nou_registre.grid(row=0, column=1, padx=15, sticky=W)

        text_nom = Label(nou_registre, text="Nom:", fg="Blue")
        text_nom.configure(background='white')
        text_nom.grid(row=0, column=0)
        self.entry_nom = Entry(nou_registre)
        self.entry_nom.grid(row=0, column=1, sticky=W)

        text_telefon = Label(nou_registre, text="Telèfon: ", fg="Blue")
        text_telefon.configure(background='white')
        text_telefon.grid(row=1, column=0)
        self.entry_telefon = Entry(nou_registre)
        self.entry_telefon.grid(row=1, column=1)

        text_email = Label(nou_registre, text="Email: ", fg="Blue")
        text_email.configure(background='white')
        text_email.grid(row=2, column=0)
        self.entry_email = Entry(nou_registre)
        self.entry_email.grid(row=2, column=1)

        button_afegir_contacte = Button(nou_registre,
                                        text="Afegir contacte",
                                        fg="Blue",
                                        command=self.afegeix_contacte)
        button_afegir_contacte.grid(row=3, column=1, sticky=E)

        button_mostra_historic = Button(nou_registre,
                                        text="Mostra historic",
                                        fg="Blue",
                                        command=self.mostra_historic)
        button_mostra_historic.grid(row=4, column=0, sticky=W)

        mostrar_contactes = Button(self.frame,
                                   text="Mostrar contactes",
                                   fg="Blue",
                                   command=self.insert_contacts_treeview)
        mostrar_contactes.grid(sticky=W, row=3)

        self.missatge_error_confirmacio = StringVar()

        self.label_error_confirmacio = Label(
            self.frame, textvariable=self.missatge_error_confirmacio, fg="Red")
        self.label_error_confirmacio.configure(background='white')
        self.label_error_confirmacio.grid(sticky=W, row=3, column=1)

        self.agenda_contactes = Treeview(self.frame,
                                         columns=["nom", "tel"],
                                         show="headings")
        self.agenda_contactes.heading("nom", text="Nom")
        self.agenda_contactes.heading("tel", text="Telefon")
        self.agenda_contactes.column("nom",
                                     minwidth=0,
                                     width=200,
                                     stretch=NO,
                                     anchor="c")
        self.agenda_contactes.column("tel",
                                     minwidth=0,
                                     width=200,
                                     stretch=NO,
                                     anchor="c")
        self.agenda_contactes.grid(row=4, column=0, padx=0, columnspan=2)

        self.insert_contacts_treeview()
        elimina_seleccionat = Button(self.frame,
                                     text="Eliminar seleccionat",
                                     command=self.elimina_contacte,
                                     fg="Blue")
        elimina_seleccionat.grid(row=5, column=0, sticky=W)

        self.modificar_seleccionat = Button(self.frame,
                                            text="Modificar seleccionat",
                                            fg="Blue",
                                            command=self.modifica_contacte)
        self.modificar_seleccionat.grid(row=5, column=1, sticky=W)
        sortir = Button(self.frame,
                        text="Sortir",
                        fg="Blue",
                        command=self.frame.quit)
        sortir.grid(row=5, column=2, sticky=E)

    def mostra_historic(self):
        popup = Toplevel()
        agenda_historic = Treeview(
            popup,
            columns=["nom", "tel", "email", "path", "accio", "data"],
            show="headings")
        agenda_historic.heading("nom", text="Nom")
        agenda_historic.heading("tel", text="Telefon")
        agenda_historic.heading("email", text="Email")
        agenda_historic.heading("path", text="Path")
        agenda_historic.heading("accio", text="Acció")
        agenda_historic.heading("data", text="Data")
        agenda_historic.column("nom",
                               minwidth=0,
                               width=150,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("tel",
                               minwidth=0,
                               width=100,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("email",
                               minwidth=0,
                               width=150,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("path",
                               minwidth=0,
                               width=200,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("accio",
                               minwidth=0,
                               width=100,
                               stretch=True,
                               anchor="c")
        agenda_historic.column("data",
                               minwidth=0,
                               width=150,
                               stretch=True,
                               anchor="c")
        agenda_historic.grid(row=0, column=0, padx=5, pady=5)
        self.cursor.execute("select * from HISTORIC ORDER BY data DESC;")
        dades = self.cursor.fetchall()
        for data_usuari in dades:
            agenda_historic.insert('', 'end', values=data_usuari)

    def insert_contacts_treeview(self):
        self.cursor.execute("select * from CONTACTES order by nom ASC;")
        self.agenda_contactes.delete(*self.agenda_contactes.get_children())
        for i in self.cursor.fetchall():
            self.agenda_contactes.insert('', 'end', values=i[:2])

    def show_image(self, imatge_label, path_imatge=''):
        file_per_default = 'avatar.jpeg'
        if path_imatge == '':

            image = Image.open(file_per_default)
        else:
            if os.path.exists(path_imatge):
                try:
                    image = Image.open(path_imatge)
                except:
                    print "Error al mostrar imatge!"
                    return False
            else:
                image = Image.open(file_per_default)

        image = image.resize((120, 120), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        imatge_label.configure(image=photo)
        imatge_label.image = photo
        return True

    def edit_image(self, imatge_label, path_imatge, nom, telefon):
        if os.path.isfile(path_imatge):
            try:
                image = Image.open(path_imatge)
            except:
                self.missatge_error_confirmacio.set("Imatge incorrecte!")

            else:
                try:
                    self.cursor.execute(
                        "UPDATE CONTACTES SET foto=:pathfoto where nom=:nom and telf=:telf",
                        {
                            'pathfoto': path_imatge,
                            'nom': nom,
                            'telf': str(telefon)
                        })
                    self.db.commit()
                except:
                    self.missatge_error_confirmacio.set(
                        "Error actualitzant la imatge!")
                    return False

        self.show_image(imatge_label, path_imatge)

    def demana_imatge(self, imatge_label, nom, telefon):
        t = tkFileDialog.askopenfilename(title="Selecciona foto",
                                         filetypes=(("jpg files", "*.jpg"),
                                                    ("jpeg files", "*.jpeg"),
                                                    ("all files", "*.*")))
        if t:
            self.edit_image(imatge_label, t, nom, telefon)

    def modificar_contacte(self, entries_fixed, entries_variable,
                           treeview_seleccionat):
        #print dades_usuari
        nom_fixed = entries_fixed[0]
        telefon_fixed = entries_fixed[1]
        email_fixed = entries_fixed[2]

        telefon_variable = entries_variable[0]
        email_variable = entries_variable[1]

        valor_text_telefon_antic = entries_fixed[3]
        valor_text_email_antic = entries_fixed[4]

        changed_email = False
        changed_tel = False
        if email_variable.get() != '':
            try:
                self.check_email(email_variable.get())
            except:
                self.missatge_error_confirmacio.set("El mail no és correcte!")
            else:
                self.cursor.execute(
                    "UPDATE CONTACTES SET email=:email where nom=:nom and telf=:telf",
                    {
                        'email': email_variable.get(),
                        'nom': nom_fixed.get(),
                        'telf': str(telefon_fixed.get())
                    })
                valor_text_email_antic.set(email_variable.get())
                changed_email = True

        if telefon_variable.get() != '':
            try:
                assert int(telefon_variable.get()) >= 600000000
            except:
                self.missatge_error_confirmacio.set("Error en el telefon!")
            else:
                try:
                    self.cursor.execute(
                        "UPDATE CONTACTES SET telf=:nou_telf where nom=:nom and telf=:telf",
                        {
                            'nou_telf': telefon_variable.get(),
                            'nom': nom_fixed.get(),
                            'telf': str(telefon_fixed.get())
                        })
                except sqlite3.IntegrityError:
                    self.missatge_error_confirmacio.set(
                        "El telèfon ja està registrat!")
                else:
                    changed_tel = True
                    self.agenda_contactes.item(treeview_seleccionat,
                                               values=(nom_fixed.get(),
                                                       telefon_variable.get()))
                    valor_text_telefon_antic.set(telefon_variable.get())

        self.db.commit()
        if changed_email & changed_tel:
            self.missatge_error_confirmacio.set(
                "Dades modificades correctament!")
        elif changed_email:
            self.missatge_error_confirmacio.set(
                "Email modificat correctament!")
        elif changed_tel:
            self.missatge_error_confirmacio.set(
                "Telefon modificat correctament!")

    def modifica_contacte(self):
        if self.child_toplevel is not None:
            self.child_toplevel.destroy()

        element_a_modificar = self.agenda_contactes.focus()
        valor_usuari = self.agenda_contactes.item(
            element_a_modificar)['values']
        self.cursor.execute("select * from CONTACTES where nom=? and telf=?;",
                            tuple(valor_usuari))
        dades = self.cursor.fetchone()
        t = Toplevel()
        self.child_toplevel = t

        label_imatge = Label(t)
        label_imatge.configure(background='white')
        label_imatge.pack(side="left", fill="both", expand=True)
        self.show_image(label_imatge, dades[3])
        frame_info = Frame(t)
        frame_info.pack(side="right", fill="both", expand=False)
        frame_info.configure(background='white')
        label_nom = Label(frame_info, text="Nom: ")
        label_nom.configure(background='white')
        label_nom.grid(row=0, column=0)
        entry_nom = Entry(frame_info,
                          textvariable=StringVar(frame_info, value=dades[0]),
                          width=20,
                          state='disabled')
        entry_nom.grid(row=0, column=1)
        label_telefon = Label(frame_info, text="Telefon antic: ")
        label_telefon.configure(background='white')
        label_telefon.grid(row=1, column=0)
        text_telefon = StringVar(frame_info, value=dades[1])
        entry_telefon = Entry(frame_info,
                              textvariable=text_telefon,
                              width=20,
                              state='disabled')
        entry_telefon.grid(row=1, column=1)

        label_telefon_nou = Label(frame_info, text="Telefon nou: ")
        label_telefon_nou.configure(background='white')
        label_telefon_nou.grid(row=2, column=0)
        entry_telefon_nou = Entry(frame_info, width=20)
        entry_telefon_nou.grid(row=2, column=1)

        label_email = Label(frame_info, text="Email: ")
        label_email.configure(background='white')
        label_email.grid(row=3, column=0)
        text_email = StringVar(frame_info, value=dades[2])  #-----
        entry_email = Entry(frame_info,
                            width=20,
                            textvariable=text_email,
                            state='disabled')
        entry_email.grid(row=3, column=1)
        label_email_nou = Label(frame_info, text="Email nou:")
        label_email_nou.configure(background='white')
        label_email_nou.grid(row=4, column=0)
        entry_email_nou = Entry(frame_info, width=20)
        entry_email_nou.grid(row=4, column=1)

        selecciona_imatge = Button(
            frame_info,
            text="Edita foto",
            command=lambda: self.demana_imatge(label_imatge, dades[0],
                                               text_telefon.get()))
        selecciona_imatge.grid(row=5)
        button_modifica_contacte = Button(
            frame_info,
            text="Modificar contacte",
            fg="Blue",
            command=lambda: self.modificar_contacte([
                entry_nom, entry_telefon, entry_email, text_telefon, text_email
            ], [entry_telefon_nou, entry_email_nou], element_a_modificar))
        button_modifica_contacte.grid(row=6, column=1, sticky=E)

    def check_email(self, email):
        if re.match("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                    email):
            return True
        else:
            raise "Mail no vàlid!"

    def elimina_contacte(self):
        element_seleccionat = self.agenda_contactes.focus()
        if element_seleccionat != '':
            informacio_contacte = self.agenda_contactes.item(
                element_seleccionat)['values']
            self.cursor.execute("DELETE from CONTACTES where nom=? and telf=?",
                                tuple(informacio_contacte))
            self.db.commit()
            self.agenda_contactes.delete(element_seleccionat)
            self.missatge_error_confirmacio.set("Borrat correctament")
            if self.child_toplevel is not None:
                self.child_toplevel.destroy()
            #print self.agenda_contactes.focus()
            #print self.agenda_contactes.selection()
        else:
            self.missatge_error_confirmacio.set("Selecciona un usuari!")
            print "Selecciona element"

    def afegeix_contacte(self):
        try:
            Nom = self.entry_nom.get()
            assert Nom != ''
            Telef = int(self.entry_telefon.get())
            assert Telef > 600000000
            Email = self.check_email(self.entry_email.get())

        except:
            self.missatge_error_confirmacio.set(
                "Introdueix les dades correctament!")
        else:
            try:
                self.cursor.execute(
                    """INSERT INTO CONTACTES values (?,?,?,'');""",
                    (Nom.title(), Telef, self.entry_email.get()))
                self.db.commit()
            except sqlite3.IntegrityError:
                self.missatge_error_confirmacio.set("Contacte ja existent!")

            else:
                self.insert_contacts_treeview()
                self.missatge_error_confirmacio.set(
                    "Afegit contacte correctament")
Example #41
0
class OfflineVisualiser(Visualiser):
    """A VTK-powered offline visualiser which runs in its own thread.
    In addition to the functions provided by the standard visualiser,
    the following additional functions are provided:

    precache_height_quantities() - Precache all the vtkpoints
    structures for any dynamic height based quantities to render.
    """
    def __init__(self, source, frameDelay=100, frameStep=1):
        """The source parameter is assumed to be a NetCDF sww file.
        The frameDelay parameter is the number of milliseconds waited between frames.
        """
        Visualiser.__init__(self, source)

        self.frameNumber = 0
        fin = NetCDFFile(self.source, 'r')
        self.maxFrameNumber = fin.variables['time'].shape[0] - 1
        fin.close()

        #self.frameNumberTkVariable = StringVar()
        #self.frameNumberTkVariable.set('Frame - %05g'%self.framNumber)

        self.frameDelay = frameDelay

        self.xmin = None
        self.xmax = None
        self.ymin = None
        self.ymax = None
        self.zmin = None
        self.zmax = None

        self.frameStep = frameStep

        self.vtk_heightQuantityCache = []
        for i in range(self.maxFrameNumber +
                       1):  # maxFrameNumber is zero indexed.
            self.vtk_heightQuantityCache.append({})

        self.paused = False
        self.movie = False

    def setup_grid(self):
        fin = NetCDFFile(self.source, 'r')
        self.vtk_cells = vtkCellArray()
        N_tri = fin.variables['volumes'].shape[0]
        for v in range(N_tri):
            self.vtk_cells.InsertNextCell(3)
            for i in range(3):
                self.vtk_cells.InsertCellPoint(fin.variables['volumes'][v][i])
        fin.close()

    def update_height_quantity(self, quantityName, dynamic=True):
        polydata = self.vtk_polyData[quantityName] = vtkPolyData()
        if dynamic is True:
            #print ' - Frame',self.frameNumber,'of',self.maxFrameNumber
            if not self.vtk_heightQuantityCache[self.frameNumber].has_key(
                    quantityName):
                self.vtk_heightQuantityCache[self.frameNumber][quantityName]\
                    = self.read_height_quantity(quantityName, True, self.frameNumber)
            polydata.SetPoints(
                self.vtk_heightQuantityCache[self.frameNumber][quantityName])
        else:
            polydata.SetPoints(self.read_height_quantity(quantityName, False))
        polydata.SetPolys(self.vtk_cells)

    def get_3d_bounds(self):
        return [
            self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax
        ]

    def read_height_quantity(self, quantityName, dynamic=True, frameNumber=0):
        """Read in a height based quantity from the NetCDF source file
        and return a vtkPoints object. frameNumber is ignored if
        dynamic is false."""
        fin = NetCDFFile(self.source, 'r')
        points = vtkPoints()
        if dynamic is True:
            N_vert = fin.variables[quantityName].shape[1]
        else:
            N_vert = len(fin.variables[quantityName])
        x = num.ravel(num.array(fin.variables['x'], num.float))
        y = num.ravel(num.array(fin.variables['y'], num.float))
        if dynamic is True:
            q = num.array(fin.variables[quantityName][frameNumber], num.float)
        else:
            q = num.ravel(num.array(fin.variables[quantityName], num.float))

        q *= self.height_zScales[quantityName]
        q += self.height_offset[quantityName]

        for v in range(N_vert):
            points.InsertNextPoint(x[v], y[v], q[v])
            if self.xmin is None or self.xmin > x[v]:
                self.xmin = x[v]
            if self.xmax is None or self.xmax < x[v]:
                self.xmax = x[v]
            if self.ymin is None or self.ymin > y[v]:
                self.ymin = y[v]
            if self.ymax is None or self.ymax < y[v]:
                self.ymax = y[v]
            if self.zmin is None or self.zmin > q[v]:
                self.zmin = q[v]
            if self.zmax is None or self.zmax < q[v]:
                self.zmax = q[v]
        fin.close()
        return points

    def precache_height_quantities(self):
        """Precache any height-based quantities. Call before rendering
        beigns."""
        for q in self.height_quantities:
            if self.height_dynamic[q] is True:
                print 'Precaching %s' % q
                for i in range(self.maxFrameNumber +
                               1):  # maxFrameNumber is zero-indexed
                    print ' - Frame %d of %d' % (i, self.maxFrameNumber)
                    self.vtk_heightQuantityCache[i][q]\
                        = self.read_height_quantity(q, True, i)

    def build_quantity_dict(self):
        quantities = {}
        fin = NetCDFFile(self.source, 'r')
        for q in filter(
                lambda n: n != 'x' and n != 'y' and n != 'z' and n != 'time'
                and n != 'volumes', fin.variables.keys()):
            if len(fin.variables[q].shape) == 1:  # Not a time-varying quantity
                quantities[q] = num.ravel(
                    num.array(fin.variables[q], num.float))
            else:  # Time-varying, get the current timestep data
                quantities[q] = num.array(fin.variables[q][self.frameNumber],
                                          num.float)
        fin.close()
        return quantities

    def setup_gui(self):
        Visualiser.setup_gui(self)
        self.tk_quit.grid(row=0, column=0, sticky=W + E)
        self.tk_movie_toggle = Button(self.tk_controlFrame,
                                      text="Movie off",
                                      command=self.movie_toggle)
        self.tk_movie_toggle.grid(row=0, column=6, sticky=W + E)

        self.tk_restart = Button(self.tk_controlFrame,
                                 text="<<<",
                                 command=self.restart,
                                 width=5)
        self.tk_restart.grid(row=1, column=0, sticky=W + E)
        self.tk_back10 = Button(self.tk_controlFrame,
                                text="<<",
                                command=self.back10,
                                width=5)
        self.tk_back10.grid(row=1, column=1, sticky=W + E)
        self.tk_back = Button(self.tk_controlFrame,
                              text="<",
                              command=self.back,
                              width=5)
        self.tk_back.grid(row=1, column=2, sticky=W + E)
        self.tk_pauseResume = Button(self.tk_controlFrame,
                                     text="Pause",
                                     command=self.pauseResume,
                                     width=15)
        self.tk_pauseResume.grid(row=1, column=3, sticky=W + E)
        self.tk_forward = Button(self.tk_controlFrame,
                                 text=">",
                                 command=self.forward,
                                 width=5)
        self.tk_forward.grid(row=1, column=4, sticky=W + E)
        self.tk_forward10 = Button(self.tk_controlFrame,
                                   text=">>",
                                   command=self.forward10,
                                   width=5)
        self.tk_forward10.grid(row=1, column=5, sticky=W + E)
        self.tk_forwardEnd = Button(self.tk_controlFrame,
                                    text=">>>",
                                    command=self.forwardEnd,
                                    width=5)
        self.tk_forwardEnd.grid(row=1, column=6, sticky=W + E)

        self.tk_frameNumber = Label(self.tk_controlFrame, text='Frame')
        self.tk_frameNumber.grid(row=2, column=0, sticky=W + E)
        self.tk_gotoFrame = Scale(self.tk_controlFrame,
                                  from_=0,
                                  to=self.maxFrameNumber,
                                  orient=HORIZONTAL)
        self.tk_gotoFrame.grid(row=2, column=1, columnspan=2, sticky=W + E)
        self.tk_stepLabel = Label(self.tk_controlFrame, text='Step')
        self.tk_stepLabel.grid(row=2, column=4, sticky=W + E)
        self.tk_frameStep = Scale(self.tk_controlFrame,
                                  from_=0,
                                  to=self.maxFrameNumber,
                                  orient=HORIZONTAL)
        self.tk_frameStep.grid(row=2, column=5, columnspan=2, sticky=W + E)

        # Make the buttons stretch to fill all available space
        for i in range(7):
            self.tk_controlFrame.grid_columnconfigure(i, weight=1)

    def run(self):
        self.alter_tkroot(Tk.after, (self.frameDelay, self.animateForward))
        Visualiser.run(self)

    def restart(self):
        self.frameNumber = 0
        self.redraw_quantities()
        self.update_labels()
        self.pause()

        if self.movie:
            self.save_image()

    def forwardEnd(self):
        self.frameNumber = self.maxFrameNumber
        self.redraw_quantities()
        self.update_labels()
        self.pause()

    def movie_toggle(self):
        if self.movie == True:
            self.movie = False
            self.tk_movie_toggle.config(text='Movie off')
        else:
            self.movie = True
            self.tk_movie_toggle.config(text='Movie on ')

    def save_image(self):

        from vtk import vtkJPEGWriter, vtkJPEGWriter, vtkPNGWriter
        from vtk import vtkPNMWriter, vtkWindowToImageFilter
        from os import path

        sourcebase, _ = path.splitext(self.source)
        fname = sourcebase + '%05g.png' % self.frameNumber
        #print fname

        extmap = {
            '.jpg': vtkJPEGWriter,
            '.jpeg': vtkJPEGWriter,
            '.png': vtkPNGWriter,
            '.pnm': vtkPNMWriter,
        }
        basename, ext = path.splitext(fname)
        try:
            Writer = extmap[ext.lower()]
        except KeyError:
            error_msg("Don't know how to handle %s files" % ext, parent=self)
            return

        renWin = self.vtk_renderer.GetRenderWindow()
        w2i = vtkWindowToImageFilter()
        writer = Writer()
        w2i.SetInput(renWin)
        w2i.Update()
        writer.SetInput(w2i.GetOutput())
        writer.SetFileName(fname)
        renWin.Render()
        writer.Write()

    def back10(self):
        if self.frameNumber - 10 >= 0:
            self.frameNumber -= 10
        else:
            self.frameNumber = 0
        self.redraw_quantities()
        self.update_labels()
        self.pause()

    def back(self):
        if self.frameNumber > 0:
            self.frameNumber -= 1
            self.redraw_quantities()
            self.update_labels()
            self.pause()

    def pauseResume(self):
        if self.paused is True:
            self.resume()
        else:
            self.pause()

    def pause(self):
        self.paused = True
        self.tk_pauseResume.config(text="Resume")

    def resume(self):
        self.paused = False
        self.tk_pauseResume.config(text="Pause")
        self.frameNumber = self.tk_gotoFrame.get()
        self.frameStep = self.tk_frameStep.get()
        self.tk_root.after(self.frameDelay, self.animateForward)

    def forward(self):
        if self.frameNumber < self.maxFrameNumber:
            self.frameNumber += 1
            self.redraw_quantities()
            self.update_labels()
            self.pause()

    def forward_step(self):
        if self.frameNumber + self.frameStep <= self.maxFrameNumber:
            self.frameNumber += self.frameStep
            self.redraw_quantities()
            self.update_labels()
        else:
            self.frameNumber = self.maxFrameNumber
            self.redraw_quantities()
            self.update_labels()
            self.pause()

        if self.movie:
            self.save_image()

    def forward10(self):
        if self.frameNumber + 10 <= self.maxFrameNumber:
            self.frameNumber += 10
        else:
            self.frameNumber = self.maxFrameNumber
        self.redraw_quantities()
        self.update_labels()
        self.pause()

    def animateForward(self):
        if self.paused is not True:
            self.forward_step()
            self.tk_root.after(self.frameDelay, self.animateForward)

    def update_labels(self):
        #self.tk_frameNumber.config(text='%05g of %05g'%(self.frameNumber,self.maxFrameNumber))
        self.tk_gotoFrame.set(self.frameNumber)
        self.tk_frameStep.set(self.frameStep)

    def shutdown(self):
        #self.pause()
        self.tk_root.withdraw()
        self.tk_root.destroy()
# =============================================================================
# Create buttons
# =============================================================================

Btn0 = Button(top, width=5, text='Forward')
Btn1 = Button(top, width=5, text='Backward')
Btn2 = Button(top, width=5, text='Left')
Btn3 = Button(top, width=5, text='Right')
Btn4 = Button(top, width=5, text='Quit')
Btn5 = Button(top, width=5, height=2, text='Home')

# =============================================================================
# Buttons layout
# =============================================================================
Btn0.grid(row=0, column=1)
Btn1.grid(row=2, column=1)
Btn2.grid(row=1, column=0)
Btn3.grid(row=1, column=2)
Btn4.grid(row=3, column=2)
Btn5.grid(row=1, column=1)

# =============================================================================
# Bind the buttons with the corresponding callback function.
# =============================================================================
Btn0.bind('<ButtonPress-1>', forward_fun
          )  # When button0 is pressed down, call the function forward_fun().
Btn1.bind('<ButtonPress-1>', backward_fun)
Btn2.bind('<ButtonPress-1>', left_fun)
Btn3.bind('<ButtonPress-1>', right_fun)
Btn0.bind('<ButtonRelease-1>',
class GUI:
    Path = "" 
    
    ########################################################################################
    # Define functions to be used for the GUI to work
    #####################################################   
    
    def greet(self):
        
        #If the folder to run in has not been assigned, force the folder selection before running.
        if(GUI.Path == ""):
           GUI.Path = tkFileDialog.askdirectory()
        language = self.combo.get()
                
        #Pull the keyword text from the Entry widget.
        text = self.entry.get()
        
        #Create a list from the string provided delimited by commas.
        keywordList = text.split(',')        
        
        #Output keywords to console for debugging
        for x, key in enumerate(keywordList):
            keywordList[x] = key.lower().replace(' ','')
            print(str(x) + " - " + key)
        
        #Run the main function and pass the path, language, and keyword list.
        run_OCR(GUI.Path, language, keywordList)
    
    def load(self):
        #Open text file for reading. 
        keywordFile = tkFileDialog.askopenfile()
        keywords = keywordFile.read()
        
        #print file contents for debugging.
        print(keywordFile.readlines())
        
        self.entry.insert(0,keywords)
        
            
    def choose(self):
        #Assing the folder the user chooses to the GUI.Path variable
        GUI.Path = tkFileDialog.askdirectory()
        
    def __init__(self, master):
        self.master = master       
        master.title("PDF OCR with Python")
        
        ##########################################################################
        # Create buttons and our combobox for user interaction
        #########################################################
               
        #Create button to load a list of keywords
        self.load_button = Button(master, text="Load Keywords", command=self.load, width = 12)
        self.load_button.grid(row = 2, column = 0)
        
        #Create Combo Box        
        self.combo = ttk.Combobox(width = 10)
        self.combo['values'] = ('eng','spa', 'chi_tra', 'ita', 'jpn', 'heb', 'kor', 'fra', 'deu', 'por', 'pol', 'rus')        
        self.combo.current(0)
        self.combo.pack(side=LEFT)
        self.combo.grid(row =4, column = 0)
        
        #Create a folder chooser
        self.chooser_button = Button(master, text="Set Folder", command=self.choose, width = 12)
        self.chooser_button.grid(row = 6, column = 0)
                
        #Create Run Button
        self.greet_button = Button(master, text="Run", command=self.greet, width = 12)
        self.greet_button.grid(row=8, column = 0)
                        
        ##########################################################################
        # Create Middle Labels for Padding
        ########################################
        
        # Create blank label for padding
        self.label = Label(master, text="      ")
        self.label.grid(row=1, column = 1, sticky = W)      
        
        self.label = Label(master, text="      ")
        self.label.grid(row=2, column = 1, sticky = W)
        
        self.label = Label(master, text="      ")
        self.label.grid(row=3, column = 1, sticky = W)
        
        self.label = Label(master, text="      ")
        self.label.grid(row=4, column = 1, sticky = W)
        
        self.label = Label(master, text="      ")
        self.label.grid(row=5, column = 1, sticky = W)
             
        ##########################################################################
        # Create Instruction Label(s)
        ######################################
        self.label = Label(master, text="Run Instructions:")
        self.label.grid(row=1, column = 3, sticky = W)
        
        self.label = Label(master, text="1. Place all PDFs for OCR into a folder.")
        self.label.grid(row=2, column = 3, sticky = W)
                
        self.label = Label(master, text="   1a. If PDFs are in different languages then create a folder for each language.")
        self.label.grid(row=3, column = 3, sticky = W)
        
        self.label = Label(master, text="2. Either load or enter the keywords in the text box below.")
        self.label.grid(row=4, column = 3, sticky = W)
        
        self.label = Label(master, text="   2a. Seperate words by commas. Use quotes for exact word searches")
        self.label.grid(row=5, column = 3, sticky = W)
        
        self.label = Label(master, text="3. Specify the language of the PDFs.")
        self.label.grid(row=6, column = 3, sticky = W)
        
        self.label = Label(master, text="4. Set the folder to run in.")
        self.label.grid(row=7, column = 3, sticky = W)
        
        self.label = Label(master, text="5. Click Run.")
        self.label.grid(row=8, column = 3, sticky = W)
        
        self.label = Label(master, text="6. A folder will be created for each PDF containing the original file and the OCR'ed text .")
        self.label.grid(row=8, column = 3, sticky = W)
                
        self.label = Label(master, text="7. A results excel file ('Keyword Results') will be created in your original folder.")
        self.label.grid(row=9, column = 3, sticky = W)
        
        self.label = Label(master, text="")
        self.label.grid(row=10, column = 3, sticky = W)
        
        ###########################################################################        
        #Create an Entry widget to enter/display keywords at bottom
        ############################################################
        
        self.label = Label(master, text="Keywords:")
        self.label.grid(row=11, column = 0)
        
        self.entry = Entry(master)
        self.entry.grid(row = 12, column = 1, columnspan = 6, sticky=W+E)
        
        self.label = Label(master, text="Example: privacy, 'term', fine, penalt, cost, exception")
        self.label.grid(row=11, column = 1, columnspan = 6, sticky = W)        
Example #44
0
    def __init__(self, root, cursor, db):
        self.frame = Frame(root)
        self.frame.configure(background='white')
        self.list_toplevel = {}
        self.cursor = cursor
        self.db = db
        self.child_toplevel = None
        self.frame.pack()
        image = Image.open("photo.jpg")
        image = image.resize((250, 250), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        label = Label(self.frame, image=photo)
        label.grid(row=0, column=0, sticky=W)
        label.image = photo  # keep a reference!
        nou_registre = LabelFrame(self.frame,
                                  text="Nou registre",
                                  fg="Blue",
                                  padx=5,
                                  pady=5)
        nou_registre.configure(background='white')
        nou_registre.grid(row=0, column=1, padx=15, sticky=W)

        text_nom = Label(nou_registre, text="Nom:", fg="Blue")
        text_nom.configure(background='white')
        text_nom.grid(row=0, column=0)
        self.entry_nom = Entry(nou_registre)
        self.entry_nom.grid(row=0, column=1, sticky=W)

        text_telefon = Label(nou_registre, text="Telèfon: ", fg="Blue")
        text_telefon.configure(background='white')
        text_telefon.grid(row=1, column=0)
        self.entry_telefon = Entry(nou_registre)
        self.entry_telefon.grid(row=1, column=1)

        text_email = Label(nou_registre, text="Email: ", fg="Blue")
        text_email.configure(background='white')
        text_email.grid(row=2, column=0)
        self.entry_email = Entry(nou_registre)
        self.entry_email.grid(row=2, column=1)

        button_afegir_contacte = Button(nou_registre,
                                        text="Afegir contacte",
                                        fg="Blue",
                                        command=self.afegeix_contacte)
        button_afegir_contacte.grid(row=3, column=1, sticky=E)

        button_mostra_historic = Button(nou_registre,
                                        text="Mostra historic",
                                        fg="Blue",
                                        command=self.mostra_historic)
        button_mostra_historic.grid(row=4, column=0, sticky=W)

        mostrar_contactes = Button(self.frame,
                                   text="Mostrar contactes",
                                   fg="Blue",
                                   command=self.insert_contacts_treeview)
        mostrar_contactes.grid(sticky=W, row=3)

        self.missatge_error_confirmacio = StringVar()

        self.label_error_confirmacio = Label(
            self.frame, textvariable=self.missatge_error_confirmacio, fg="Red")
        self.label_error_confirmacio.configure(background='white')
        self.label_error_confirmacio.grid(sticky=W, row=3, column=1)

        self.agenda_contactes = Treeview(self.frame,
                                         columns=["nom", "tel"],
                                         show="headings")
        self.agenda_contactes.heading("nom", text="Nom")
        self.agenda_contactes.heading("tel", text="Telefon")
        self.agenda_contactes.column("nom",
                                     minwidth=0,
                                     width=200,
                                     stretch=NO,
                                     anchor="c")
        self.agenda_contactes.column("tel",
                                     minwidth=0,
                                     width=200,
                                     stretch=NO,
                                     anchor="c")
        self.agenda_contactes.grid(row=4, column=0, padx=0, columnspan=2)

        self.insert_contacts_treeview()
        elimina_seleccionat = Button(self.frame,
                                     text="Eliminar seleccionat",
                                     command=self.elimina_contacte,
                                     fg="Blue")
        elimina_seleccionat.grid(row=5, column=0, sticky=W)

        self.modificar_seleccionat = Button(self.frame,
                                            text="Modificar seleccionat",
                                            fg="Blue",
                                            command=self.modifica_contacte)
        self.modificar_seleccionat.grid(row=5, column=1, sticky=W)
        sortir = Button(self.frame,
                        text="Sortir",
                        fg="Blue",
                        command=self.frame.quit)
        sortir.grid(row=5, column=2, sticky=E)
Example #45
0
    def modifica_contacte(self):
        if self.child_toplevel is not None:
            self.child_toplevel.destroy()

        element_a_modificar = self.agenda_contactes.focus()
        valor_usuari = self.agenda_contactes.item(
            element_a_modificar)['values']
        self.cursor.execute("select * from CONTACTES where nom=? and telf=?;",
                            tuple(valor_usuari))
        dades = self.cursor.fetchone()
        t = Toplevel()
        self.child_toplevel = t

        label_imatge = Label(t)
        label_imatge.configure(background='white')
        label_imatge.pack(side="left", fill="both", expand=True)
        self.show_image(label_imatge, dades[3])
        frame_info = Frame(t)
        frame_info.pack(side="right", fill="both", expand=False)
        frame_info.configure(background='white')
        label_nom = Label(frame_info, text="Nom: ")
        label_nom.configure(background='white')
        label_nom.grid(row=0, column=0)
        entry_nom = Entry(frame_info,
                          textvariable=StringVar(frame_info, value=dades[0]),
                          width=20,
                          state='disabled')
        entry_nom.grid(row=0, column=1)
        label_telefon = Label(frame_info, text="Telefon antic: ")
        label_telefon.configure(background='white')
        label_telefon.grid(row=1, column=0)
        text_telefon = StringVar(frame_info, value=dades[1])
        entry_telefon = Entry(frame_info,
                              textvariable=text_telefon,
                              width=20,
                              state='disabled')
        entry_telefon.grid(row=1, column=1)

        label_telefon_nou = Label(frame_info, text="Telefon nou: ")
        label_telefon_nou.configure(background='white')
        label_telefon_nou.grid(row=2, column=0)
        entry_telefon_nou = Entry(frame_info, width=20)
        entry_telefon_nou.grid(row=2, column=1)

        label_email = Label(frame_info, text="Email: ")
        label_email.configure(background='white')
        label_email.grid(row=3, column=0)
        text_email = StringVar(frame_info, value=dades[2])  #-----
        entry_email = Entry(frame_info,
                            width=20,
                            textvariable=text_email,
                            state='disabled')
        entry_email.grid(row=3, column=1)
        label_email_nou = Label(frame_info, text="Email nou:")
        label_email_nou.configure(background='white')
        label_email_nou.grid(row=4, column=0)
        entry_email_nou = Entry(frame_info, width=20)
        entry_email_nou.grid(row=4, column=1)

        selecciona_imatge = Button(
            frame_info,
            text="Edita foto",
            command=lambda: self.demana_imatge(label_imatge, dades[0],
                                               text_telefon.get()))
        selecciona_imatge.grid(row=5)
        button_modifica_contacte = Button(
            frame_info,
            text="Modificar contacte",
            fg="Blue",
            command=lambda: self.modificar_contacte([
                entry_nom, entry_telefon, entry_email, text_telefon, text_email
            ], [entry_telefon_nou, entry_email_nou], element_a_modificar))
        button_modifica_contacte.grid(row=6, column=1, sticky=E)
Example #46
0
    def __init__(self, master):

        self.fname = ""
        #global variables
        self.t1 = StringVar()
        self.t2 = StringVar()
        self.t3 = StringVar()
        self.t4 = StringVar()
        self.t5 = StringVar()
        self.t6 = StringVar()
        self.t7 = StringVar()
        self.t8 = StringVar()
        self.t9 = StringVar()
        self.t10 = StringVar()
        self.t11 = StringVar()
        self.t12 = StringVar()
        self.t13 = StringVar()
        self.t14 = StringVar()
        self.t15 = StringVar()
        self.t16 = StringVar()
        self.t17 = StringVar()
        self.t18 = StringVar()
        self.t19 = StringVar()
        self.t20 = StringVar()
        self.t21 = StringVar()
        self.t22 = StringVar()
        self.t23 = StringVar()
        self.t24 = StringVar()
        self.t25 = StringVar()
        self.t26 = StringVar()
        self.t27 = StringVar()
        self.t28 = StringVar()
        self.t29 = StringVar()
        self.t30 = StringVar()
        self.t31 = StringVar()
        self.t32 = StringVar()
        self.t33 = StringVar()
        self.t34 = StringVar()

        self.var1 = StringVar()
        self.var2 = StringVar()
        self.var3 = StringVar()
        self.var4 = StringVar()
        self.var5 = StringVar()
        self.var6 = StringVar()
        self.var7 = StringVar()
        self.var8 = StringVar()
        self.var9 = StringVar()
        self.var10 = StringVar()
        self.var11 = StringVar()
        self.var12 = StringVar()
        self.var13 = StringVar()
        self.var14 = StringVar()
        self.var15 = StringVar()
        self.var16 = StringVar()
        self.var17 = StringVar()
        self.var18 = StringVar()
        self.var19 = StringVar()
        self.var20 = StringVar()
        self.var21 = StringVar()
        self.var22 = StringVar()
        self.var23 = StringVar()
        self.var24 = StringVar()
        self.var25 = StringVar()
        self.var26 = StringVar()
        self.var27 = StringVar()
        self.var28 = StringVar()
        self.var29 = StringVar()
        self.var30 = StringVar()
        self.var31 = StringVar()
        self.var32 = StringVar()
        self.var33 = StringVar()
        self.var34 = StringVar()
        #end

        mymaster = Frame(master, name='mymaster')  # create Frame in "root"
        mymaster.pack(fill=BOTH)
        #min and max size of window
        #master.minsize(width=900, height=900)
        #master.maxsize(width=650, height=385)
        #end

        #title of window
        master.title("Airbase-ng")
        #end

        #for the style of fonts
        self.customFont = tkFont.Font(family="Helvetica", size=12)
        self.myfont = tkFont.Font(family="Helvetica", size=10)
        self.myfont2 = tkFont.Font(family="Helvetica", size=8)
        self.headerfont = tkFont.Font(family="Helvetica",
                                      size=15,
                                      underline=True)
        self.myfontnew = tkFont.Font(family="Helvetica",
                                     size=11,
                                     underline=True)
        #end

        nb = Notebook(mymaster, name='nb')  # create Notebook in "master"
        nb.pack(fill=BOTH, padx=2, pady=3)  # fill "master" but pad sides
        #content frame
        self.frame_content = Frame(nb, name="frame_content", bg="white")
        self.frame_content.pack(fill=BOTH, side=TOP, expand=True)
        nb.add(self.frame_content, text="Filter-1")  # add tab to Notebook

        # repeat for each tab
        self.frame_content2 = Frame(nb, name='frame_content2', bg="white")
        nb.add(self.frame_content2, text="Filter-2")
        self.frame_content3 = Frame(nb, name='frame_content3', bg="white")
        nb.add(self.frame_content3, text="Filter-3")
        self.frame_content4 = Frame(nb, name='frame_content4', bg="white")
        nb.add(self.frame_content4, text="Filter-4")
        self.frame_content6 = Frame(nb, name='frame_content6', bg="white")
        nb.add(self.frame_content6, text="Filter-5")
        self.frame_content7 = Frame(nb, name='frame_content7', bg="white")
        nb.add(self.frame_content7, text="Detect Devices")
        self.frame_content5 = Frame(nb, name='frame_content5', bg="white")
        nb.add(self.frame_content5, text="output")

        #End
        #frame content 7
        Label(self.frame_content7,
              text='Airbase-ng',
              font=self.headerfont,
              bg="white",
              padx=10,
              pady=10).grid(row=0, column=0)
        btndetect = Button(self.frame_content7,
                           text='Detect',
                           command=self.canvas_detect,
                           height=2,
                           width=15,
                           font=self.customFont).grid(row=1,
                                                      column=0,
                                                      padx=5,
                                                      pady=5)

        btndbrowse = Button(self.frame_content7,
                            text='Attach File',
                            command=self.browse_file,
                            height=2,
                            width=15,
                            font=self.customFont).grid(row=3,
                                                       column=0,
                                                       padx=5,
                                                       pady=5)
        self.lilnew1 = Listbox(self.frame_content7,
                               bg="black",
                               fg="white",
                               font=self.myfont,
                               selectmode=SINGLE,
                               width=30,
                               height=15)
        self.lilnew1.grid(row=1, column=1, rowspan=3)
        #End

        Label(self.frame_content,
              text='Airbase-ng',
              font=self.headerfont,
              bg="white",
              padx=10,
              pady=10).grid(row=0, column=0)
        Label(self.frame_content,
              text='Options :',
              font=self.myfontnew,
              bg="white").grid(row=1, column=1)
        #command Listbox
        Label(self.frame_content5,
              text='Edit Command From Here',
              font=self.myfontnew,
              bg="white",
              justify=LEFT).grid(row=0, column=0)
        TextCommandBox = Text(self.frame_content5, height=5, width=30)
        TextCommandBox.grid(row=1, column=0, padx=5, pady=5)
        self.output = Text(self.frame_content5,
                           bg="black",
                           fg="white",
                           font=self.myfont,
                           height=20,
                           width=42)
        self.output.grid(row=0, column=1, padx=50, pady=5, rowspan=3)
        btnsubmit = Button(self.frame_content5,
                           width=15,
                           height=2,
                           text="Get Result",
                           command=self.mycallback)
        btnsubmit.grid(row=2, column=0)
        btnclear = Button(self.frame_content5,
                          width=15,
                          height=2,
                          text="Clear Output",
                          command=self.clearoutput)
        btnclear.grid(row=3, column=0)
        #end
        self.C1 = Checkbutton(self.frame_content, text = "-a", \
                 onvalue = "-a", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont, variable=self.var1)
        self.C1.grid(row=2, column=0, padx=5, pady=5)
        self.t1 = Text(self.frame_content, height=1, width=20)
        self.t1.grid(row=2, column=1, padx=5, pady=5)
        l1 = Label(self.frame_content,
                   text=': set Access Point MAC address',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=2, column=2, padx=5, pady=5)

        self.C2 = Checkbutton(self.frame_content, text = "-i", \
                 onvalue = "-i", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont, variable=self.var2)
        self.C2.grid(row=3, column=0, padx=5, pady=5)
        self.t2 = Text(self.frame_content, height=1, width=20)
        self.t2.grid(row=3, column=1, padx=5, pady=5)
        l2 = Label(self.frame_content,
                   text=': capture packets from this interface',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=3, column=2, padx=5, pady=5)

        self.C3 = Checkbutton(self.frame_content, text = "-w", \
                 onvalue = "-w", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var3)
        self.C3.grid(row=4, column=0, padx=5, pady=5)
        self.t3 = Text(self.frame_content, height=1, width=20)
        self.t3.grid(row=4, column=1, padx=5, pady=5)
        l3 = Label(self.frame_content,
                   text=': use this WEP key to encrypt/decrypt packets',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=4, column=2, padx=5, pady=5)

        self.C4 = Checkbutton(self.frame_content, text = "-h", \
                 onvalue = "-h", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var4)
        self.C4.grid(row=5, column=0, padx=5, pady=5)
        self.t4 = Text(self.frame_content, height=1, width=20)
        self.t4.grid(row=5, column=1, padx=5, pady=5)
        l4 = Label(self.frame_content,
                   text=': source mac for MITM mode',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=5, column=2, padx=5, pady=5)

        self.C5 = Checkbutton(self.frame_content, text = "-f", \
                 onvalue = "-f", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var5)
        self.C5.grid(row=6, column=0, padx=5, pady=5)
        self.t5 = Text(self.frame_content, height=1, width=20)
        self.t5.grid(row=6, column=1, padx=5, pady=5)
        l5 = Label(self.frame_content,
                   text=': disallow specified client MACs (default: allow)',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=6, column=2, padx=5, pady=5)

        self.C6 = Checkbutton(self.frame_content, text = "-W", \
                 onvalue = "-W", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var6)
        self.C6.grid(row=7, column=0, padx=5, pady=5)
        self.t6 = Text(self.frame_content, height=1, width=20)
        self.t6.grid(row=7, column=1, padx=5, pady=5)
        l6 = Label(
            self.frame_content,
            text=': [don\'t] set WEP flag in beacons 0|1 (default: auto)',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=7, column=2, padx=5, pady=5)

        self.C7 = Checkbutton(self.frame_content, text = "-q", \
                 onvalue = "-q", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var7)
        self.C7.grid(row=8, column=0, padx=5, pady=5)
        self.t7 = Text(self.frame_content, height=1, width=20)
        self.t7.grid(row=8, column=1, padx=5, pady=5)
        l7 = Label(self.frame_content,
                   text=': quiet (do not print statistics)',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=8, column=2, padx=5, pady=5)

        self.C8 = Checkbutton(self.frame_content2, text = "-v", \
                 onvalue = "-v", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var8)
        self.C8.grid(row=9, column=0, padx=5, pady=5)
        self.t8 = Text(self.frame_content2, height=1, width=20)
        self.t8.grid(row=9, column=1, padx=5, pady=5)
        l8 = Label(self.frame_content2,
                   text=':  verbose (print more messages) (long --verbose)',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=9, column=2, padx=5, pady=5)

        self.C9 = Checkbutton(self.frame_content2, text = "-M", \
                 onvalue = "-M", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var9)
        self.C9.grid(row=10, column=0, padx=5, pady=5)
        self.t9 = Text(self.frame_content2, height=1, width=20)
        self.t9.grid(row=10, column=1, padx=5, pady=5)
        l9 = Label(self.frame_content2,
                   text=': M-I-T-M between [specified] clients and bssids',
                   font=self.myfont,
                   bg="white",
                   justify=LEFT).grid(row=10, column=2, padx=5, pady=5)

        Label(self.frame_content2,
              text='Airbase-ng',
              font=self.headerfont,
              bg="white",
              padx=10,
              pady=10).grid(row=0, column=0)

        self.C10 = Checkbutton(self.frame_content2, text = "-A", \
                 onvalue = "-A", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var10)
        self.C10.grid(row=11, column=0, padx=5, pady=5)
        self.t10 = Text(self.frame_content2, height=1, width=20)
        self.t10.grid(row=11, column=1, padx=5, pady=5)
        l10 = Label(
            self.frame_content2,
            text=': Ad-Hoc Mode (allows other clients to peer) (long --ad-hoc)',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=11, column=2, padx=5, pady=5)

        self.C11 = Checkbutton(self.frame_content2, text = "-Y", \
                 onvalue = "-Y", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var11)
        self.C11.grid(row=12, column=0, padx=5, pady=5)
        self.t11 = Text(self.frame_content2, height=1, width=20)
        self.t11.grid(row=12, column=1, padx=5, pady=5)
        l11 = Label(self.frame_content2,
                    text=': external packet processing',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=12, column=2, padx=5, pady=5)

        self.C12 = Checkbutton(self.frame_content2, text = "-c", \
                 onvalue = "-c", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var12)
        self.C12.grid(row=13, column=0, padx=5, pady=5)
        self.t12 = Text(self.frame_content2, height=1, width=20)
        self.t12.grid(row=13, column=1, padx=5, pady=5)
        l12 = Label(self.frame_content2,
                    text=': sets the channel the AP is running on',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=13, column=2, padx=5, pady=5)

        self.C13 = Checkbutton(self.frame_content2, text = "-X", \
                 onvalue = "-X", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var13)
        self.C13.grid(row=14, column=0, padx=5, pady=5)
        self.t13 = Text(self.frame_content2, height=1, width=20)
        self.t13.grid(row=14, column=1, padx=5, pady=5)
        l13 = Label(self.frame_content2,
                    text=': hidden ESSID (long --hidden)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=14, column=2, padx=5, pady=5)

        self.C14 = Checkbutton(self.frame_content2, text = "-s", \
                 onvalue = "-s", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var14)
        self.C14.grid(row=15, column=0, padx=5, pady=5)
        self.t14 = Text(self.frame_content2, height=1, width=20)
        self.t14.grid(row=15, column=1, padx=5, pady=5)
        l14 = Label(self.frame_content2,
                    text=': force shared key authentication',
                    font=self.myfont,
                    bg="white").grid(row=15, column=2, padx=5, pady=5)

        Label(self.frame_content3,
              text='Airbase-ng',
              font=self.headerfont,
              bg="white",
              padx=10,
              pady=10).grid(row=0, column=0)
        Label(self.frame_content3,
              text='Filter Options :',
              font=self.myfontnew,
              bg="white",
              justify=LEFT).grid(row=16, column=1)

        self.C15 = Checkbutton(self.frame_content3, text = "-S", \
                 onvalue = "-S", offvalue = "", height=1, \
                 width = 7, bg="white", font=self.customFont,variable=self.var15)
        self.C15.grid(row=17, column=0, padx=5, pady=5)
        self.t15 = Text(self.frame_content3, height=1, width=20)
        self.t15.grid(row=17, column=1, padx=5, pady=5)
        l15 = Label(self.frame_content3,
                    text=': set shared key challenge length (default: 128)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=17, column=2, padx=5, pady=5)

        self.C16 = Checkbutton(self.frame_content3, text = "-L", \
                 onvalue = "-L", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var16)
        self.C16.grid(row=18, column=0, padx=5, pady=5)
        self.t16 = Text(self.frame_content3, height=1, width=20)
        self.t16.grid(row=18, column=1, padx=5, pady=5)
        l16 = Label(self.frame_content3,
                    text=': Caffe-Latte attack (long --caffe-latte)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=18, column=2, padx=5, pady=5)

        self.C17 = Checkbutton(self.frame_content3, text = "-N", \
                 onvalue = "-N", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var17)
        self.C17.grid(row=19, column=0, padx=5, pady=5)
        self.t17 = Text(self.frame_content3, height=1, width=20)
        self.t17.grid(row=19, column=1, padx=5, pady=5)
        l17 = Label(
            self.frame_content3,
            text=':  creates arp request against wep client (long cfrag)',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=19, column=2, padx=5, pady=5)


        self.C18 = Checkbutton(self.frame_content3, text = "-x", \
                 onvalue = "-x", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var18)
        self.C18.grid(row=21, column=0, padx=5, pady=5)
        self.t18 = Text(self.frame_content3, height=1, width=20)
        self.t18.grid(row=21, column=1, padx=5, pady=5)
        l18 = Label(self.frame_content3,
                    text=': number of packets per second (default: 100)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=21, column=2, padx=5, pady=5)

        self.C19 = Checkbutton(self.frame_content3, text = "-y", \
                 onvalue = "-y", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var19)
        self.C19.grid(row=22, column=0, padx=5, pady=5)
        self.t19 = Text(self.frame_content3, height=1, width=20)
        self.t19.grid(row=22, column=1, padx=5, pady=5)
        l19 = Label(self.frame_content3,
                    text=': disables responses to broadcast probes',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=22, column=2, padx=5, pady=5)

        Label(self.frame_content4,
              text='Airbase-ng',
              font=self.headerfont,
              bg="white",
              padx=10,
              pady=10).grid(row=0, column=0)

        self.C20 = Checkbutton(self.frame_content4, text = "--o", \
                 onvalue = "--o", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var20)
        self.C20.grid(row=23, column=0, padx=5, pady=5)
        self.t20 = Text(self.frame_content4, height=1, width=20)
        self.t20.grid(row=23, column=1, padx=5, pady=5)
        l20 = Label(
            self.frame_content4,
            text=': set all WPA,WEP,open tags. can\'t be used with -z & -Z',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=23, column=2, padx=5, pady=5)

        self.C21 = Checkbutton(self.frame_content4, text = "-z", \
                 onvalue = "-z", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var21)
        self.C21.grid(row=24, column=0, padx=5, pady=5)
        self.t21 = Text(self.frame_content4, height=1, width=20)
        self.t21.grid(row=24, column=1, padx=5, pady=5)
        l21 = Label(
            self.frame_content4,
            text=':  sets WPA1 tags. 1=WEP40 2=TKIP 3=WRAP 4=CCMP 5=WEP104',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=24, column=2, padx=5, pady=5)

        self.C22 = Checkbutton(self.frame_content4, text = "-Z", \
                 onvalue = "-Z", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var22)
        self.C22.grid(row=25, column=0, padx=5, pady=5)
        self.t22 = Text(self.frame_content4, height=1, width=20)
        self.t22.grid(row=25, column=1, padx=5, pady=5)
        l22 = Label(self.frame_content4,
                    text=':  same as -z, but for WPA2',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=25, column=2, padx=5, pady=5)

        self.C23 = Checkbutton(self.frame_content4, text = "-V", \
                 onvalue = "-V", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var23)
        self.C23.grid(row=26, column=0, padx=5, pady=5)
        self.t23 = Text(self.frame_content4, height=1, width=20)
        self.t23.grid(row=26, column=1, padx=5, pady=5)
        l23 = Label(self.frame_content4,
                    text=':  fake EAPOL 1=MD5 2=SHA1 3=auto',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=26, column=2, padx=5, pady=5)

        self.C24 = Checkbutton(self.frame_content4, text = "-F", \
                 onvalue = "-F", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var24)
        self.C24.grid(row=27, column=0, padx=5, pady=5)
        self.t24 = Text(self.frame_content4, height=1, width=20)
        self.t24.grid(row=27, column=1, padx=5, pady=5)
        l24 = Label(
            self.frame_content4,
            text=':  write all sent and received frames into pcap file',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=27, column=2, padx=5, pady=5)

        self.C25 = Checkbutton(self.frame_content4, text = "-P", \
                 onvalue = "-P", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var25)
        self.C25.grid(row=28, column=0, padx=5, pady=5)
        self.t25 = Text(self.frame_content4, height=1, width=20)
        self.t25.grid(row=28, column=1, padx=5, pady=5)
        l25 = Label(
            self.frame_content4,
            text=':  respond to all probes, even when specifying ESSIDs',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=28, column=2, padx=5, pady=5)


        self.C26 = Checkbutton(self.frame_content4, text = "-I", \
                 onvalue = "-I", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var26)
        self.C26.grid(row=29, column=0, padx=5, pady=5)
        self.t26 = Text(self.frame_content4, height=1, width=20)
        self.t26.grid(row=29, column=1, padx=5, pady=5)
        l26 = Label(self.frame_content4,
                    text=':  sets the beacon interval value in ms',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=29, column=2, padx=5, pady=5)

        self.C27 = Checkbutton(self.frame_content4, text = "-C", \
                 onvalue = "-C", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var27)
        self.C27.grid(row=30, column=0, padx=5, pady=5)
        self.t27 = Text(self.frame_content4, height=1, width=20)
        self.t27.grid(row=30, column=1, padx=5, pady=5)
        l27 = Label(
            self.frame_content4,
            text=':   enables beaconing of probed ESSID values (requires -P)',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=30, column=2, padx=5, pady=5)

        Label(self.frame_content6,
              text='Airbase-ng',
              font=self.headerfont,
              bg="white",
              padx=10,
              pady=10).grid(row=0, column=0)
        Label(self.frame_content6,
              text='Filter Options :',
              font=self.myfontnew,
              bg="white",
              justify=LEFT).grid(row=16, column=1)

        self.C28 = Checkbutton(self.frame_content6, text = "--bssid", \
                 onvalue = "--bssid", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var28)
        self.C28.grid(row=31, column=0, padx=5, pady=5)
        self.t28 = Text(self.frame_content6, height=1, width=20)
        self.t28.grid(row=31, column=1, padx=5, pady=5)
        l28 = Label(self.frame_content6,
                    text=':  BSSID to filter/use (short -b)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=31, column=2, padx=5, pady=5)

        self.C29 = Checkbutton(self.frame_content6, text = "--bssids", \
                 onvalue = "--bssids", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var29)
        self.C29.grid(row=32, column=0, padx=5, pady=5)
        self.t29 = Text(self.frame_content6, height=1, width=20)
        self.t29.grid(row=32, column=1, padx=5, pady=5)
        l29 = Label(
            self.frame_content6,
            text=':  read a list of BSSIDs out of that file (short -B)',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=32, column=2, padx=5, pady=5)

        self.C30 = Checkbutton(self.frame_content6, text = "--client", \
                 onvalue = "--client", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var30)
        self.C30.grid(row=33, column=0, padx=5, pady=5)
        self.t30 = Text(self.frame_content6, height=1, width=20)
        self.t30.grid(row=33, column=1, padx=5, pady=5)
        l30 = Label(self.frame_content6,
                    text=':   MAC of client to accept (short -d)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=33, column=2, padx=5, pady=5)

        self.C31 = Checkbutton(self.frame_content6, text = "--clients", \
                 onvalue = "--clients", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var31)
        self.C31.grid(row=34, column=0, padx=5, pady=5)
        self.t31 = Text(self.frame_content6, height=1, width=20)
        self.t31.grid(row=34, column=1, padx=5, pady=5)
        l31 = Label(self.frame_content6,
                    text=':  read a list of MACs out of that file (short -D)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=34, column=2, padx=5, pady=5)

        self.C32 = Checkbutton(self.frame_content6, text = "--essid", \
                 onvalue = "--essid", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var32)
        self.C32.grid(row=35, column=0, padx=5, pady=5)
        self.t32 = Text(self.frame_content6, height=1, width=20)
        self.t32.grid(row=35, column=1, padx=5, pady=5)
        l32 = Label(self.frame_content6,
                    text=':  specify a single ESSID (short -e)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=35, column=2, padx=5, pady=5)

        self.C33 = Checkbutton(self.frame_content6, text = "--essids", \
                 onvalue = "--essids", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var33)
        self.C33.grid(row=36, column=0, padx=5, pady=5)
        self.t33 = Text(self.frame_content6, height=1, width=20)
        self.t33.grid(row=36, column=1, padx=5, pady=5)
        l33 = Label(
            self.frame_content6,
            text=':  read a list of ESSIDs out of that file (short -E)',
            font=self.myfont,
            bg="white",
            justify=LEFT).grid(row=36, column=2, padx=5, pady=5)

        self.C34 = Checkbutton(self.frame_content6, text = "--help", \
                 onvalue = "--help", offvalue = "", height=1, \
                 bg="white", font=self.customFont,variable=self.var34)
        self.C34.grid(row=37, column=0, padx=5, pady=5)
        self.t34 = Text(self.frame_content6, height=1, width=20)
        self.t34.grid(row=37, column=1, padx=5, pady=5)
        l34 = Label(self.frame_content6,
                    text=':  Displays the usage screen (short -H)',
                    font=self.myfont,
                    bg="white",
                    justify=LEFT).grid(row=37, column=2, padx=5, pady=5)
Example #47
0
class MatrixProperties:
    """Gets the contaminant properties."""

    def __init__(self, master, system, materials):

        """Constructor method. Defines the parameters to be obtained in this window."""

        self.master    = master
        self.fonttype  = system.fonttype
        self.version   = system.version
        self.superfont = get_superfont(self.fonttype) #superscript font
        self.tframe    = Frame(master.tframe)
        self.frame     = Frame(master.frame)
        self.bframe    = Frame(master.bframe)
        self.top       = None                   #flag for existence of toplevel#

        self.system    = system
        self.materials = materials

        if system.matrices is None:
            self.matrices  = []
            self.nmatrices = 0
        else:
            self.matrices  = system.matrices
            self.nmatrices = system.nmatrices


    def make_widgets(self):
        """Make the widgets for the window."""

        self.bgcolor      = self.frame.cget('bg')

        # Construct all label widgets used in the problem
        self.instructions = Label(self.tframe, text = ' Please select the potential layer materials and provide the following properties:                    ')

        self.blankcolumn    = Label(self.tframe,  text ='',  width = 1)
        self.editcolumn     = Label(self.tframe,  text =' ', width = 6)
        self.delcolumn      = Label(self.tframe,  text =' ', width = 6)
        self.namecolumn     = Label(self.tframe,  text =' ', width = 20)
        self.ecolumn        = Label(self.tframe,  text =' ', width = 15)
        self.rhocolumn      = Label(self.tframe,  text =' ', width = 15)
        self.foccolumn      = Label(self.tframe,  text =' ', width = 20)
        self.endcolumn      = Label(self.tframe,  text =' ', width = 2)

        self.namelabel      = Label(self.tframe,  text = 'Matrix')
        self.elabel         = Label(self.tframe,  text = 'Porosity')
        self.rholabel       = Label(self.tframe,  text = 'Bulk density' )
        self.foclabel       = Label(self.tframe,  text = 'Organic carbon fraction')

        self.rhounit        = Label(self.tframe,  text = u'g/cm\u00B3')

        self.botblankcolumn    = Label(self.frame,  text ='', width = 1)
        self.boteditcolumn     = Label(self.frame,  text =' ', width = 6)
        self.botdelcolumn      = Label(self.frame,  text =' ', width = 6)
        self.botnamecolumn     = Label(self.frame,  text =' ', width = 20)
        self.botecolumn        = Label(self.frame,  text =' ', width = 15)
        self.botrhocolumn      = Label(self.frame,  text =' ', width = 15)
        self.botfoccolumn      = Label(self.frame,  text =' ', width = 20)
        self.botendcolumn      = Label(self.frame,  text =' ', width = 2)

        self.blank1 = Label(self.bframe, text = ' ')
        self.blank2 = Label(self.bframe, text = ' ')
        self.blank3 = Label(self.bframe, text = ' ')

        self.addwidget  = Button(self.bframe, text = 'Add materials', command = self.addmatrix,  width = 20)
        self.loadwidget = Button(self.bframe, text = 'Load materials', command = self.loadmatrix,  width = 20)
        self.mixwidget  = Button(self.bframe, text = 'Create mixtures',  command = self.addmixture,  width = 20)

        #show the widgets on the grid
        self.instructions.grid(  row    = 0, column = 0, sticky = 'W',  padx = 8, columnspan = 6,)

        self.blankcolumn.grid(   row    = 1, column = 0, sticky = 'WE', padx = 1, pady = 1)
        self.editcolumn.grid(    row    = 1, column = 1, sticky = 'WE', padx = 1, pady = 1)
        self.delcolumn.grid(     row    = 1, column = 2, sticky = 'WE', padx = 1, pady = 1)
        self.namecolumn.grid(    row    = 1, column = 3, sticky = 'WE', padx = 1, pady = 1)
        self.ecolumn.grid(       row    = 1, column = 4, sticky = 'WE', padx = 1, pady = 1)
        self.rhocolumn.grid(     row    = 1, column = 5, sticky = 'WE', padx = 1, pady = 1)
        self.foccolumn.grid(     row    = 1, column = 6, sticky = 'WE', padx = 1, pady = 1)

        self.namelabel.grid(     row    = 2, column = 3, sticky = 'WE', padx = 1, pady = 1)
        self.elabel.grid  (      row    = 2, column = 4, sticky = 'WE', padx = 1, pady = 1)
        self.rholabel.grid (     row    = 2, column = 5, sticky = 'WE', padx = 1, pady = 1)
        self.foclabel.grid (     row    = 2, column = 6, sticky = 'WE', padx = 1, pady = 1)

        self.rhounit.grid (      row    = 3, column = 5, sticky = 'WE', padx = 1, pady = 1)

        self.updatematrices()


    def updatematrices(self):

        self.addwidget.grid_forget()
        self.loadwidget.grid_forget()
        self.blank1.grid_forget()

        self.botblankcolumn.grid_forget()
        self.boteditcolumn.grid_forget()
        self.botdelcolumn.grid_forget()
        self.botnamecolumn.grid_forget()
        self.botecolumn.grid_forget()
        self.botrhocolumn.grid_forget()
        self.botfoccolumn.grid_forget()

        material_list = self.materials.keys()
        for matrix in self.matrices:
            if len(matrix.components) == 1 :
                try: material_list.remove(matrix.name)
                except: pass

        row = 4

        for matrix in self.matrices:
            try: matrix.remove_propertieswidgets()
            except:pass
            matrix.number = self.matrices.index(matrix) + 1
            matrix.propertieswidgets(self.frame, row, self.master)
            row = row + 1

        self.botblankcolumn.grid(   row    = row, column = 0, sticky = 'WE', padx = 1, pady = 1)
        self.boteditcolumn.grid(    row    = row, column = 1, sticky = 'WE', padx = 1, pady = 1)
        self.botdelcolumn.grid(     row    = row, column = 2, sticky = 'WE', padx = 1, pady = 1)
        self.botnamecolumn.grid(    row    = row, column = 3, sticky = 'WE', padx = 1, pady = 1)
        self.botecolumn.grid(       row    = row, column = 4, sticky = 'WE', padx = 1, pady = 1)
        self.botrhocolumn.grid(     row    = row, column = 5, sticky = 'WE', padx = 1, pady = 1)
        self.botfoccolumn.grid(     row    = row, column = 6, sticky = 'WE', padx = 1, pady = 1)

        row = 0
        self.blank1.grid(row = row)
        row = row + 1
        self.blank2.grid(row = row)
        row = row + 1
        self.addwidget.grid(row = row, columnspan = 11)
        row = row + 1
        if len(material_list) > 0:
            self.loadwidget.grid(row = row, columnspan = 11)
            row = row + 1
        self.mixwidget.grid(row = row, columnspan = 11)
        row = row + 1

        self.addwidget.bind('<Return>', self.addmatrix)
        self.mixwidget.bind('<Return>', self.addmixture)
        if self.nmatrices == 0:     self.focusbutton = self.addwidget
        else:                       self.focusbutton = None
        self.master.geometry()
        self.master.center()

    def addmixture(self, default = None):

        self.nmatrices = self.nmatrices + 1
        self.matrices.append(Matrix(self.nmatrices))

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(MixtureEditor(self.top, self.system, self.matrices[-1], self.matrices, self.materials, editflag = 0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.matrices[-1].get_matrix(self.top.window)
            else:
                self.matrices.remove(self.matrices[-1])
                self.nmatrices = self.nmatrices - 1

            for component in self.matrices[-1].components:
                for matrix in self.matrices[:-1]:
                    for sub_component in matrix.components:
                        if sub_component.name == component.name:
                            sub_component.e   = component.e
                            sub_component.rho = component.rho
                            sub_component.foc = component.foc

                    if len(matrix.components) > 1:
                        e         = 0
                        rho       = 0
                        moc       = 0
                        foc       = 0
                        fractions = 0

                        for component in matrix.components:

                            fractions = fractions + component.fraction
                            e         = e         + component.fraction * component.e
                            rho       = rho       + component.fraction * component.rho
                            moc       = moc       + component.fraction * component.rho * component.foc

                        foc = moc/rho

                        matrix.e = (round(e,2))
                        matrix.rho = (round(rho,3))
                        matrix.foc = (round(foc,3))

                    else:
                        matrix.e          = matrix.components[-1].e
                        matrix.rho        = matrix.components[-1].rho
                        matrix.foc        = matrix.components[-1].foc

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatematrices()

    def addmatrix(self, default = None):

        self.nmatrices = self.nmatrices + 1
        self.matrices.append(Matrix(self.nmatrices))

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(MatrixEditor(self.top, self.system, self.matrices[-1], self.matrices, self.materials, editflag = 0, newflag = 1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.matrices[-1].get_matrix(self.top.window)
            else:
                self.matrices.remove(self.matrices[-1])
                self.nmatrices = self.nmatrices - 1

            if len(self.matrices) > 0:
                for component in self.matrices[-1].components:
                    for matrix in self.matrices[:-1]:
                        for sub_component in matrix.components:
                            if sub_component.name == component.name:
                                sub_component.e   = component.e
                                sub_component.rho = component.rho
                                sub_component.foc = component.foc

                        if len(matrix.components) > 1:
                            e         = 0
                            rho       = 0
                            moc       = 0
                            foc       = 0
                            fractions = 0

                            for component in matrix.components:

                                fractions = fractions + component.fraction
                                e         = e         + component.fraction * component.e
                                rho       = rho       + component.fraction * component.rho
                                moc       = moc       + component.fraction * component.rho * component.foc

                            foc = moc/rho

                            matrix.e = (round(e,2))
                            matrix.rho = (round(rho,3))
                            matrix.foc = (round(foc,3))

                        else:
                            matrix.e          = matrix.components[-1].e
                            matrix.rho        = matrix.components[-1].rho
                            matrix.foc        = matrix.components[-1].foc

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatematrices()

    def loadmatrix(self, default = None):

        self.nmatrices = self.nmatrices + 1
        self.matrices.append(Matrix(self.nmatrices))

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(MatrixEditor(self.top, self.system, self.matrices[-1], self.matrices, self.materials, editflag = 0, newflag = 0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.matrices[-1].get_matrix(self.top.window)
            else:
                self.matrices.remove(self.matrices[-1])
                self.nmatrices = self.nmatrices - 1

            if len(self.matrices) > 0:
                for component in self.matrices[-1].components:
                    for matrix in self.matrices[:-1]:
                        for sub_component in matrix.components:
                            if sub_component.name == component.name:
                                sub_component.e   = component.e
                                sub_component.rho = component.rho
                                sub_component.foc = component.foc

                        if len(matrix.components) > 1:
                            e         = 0
                            rho       = 0
                            moc       = 0
                            foc       = 0
                            fractions = 0

                            for component in matrix.components:

                                fractions = fractions + component.fraction
                                e         = e         + component.fraction * component.e
                                rho       = rho       + component.fraction * component.rho
                                moc       = moc       + component.fraction * component.rho * component.foc

                            foc = moc/rho

                            matrix.e = (round(e,2))
                            matrix.rho = (round(rho,3))
                            matrix.foc = (round(foc,3))

                        else:
                            matrix.e          = matrix.components[-1].e
                            matrix.rho        = matrix.components[-1].rho
                            matrix.foc        = matrix.components[-1].foc

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatematrices()

    def editmatrix(self, number):

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            if len(self.matrices[number - 1].components) < 2: self.top.make_window(MatrixEditor(self.top, self.system, self.matrices[number-1], self.matrices, self.materials, editflag = 1, newflag = 0))
            else:                                             self.top.make_window(MixtureEditor(self.top, self.system,self.matrices[number-1], self.matrices, self.materials, editflag = 1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.matrices[number-1].get_matrix(self.top.window)

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatematrices()

    def deletematrix(self, number):

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(MatrixDeleter(self.top, self.system, self.matrices[number-1]))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.matrices[number-1].remove_propertieswidgets()
                self.matrices.remove(self.matrices[number-1])
                self.nmatrices = self.nmatrices - 1

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatematrices()


    def error_check(self):

        error = 0

        if self.nmatrices == 0: error = 1

        return error

    def warning(self):

        tkmb.showerror(title = self.version, message = 'No matrices has been selected, please add matrices by pressing the button "Add materials" or the button "Add mixture"')
        self.focusbutton = None
        self.master.tk.lift()
Example #48
0
class pump_ui(object):
    def __init__(self):
        master = Tk()
        master.style = ttk.Style()
        master.style.theme_use("default")
        master.config(bg=background_colour)
        master.resizable(
            0, 0
        )  # Disable resizing the UI to prevent having to make widget placing dynamic
        master.winfo_toplevel().title(frame_title)
        master.iconbitmap("bitcoin.ico")

        # Create pumper assistant to store data on the current BTC and alt holdings.
        self.pumper = pumper()

        self.create_title(master)
        self.create_api_info(master, previous_row=0)
        self.create_auto_sell(master, previous_row=3)
        self.create_stop_loss(master, previous_row=4)
        self.create_order_type(master, previous_row=6)
        self.create_fee_type(master, previous_row=7)
        self.create_btc_balance_picker(master, previous_row=8)
        self.create_alt_ticker(master, previous_row=10)
        self.create_pump_and_sell_buttons(master, previous_row=11)
        self.create_current_profit(master, previous_row=12)

        self.create_output_box(master, rightmost_column=1)

        # Can hardcode API key and Secret
        #self.api_key_entry.delete(0,END)
        #self.api_key_entry.insert(0,"KEY")
        #self.api_key_entry.config(state=DISABLED)
        #self.api_secret_entry.delete(0, END)
        #self.api_secret_entry.insert(0, "SECRET")
        #self.api_secret_entry.config(state=DISABLED)

        # Display the UI, this can only be called once per program.
        # Nothing in the main Python script will be run after creating the UI because of this.
        master.mainloop()

    def create_title(self, master, previous_row=-1, previous_column=-1):
        empty = Label(master, text=frame_title)
        empty.grid(row=previous_row + 1,
                   column=previous_column + 2,
                   columnspan=1)
        empty.config(bg=background_colour, fg=label_font_colour)

    def create_api_info(self, master, previous_row=-1, previous_column=-1):
        api_key_lbl = Label(master, text="API Key:")
        api_key_lbl.grid(row=previous_row + 1,
                         column=previous_column + 1,
                         columnspan=1,
                         sticky=E,
                         padx=(3, 0))
        api_key_lbl.config(bg=background_colour, fg=label_font_colour)

        self.api_key_entry = Entry(master,
                                   highlightthickness=0,
                                   bd=0,
                                   width=21,
                                   show="*")
        self.api_key_entry.config(borderwidth=2, relief=default_relief)
        self.api_key_entry.grid(row=previous_row + 1,
                                column=previous_column + 2)

        api_secret_lbl = Label(master, text="API Secret:")
        api_secret_lbl.grid(row=previous_row + 2,
                            column=previous_column + 1,
                            columnspan=1,
                            sticky=E,
                            padx=(3, 0))
        api_secret_lbl.config(bg=background_colour, fg=label_font_colour)

        self.api_secret_entry = Entry(master,
                                      highlightthickness=0,
                                      bd=0,
                                      width=21,
                                      show="*")
        self.api_secret_entry.config(borderwidth=2, relief=default_relief)
        self.api_secret_entry.grid(row=previous_row + 2,
                                   column=previous_column + 2)

        self.api_connect_btn = Button(master,
                                      text="Connect To Binance",
                                      command=self.on_connect_api)
        self.api_connect_btn.grid(row=previous_row + 3,
                                  column=previous_column + 2,
                                  columnspan=1,
                                  sticky=W + E,
                                  padx=10,
                                  pady=(0, 3))
        self.api_connect_btn.config(highlightbackground=background_colour)

    def create_auto_sell(self, master, previous_row=-1, previous_column=-1):
        auto_sell_lbl = Label(master, text="Auto Sell (%):")
        auto_sell_lbl.grid(row=previous_row + 1,
                           column=previous_column + 1,
                           columnspan=1,
                           sticky=E,
                           padx=(3, 0))
        auto_sell_lbl.config(bg=background_colour, fg=label_font_colour)

        self.auto_sell_spinbox = Spinbox(master,
                                         from_=1.0,
                                         to=300.0,
                                         increment=1.0,
                                         highlightbackground=background_colour)
        self.auto_sell_spinbox.config(borderwidth=2, relief=default_relief)
        self.auto_sell_spinbox.grid(row=previous_row + 1,
                                    column=previous_column + 2)
        self.auto_sell_spinbox.delete(0, "end")
        self.auto_sell_spinbox.insert(0, 50)

    def create_stop_loss(self, master, previous_row=-1, previous_column=-1):
        stop_loss_lbl = Label(master, text="Stop Loss (%):")
        stop_loss_lbl.grid(row=previous_row + 1,
                           column=previous_column + 1,
                           columnspan=1,
                           sticky=E,
                           padx=(3, 0))
        stop_loss_lbl.config(bg=background_colour, fg=label_font_colour)

        self.stop_loss_spinbox = Spinbox(master,
                                         from_=-100.0,
                                         to=-10.0,
                                         increment=1.0,
                                         highlightbackground=background_colour)
        self.stop_loss_spinbox.config(borderwidth=2, relief=default_relief)
        self.stop_loss_spinbox.grid(row=previous_row + 1,
                                    column=previous_column + 2)
        self.stop_loss_spinbox.delete(0, "end")
        self.stop_loss_spinbox.insert(0, -10)

    def create_btc_balance_picker(self,
                                  master,
                                  previous_row=-1,
                                  previous_column=-1):
        self.btc_balance_str = StringVar()
        btc_balance_lbl = Label(master, textvar=self.btc_balance_str)
        btc_balance_lbl.grid(row=previous_row + 1,
                             column=previous_column + 1,
                             columnspan=2,
                             sticky=W + E,
                             padx=(3, 0))
        btc_balance_lbl.config(bg=background_colour, fg=label_font_colour)
        self.set_available_btc_balance(Decimal(0))

        btc_to_use_label = Label(master,
                                 text="BTC to spend:",
                                 bg=background_colour,
                                 fg=label_font_colour)
        btc_to_use_label.grid(row=previous_row + 2,
                              column=previous_column + 1,
                              sticky=E,
                              padx=(3, 0))

        self.btc_to_use_spinbox = Spinbox(
            master,
            from_=minimum_trade,
            to=minimum_trade,
            increment=btc_to_use_increment,
            highlightbackground=background_colour)
        self.btc_to_use_spinbox.config(borderwidth=2, relief=default_relief)
        self.btc_to_use_spinbox.grid(row=previous_row + 2,
                                     column=previous_column + 2)

    def create_order_type(self, master, previous_row=-1, previous_column=-1):
        order_type_lbl = Label(master, text="Entry Type:")
        order_type_lbl.grid(row=previous_row + 1,
                            column=previous_column + 1,
                            sticky=E,
                            padx=(3, 0))
        order_type_lbl.config(bg=background_colour, fg=label_font_colour)

        self.is_entry_market = True

        def change_order_type(*args):
            self.is_entry_market = (self.order_type.get() == "Market Buy  \/")

        self.order_type = StringVar()
        self.order_type.trace(
            "w", change_order_type
        )  # Reduces how much work is done when the pump starts
        choices = {"Market Buy  \/", "Limit Buy     \/"}
        self.entry_type_option_menu = OptionMenu(master, self.order_type,
                                                 *choices)
        self.entry_type_option_menu.grid(row=previous_row + 1,
                                         column=previous_column + 2,
                                         sticky=W + E,
                                         padx=8)
        self.entry_type_option_menu.config(highlightthickness=0)
        self.entry_type_option_menu.configure(indicatoron=0)
        self.order_type.set("Market Buy  \/")

    def create_fee_type(self, master, previous_row=-1, previous_column=-1):
        fee_type_lbl = Label(master, text="Fee Type:")
        fee_type_lbl.grid(row=previous_row + 1,
                          column=previous_column + 1,
                          sticky=E,
                          padx=(3, 0))
        fee_type_lbl.config(bg=background_colour, fg=label_font_colour)

        self.is_using_bnb = True

        def change_fee_type(*args):
            self.is_using_bnb = (
                self.order_type.get() == "Binance Coin (BNB) \/")

        self.fee_type = StringVar()
        self.fee_type.trace(
            "w", change_fee_type
        )  # Reduces how much work is done when the pump starts
        choices = {"Binance Coin (BNB) \/", "0.1% Of All Trades    \/"}
        self.fee_type_option_menu = OptionMenu(master, self.fee_type, *choices)
        self.fee_type_option_menu.grid(row=previous_row + 1,
                                       column=previous_column + 2,
                                       sticky=W + E,
                                       padx=8)
        self.fee_type_option_menu.config(highlightthickness=0)
        self.fee_type_option_menu.configure(indicatoron=0)
        self.fee_type.set("Binance Coin (BNB) \/")

    def create_pump_and_sell_buttons(self,
                                     master,
                                     previous_row=-1,
                                     previous_column=-1):
        # Manual sell button can only be activated after initiating a pump.
        self.manual_sell_btn = Button(master,
                                      text="Sell",
                                      state=DISABLED,
                                      command=self.on_manual_sell)
        self.manual_sell_btn.grid(row=previous_row + 1,
                                  column=previous_column + 1,
                                  sticky=W + E,
                                  padx=(3, 0))
        self.manual_sell_btn.config(highlightbackground=background_colour)

        self.pump_btn = Button(master, text="Pump", command=self.on_pump)
        self.pump_btn.grid(row=previous_row + 1,
                           column=previous_column + 2,
                           sticky=W + E,
                           padx=8)
        self.pump_btn.config(highlightbackground=background_colour,
                             state=DISABLED)

    def create_alt_ticker(self, master, previous_row=-1, previous_column=-1):
        ticker_lbl = Label(master, text="Ticker To Pump:")
        ticker_lbl.grid(row=previous_row + 1,
                        column=previous_column + 1,
                        columnspan=1,
                        sticky=E,
                        padx=(3, 0),
                        pady=(0, 8))
        ticker_lbl.config(bg=background_colour, fg=label_font_colour)

        self.ticker_entry = Entry(master, highlightthickness=0, bd=0, width=21)
        self.ticker_entry.config(borderwidth=2, relief=default_relief)
        self.ticker_entry.grid(row=previous_row + 1,
                               column=previous_column + 2,
                               pady=8)
        self.ticker_entry.bind('<Return>', self.on_pump_shortcut)

    def create_current_profit(self,
                              master,
                              previous_row=-1,
                              previous_column=-1):
        self.current_profit_str = StringVar()
        current_profit_lbl = Label(master, textvar=self.current_profit_str)
        current_profit_lbl.grid(row=previous_row + 1,
                                column=previous_column + 1,
                                columnspan=2,
                                sticky=W + E,
                                padx=3,
                                pady=(0, 3))
        current_profit_lbl.config(bg=background_colour, fg=label_font_colour)
        self.current_profit_str.set("Current Profit: 0%")

    def create_output_box(self, master, rightmost_column):
        self.pump_output = StringVar()
        console_lbl = Label(master,
                            textvar=self.pump_output,
                            borderwidth=2,
                            relief=default_relief,
                            anchor=N)
        console_lbl.grid(row=0,
                         column=rightmost_column + 1,
                         columnspan=1,
                         rowspan=14,
                         padx=(10, 0),
                         pady=0)
        console_lbl.config(width=50,
                           height=22,
                           bg="black",
                           font=Font(family="Courier", size=9),
                           fg="white")
        self.lines = 0

    def disable_pre_pump_options(self):
        # Change the buttons that can be clicked to prevent the user
        # from trying to pump multiple coins with one bot.
        self.manual_sell_btn.config(state=NORMAL)
        self.pump_btn.config(state=DISABLED)
        self.btc_to_use_spinbox.config(state=DISABLED)
        self.ticker_entry.config(state=DISABLED)
        self.auto_sell_spinbox.config(state=DISABLED)
        self.stop_loss_spinbox.config(state=DISABLED)
        self.api_key_entry.config(
            state=DISABLED)  # Comment out if hardcoding key
        self.api_secret_entry.config(
            state=DISABLED)  # Comment out if hardcoding secret
        self.api_connect_btn.config(state=DISABLED)
        self.entry_type_option_menu.config(state=DISABLED)
        self.fee_type_option_menu.config(state=DISABLED)

    def enable_pump_options(self):
        # Change the buttons that can be clicked to prevent the user
        # from trying to pump multiple coins with one bot.
        self.manual_sell_btn.config(state=DISABLED)
        self.pump_btn.config(state=NORMAL)
        self.btc_to_use_spinbox.config(state=NORMAL)
        self.ticker_entry.config(state=NORMAL)
        self.auto_sell_spinbox.config(state=NORMAL)
        self.stop_loss_spinbox.config(state=NORMAL)
        self.api_key_entry.config(
            state=NORMAL)  # Comment out if hardcoding key
        self.api_secret_entry.config(
            state=NORMAL)  # Comment out if hardcoding secret
        self.api_connect_btn.config(state=NORMAL)
        self.entry_type_option_menu.config(state=NORMAL)
        self.fee_type_option_menu.config(state=NORMAL)

    def set_available_btc_balance(self, btc_balance):
        self.pumper.btc_balance = btc_balance
        self.btc_balance_str.set("Available Balance: " +
                                 readable_btc_balance(btc_balance))

    def set_current_profit(self, current_profit):
        self.current_profit_str.set(
            "Current Profit: " +
            '{0:.3f}'.format(round(current_profit * Decimal(100), 3)) + "%")

    def write_to_console(self, line):
        self.lines += 1
        if self.lines > max_lines_in_console:
            i = self.pump_output.get().index('\n')
            self.pump_output.set(self.pump_output.get()[i + 1:] + "\n" + line)
        elif self.lines == 1:
            self.pump_output.set(line)
        else:
            self.pump_output.set(self.pump_output.get() + "\n" + line)

    #### Button Behaviour ####
    def on_pump(self):
        try:
            api = self.api
            btc_to_use = Decimal(self.btc_to_use_spinbox.get())
        except InvalidOperation:
            # The BTC to spend box is empty.
            self.write_to_console("Stop!")
            self.write_to_console("BTC to spend cannot be empty.")
            return
        except AttributeError:
            # There is no API object.
            self.write_to_console(
                "You need to connect to Binance before pumping.")
            return

        if btc_to_use >= minimum_trade:
            if btc_to_use <= self.pumper.btc_balance:
                target_profit_percentage = Decimal(
                    float(self.auto_sell_spinbox.get()) / 100.0)

                # Validate auto-sell and stop loss
                if target_profit_percentage <= Decimal(0):
                    self.write_to_console("Auto sell has to be positive.")
                    return
                if Decimal(self.stop_loss_spinbox.get()) >= Decimal(0):
                    self.write_to_console("Stop loss has to be negative.")
                    return

                ticker = self.ticker_entry.get().upper()

                # Empty strings are False in Python
                if ticker:
                    full_ticker = api.full_ticker_for(ticker)

                    try:
                        alt = self.api.get_ticker(symbol=full_ticker)
                    except BinanceAPIException, e:
                        logging.debug(str(e))
                        self.write_to_console("Invalid ticker.")
                        return

                    alt_value = Decimal(alt["askPrice"])

                    # Used in console output
                    decimal_points = minimum_decimals_in_quantity.get(
                        full_ticker, 0)
                    self.pumper.decimal_points_in_alt = decimal_points

                    self.pumper.set_up(btc_to_use, target_profit_percentage,
                                       alt_value, ticker)
                    if self.is_entry_market:
                        self.pumper.alt_holdings = api.market_buy(
                            self.pumper.btc_to_use, full_ticker,
                            self.is_using_bnb)
                        self.write_to_console(
                            "Bought " + readable_alt_balance(
                                decimal_points, pumper=self.pumper) +
                            " with " + readable_btc_balance(btc_to_use) + ".")
                    else:
                        highest_bid = Decimal(alt["bidPrice"])

                        if alt_value - highest_bid <= Decimal(0.00000001):
                            to_bid = highest_bid
                        else:
                            # Bid between the highest bid and the lowest ask for the best odds of being filled.
                            to_bid = (alt_value -
                                      highest_bid) / 2 + highest_bid
                            to_bid = Decimal(
                                floor(to_bid * Decimal(100000000.0))
                            ) / Decimal(100000000.0)
                        self.pumper.starting_alt_value = to_bid

                        expected = api.limit_buy(
                            btc_to_alt(btc_to_use, alt_value), pumper,
                            full_ticker, to_bid, self.is_using_bnb)
                        self.write_to_console("Buying " + readable_alt_balance(
                            decimal_points, alt_amount=expected, ticker=ticker
                        ) + " for " + readable_btc_balance(btc_to_use) + ".")
                        self.write_to_console(
                            "This is a limit order, it may not get filled.")

                    self.disable_pre_pump_options()
                    self.set_stop_loss()
                    self.start_monitoring_orderbook(full_ticker)
                else:
                    # The user is trying to trade with more than they actually have.
                    self.write_to_console("You did not enter a ticker.")
            else:
                # The user is trying to trade with more than they actually have.
                self.write_to_console("Stop!")
                self.write_to_console(
                    "You are trying to spend more BTC than you have.")
        else:
Example #49
0
class Interface:

    def __init__(self, master):



        serverPort = 12000
        clientAddress = '255.255.255.255'
        serverSocket = socket(AF_INET, SOCK_DGRAM)
        serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        serverSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        serverSocket.bind(('', serverPort))

        self.master = master
        master.title("              DDOS ATTACK - HTTP FLOOD")

        self.IP = None

        self.message = "TYPE IP TO BE ATTACKED :"
        self.label_text = StringVar()
        self.label_text.set(self.message)
        self.label = Label(master, textvariable=self.label_text,font=(None, 13),background ="black",fg ="white")

        vcmd = master.register(self.validate) # we have to wrap the command



        self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
        self.entry.configure(insertwidth=2,highlightbackground= "black")


        validate_ip_args = partial(self.validate_IP, serverSocket, clientAddress, serverPort)
        self.attack_button = Button(master, text="Start Attack", command=validate_ip_args, height = 2, width = 20,  font=(None, 13), fg ="white", background ="black",highlightbackground= "black")

        stop_attack_args = partial(self.stop_attack, serverSocket, clientAddress, serverPort)
        self.stop_button = Button(master, text="Stop Attack", command=stop_attack_args, state=DISABLED, height = 2, width = 20, font=(None, 13), fg ="white", background = "black",highlightbackground= "black")


        self.label.grid(row=0, column=0, columnspan=2, sticky=W+E,  pady=20)
        self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E, pady= 8)
        self.attack_button.grid(row=2, column=0, padx= 5,pady= 8)
        self.stop_button.grid(row=2, column=1, padx= 5, pady= 8)


    def validate(self, new_text):
        if not new_text: # the field is being cleablack
            self.IP = None
            return True
        else:
            IP = new_text
            self.IP=IP
            return True

    def validate_IP(self, serverSocket, clientAddress, serverPort):

        if (is_valid_ipv4(str(self.IP))):
            self.message = "VALID IP, CONTACTING SLAVES!"
            serverSocket.sendto("S/"+self.IP, (clientAddress, serverPort))
            self.attack_button.configure(state=DISABLED)
            self.stop_button.configure(state=NORMAL)
        else:
            self.message = "INVALID IP, TRY AGAIN"

        if self.IP is None:
            self.message = "TYPE IP TO BE ATTACKED :"

        self.label_text.set(self.message)

    def stop_attack(self, serverSocket, clientAddress, serverPort):
        self.entry.delete(0, END)

        self.IP = None
        serverSocket.sendto("B/", (clientAddress, serverPort))

        self.message = "TYPE IP TO BE ATTACKED :"
        self.label_text.set(self.message)

        self.attack_button.configure(state=NORMAL)
        self.stop_button.configure(state=DISABLED)
Example #50
0
def start():
    menu = Tk()
    button1 = Button(menu, text="Add New Recipe", command=createRecipe)
    button1.grid(row=0, column=0)
    button2 = Button(menu, text="Export Recipe")
    button2.grid(row=1, column=0)
    button3 = Button(menu, text="My Recipes", command=recipebox)
    button3.grid(row=2, column=0)
    button4 = Button(menu, text="Recently Viewed")
    button4.grid(row=3, column=0)
    button5 = Button(menu, text="Favourites", command=FavsWnd)
    button5.grid(row=0, column=5)
    button6 = Button(menu, text="Grocery List", command=openGrocery)
    button6.grid(row=0, column=2)
    button7 = Button(menu, text="Hungry?")
    button7.grid(row=0, column=3)
    search = Label(menu, text="Search by:")
    search.grid(row=0, column=6)
    filter1 = Button(menu, text="Recipe Name")
    filter1.grid(row=1, column=6)
    filter2 = Button(menu, text="Ingredient")
    filter2.grid(row=2, column=6)
    filter3 = Button(menu, text="User")
    filter3.grid(row=3, column=6)
    button8 = Button(menu, text="Notifications")
    button8.grid(row=0, column=4)
    newsfeed = Label(menu, text="Newsfeed")
    newsfeed.grid(row=0, column=1)
    cookbook = Button(menu, text="Main Cookbook", command=All_recipes)
    cookbook.grid(row=1, column=4)
    Txt = Text(menu, height="20")
    Txt.grid(row=1, column=1)
    menu.mainloop()
Example #51
0
numberOfRegions = 2


def regiones():
    global regionCoord
    regionCoord = regions.funcionRegiones(numberOfRegions)
    print regionCoord


botonregiones = Button(ventana,
                       text="REGIONES",
                       command=regiones,
                       fg="white",
                       bg='red',
                       font=("Helvetica 12 bold"))
botonregiones.grid(row=3, column=1)

######################## LABEL COLOR + FUNC COLOR + BOTON COLOR

labelcolor = Label(ventana,
                   text="Por favor seleccione un rango de color",
                   fg="black",
                   bg="white",
                   font=("Helvetica 12 "))
labelcolor.grid(row=4, column=1)


def color():
    global lower, upper
    import numpy as np
    hMin = 8
Example #52
0
class Database:
    """Opens a window for inputing the properties of a compound."""
    def __init__(self, master, system, database):
        """The constructor method."""

        self.system = system
        self.version = system.version
        self.fonttype = system.fonttype
        self.sfont = get_superfont(self.fonttype)
        self.master = master
        self.tframe = Frame(master.tframe)
        self.frame = Frame(master.frame)
        self.bframe = Frame(master.bframe)
        self.top = None

        self.database = database  #the database of values

        self.exitflag = 0
        self.names = []  #a list of the chemical names

        solids_list = self.database.keys()
        solids_list.sort()

        self.solids_list = solids_list

        self.solids = []
        for solidname in solids_list:
            self.solids.append(Solid(solids_list.index(solidname)))
            self.solids[-1].read_database(self.database[solidname])

    def make_widgets(self):

        self.instructions = Label(
            self.tframe,
            text=
            'Please provide the following fundamental properties for the material:\n'
        )

        self.blankcolumn = Label(self.tframe,
                                 text='',
                                 font='courier 10',
                                 width=1)
        self.editcolumn = Label(self.tframe,
                                text='',
                                font='courier 10',
                                width=6)
        self.delcolumn = Label(self.tframe,
                               text='',
                               font='courier 10',
                               width=6)
        self.numbercolumn = Label(self.tframe,
                                  text='',
                                  font='courier 10',
                                  width=8)
        self.namecolumn = Label(self.tframe,
                                text='',
                                font='courier 10',
                                width=18)
        self.ecolumn = Label(self.tframe, text='', font='courier 10', width=8)
        self.rhocolumn = Label(self.tframe,
                               text='',
                               font='courier 10',
                               width=12)
        self.foccolumn = Label(self.tframe,
                               text='',
                               font='courier 10',
                               width=20)
        self.tortcolumn = Label(self.tframe,
                                text='',
                                font='courier 10',
                                width=18)
        self.sorpcolumn = Label(self.tframe,
                                text='',
                                font='courier 10',
                                width=18)
        self.refcolumn = Label(self.tframe,
                               text='',
                               font='courier 10',
                               width=15)

        self.numberlabel = Label(self.tframe, text='Number')
        self.namelabel = Label(self.tframe, text='Material')
        self.elabel = Label(self.tframe, text='Porosity')
        self.rholabel = Label(self.tframe, text='Bulk density')
        self.foclabel = Label(self.tframe, text='Organic carbon fraction')
        self.tortlabel = Label(self.tframe, text='Tortuosity correction')
        self.sorplabel = Label(self.tframe, text='Sorption isotherms')
        self.reflabel = Label(self.tframe, text='Reference')

        self.rhounitlabel = Label(self.tframe, text=u'g/cm\u00B3')

        self.botblankcolumn = Label(self.frame,
                                    text='',
                                    font='courier 10',
                                    width=1)
        self.boteditcolumn = Label(self.frame,
                                   text='',
                                   font='courier 10',
                                   width=6)
        self.botdelcolumn = Label(self.frame,
                                  text='',
                                  font='courier 10',
                                  width=6)
        self.botnumbercolumn = Label(self.frame,
                                     text='',
                                     font='courier 10',
                                     width=8)
        self.botnamecolumn = Label(self.frame,
                                   text='',
                                   font='courier 10',
                                   width=18)
        self.botecolumn = Label(self.frame,
                                text='',
                                font='courier 10',
                                width=8)
        self.botrhocolumn = Label(self.frame,
                                  text='',
                                  font='courier 10',
                                  width=12)
        self.botfoccolumn = Label(self.frame,
                                  text='',
                                  font='courier 10',
                                  width=20)
        self.bottortcolumn = Label(self.frame,
                                   text='',
                                   font='courier 10',
                                   width=18)
        self.botsorpcolumn = Label(self.frame,
                                   text='',
                                   font='courier 10',
                                   width=18)
        self.botrefcolumn = Label(self.frame,
                                  text='',
                                  font='courier 10',
                                  width=15)

        self.addwidget = Button(self.bframe,
                                text='Add solids',
                                command=self.addsolid,
                                width=20)
        self.savebutton = Button(self.bframe,
                                 text='Save',
                                 width=20,
                                 command=self.save)
        self.importwidget = Button(self.bframe,
                                   text='Import database file',
                                   command=self.importsoliddata,
                                   width=20)
        self.cancelbutton = Button(self.bframe,
                                   text='Cancel',
                                   command=self.cancel,
                                   width=20)

        self.blank1 = Label(self.bframe, text=' ')
        self.blank2 = Label(self.bframe, text=' ')
        self.blank3 = Label(self.bframe, text=' ')

        #show the widgets on the grid (top to bottom and left to right)

        self.instructions.grid(row=0,
                               column=0,
                               columnspan=11,
                               padx=8,
                               sticky='W',
                               pady=10)

        self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1)
        self.editcolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1)
        self.delcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1)
        self.numbercolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1)
        self.namecolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1)
        self.ecolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1)
        self.rhocolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1)
        self.foccolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1)
        self.tortcolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1)
        self.sorpcolumn.grid(row=1, column=9, sticky='WE', padx=1, pady=1)
        self.refcolumn.grid(row=1, column=10, sticky='WE', padx=1, pady=1)

        self.numberlabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1)
        self.namelabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1)
        self.elabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1)
        self.rholabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1)
        self.foclabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1)
        self.tortlabel.grid(row=2, column=8, sticky='WE', padx=1, pady=1)
        self.sorplabel.grid(row=2, column=9, sticky='WE', padx=1, pady=1)
        self.reflabel.grid(row=2, column=10, sticky='WE', padx=1, pady=1)

        self.rhounitlabel.grid(row=3, column=6, sticky='WE', padx=1, pady=1)

        self.updatesolids()

        #Bind the "return key" to the buttons

        self.focusbutton = self.cancelbutton

    def updatesolids(self):

        self.addwidget.grid_forget()
        self.blank1.grid_forget()
        self.blank2.grid_forget()

        self.botblankcolumn.grid_forget()
        self.boteditcolumn.grid_forget()
        self.botdelcolumn.grid_forget()
        self.botnumbercolumn.grid_forget()
        self.botnamecolumn.grid_forget()
        self.botecolumn.grid_forget()
        self.botrhocolumn.grid_forget()
        self.botfoccolumn.grid_forget()
        self.bottortcolumn.grid_forget()
        self.botsorpcolumn.grid_forget()
        self.botrefcolumn.grid_forget()

        namelabellength = 18
        reflabellength = 15

        row = 4
        for solid in self.solids:
            try:
                solid.remove_propertieswidget()
            except:
                pass
            solid.number = self.solids.index(solid) + 1
            solid.propertieswidget(self.frame, row, self.master)
            row = row + 1

            if namelabellength < solid.namelabel.winfo_reqwidth() / 8:
                namelabellength = int(solid.namelabel.winfo_reqwidth() / 8) + 1
            if reflabellength < solid.reflabel.winfo_reqwidth() / 8:
                reflabellength = int(solid.reflabel.winfo_reqwidth() / 8) + 1

        self.namecolumn.config(width=namelabellength)
        self.botnamecolumn.config(width=namelabellength)
        self.refcolumn.config(width=reflabellength)
        self.botrefcolumn.config(width=reflabellength)

        self.botblankcolumn.grid(row=row,
                                 column=0,
                                 sticky='WE',
                                 padx=1,
                                 pady=1)
        self.boteditcolumn.grid(row=row, column=1, sticky='WE', padx=1, pady=1)
        self.botdelcolumn.grid(row=row, column=2, sticky='WE', padx=1, pady=1)
        self.botnumbercolumn.grid(row=row,
                                  column=3,
                                  sticky='WE',
                                  padx=1,
                                  pady=1)
        self.botnamecolumn.grid(row=row, column=4, sticky='WE', padx=1, pady=1)
        self.botecolumn.grid(row=row, column=5, sticky='WE', padx=1, pady=1)
        self.botrhocolumn.grid(row=row, column=6, sticky='WE', padx=1, pady=1)
        self.botfoccolumn.grid(row=row, column=7, sticky='WE', padx=1, pady=1)
        self.bottortcolumn.grid(row=row, column=8, sticky='WE', padx=1, pady=1)
        self.botsorpcolumn.grid(row=row, column=9, sticky='WE', padx=1, pady=1)
        self.botrefcolumn.grid(row=row, column=10, sticky='WE', padx=1, pady=1)
        row = row + 1

        row = 0
        self.blank1.grid(row=row)
        row = row + 1
        self.blank2.grid(row=row)
        row = row + 1
        self.addwidget.grid(row=row, columnspan=11)
        row = row + 1
        self.importwidget.grid(row=row, columnspan=11)
        row = row + 1
        self.savebutton.grid(row=row, columnspan=11)
        row = row + 1
        self.cancelbutton.grid(row=row, columnspan=11)
        row = row + 1
        self.blank3.grid(row=row)

        self.savebutton.bind('<Return>', self.save)
        self.cancelbutton.bind('<Return>', self.cancel)

        self.focusbutton = self.savebutton
        self.master.geometry()

    def addsolid(self):

        self.solids.append(Solid(self.solids[-1].number + 1))

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                SolidDatabaseEditor(self.top,
                                    self.system,
                                    self.solids[-1],
                                    self.solids,
                                    editflag=0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.solids[-1].get_solid(self.top.window)
            else:
                self.solids.remove(self.solids[-1])

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatesolids()

    def editsolid(self, number):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                SolidDatabaseEditor(self.top,
                                    self.system,
                                    self.solids[number - 1],
                                    self.solids,
                                    editflag=1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.solids[number - 1].get_solid(self.top.window)

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatesolids()

    def importsoliddata(self):

        UserPath = os.environ['USERPROFILE']
        Filepath = tkfd.askopenfilename(initialdir=UserPath)

        if Filepath != '':
            data = open(Filepath, 'r')
            database_imported = pickle.load(data)
            data.close()
            if self.top is None:
                self.top = CapSimWindow(master=self.master, buttons=2)
                self.top.make_window(
                    SolidDatabaseImporter(self.top, self.system,
                                          database_imported))
                self.top.tk.mainloop()

                duplicate_name = []

                if self.top.window.cancelflag == 0:
                    error_check = 0
                    for solid in self.top.window.solids:
                        if solid.check == 1:
                            if self.solids_list.count(solid.name_new) == 0:
                                self.solids_list.append(solid.name_new)
                                self.solids.append(
                                    Solid(
                                        self.solids_list.index(
                                            solid.name_new)))
                                self.solids[-1].import_coefficients(solid)
                            else:
                                duplicate_name.append(solid.name_new)
                                error_check = 1

                    error_message = 'The following compound information are duplicated:\n\n'
                    for na in range(len(duplicate_name)):
                        error_message = error_message + '              ' + str(
                            duplicate_name[na]) + ' \n'

                    if error_check == 1:
                        tkmb.showerror(title=self.system.version,
                                       message=error_message)

                if self.top is not None:
                    self.top.destroy()
                    self.top = None

            elif self.top is not None:
                tkmb.showerror(
                    title=self.system.version,
                    message=
                    'Please close the existing parameter input window first.')
                self.top.tk.focus()

        self.updatesolids()

    def deletesolid(self, number):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                SolidDatabaseDeleter(self.top, self.system,
                                     self.solids[number - 1]))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.solids[number - 1].remove_propertieswidget()
                self.solids.remove(self.solids[number - 1])

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatesolids()

    def save(self, event=None):

        self.database = self.write_database()

        self.exitflag = 1
        self.frame.quit()

    def cancel(self, event=None):

        self.exitflag = 1
        self.frame.quit()

    def exit(self, event=None):
        """Exit CapSim."""

        if tkmb.askyesno(self.version,
                         'Do you really want to exit CapSim?') == 1:
            sys.exit()

    def write_database(self):

        soliddatabase = {}
        for solid in self.solids:
            soliddatabase[solid.name] = SolidDatabase(solid.name, solid.number,
                                                      solid.e, solid.rho,
                                                      solid.foc, solid.tort,
                                                      solid.sorp, solid.Ref)

        return soliddatabase
Example #53
0
class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master,
                           validate="key",
                           validatecommand=(vcmd, '%P'))

        self.add_button = Button(master,
                                 text="+",
                                 command=lambda: self.update("add"))
        self.subtract_button = Button(master,
                                      text="-",
                                      command=lambda: self.update("subtract"))
        self.reset_button = Button(master,
                                   text="Reset",
                                   command=lambda: self.update("reset"))

        # LAYOUT

        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)

        self.entry.grid(row=1, column=0, columnspan=3, sticky=W + E)

        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.reset_button.grid(row=2, column=2, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
            return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        else:  # reset
            self.total = 0

        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
class Automailor:
    def __init__(self, master):
        self.master = master
        master.title("AutoMailor")

        # Guest object
        self.guest = Guest()

        # self.total = 0
        # self.entered_number = 0
        #
        # self.total_label_text = IntVar()
        # self.total_label_text.set(self.total)
        #
        # Change words while click "Run" button
        self.my_text = StringVar()
        self.my_text.set("Hello, master!")
        self.my_label = Label(master, textvariable=self.my_text)
        #
        # self.total_label = Label(master, textvariable=self.total_label_text)
        # self.label = Label(master, text="Total:")

        # Label Added
        self.account_label = Label(master, text="Sender account: ")
        self.pwd_label = Label(master, text="Sender password: "******"Mail server port: ")
        self.flag_label = Label(master, text="Replacement flag character: ")
        self.subject_label = Label(master, text="Mail subject: ")
        self.frame_content_label = Label(master, text="Framework words:")
        self.individual_info_label = Label(master, text="Ordered information:")

        # vcmd = master.register(self.validate) # we have to wrap the command
        # self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))

        vcmd2 = master.register(self.validate2)
        self.my_entry = Entry(master,
                              validate="key",
                              validatecommand=(vcmd2, '%P'))

        # Entry added
        self.account_entry = Entry(master)
        self.pwd_entry = Entry(master)
        self.port_entry = Entry(master)
        self.flag_entry = Entry(master)
        self.subject_entry = Entry(master)

        # self.add_button = Button(master, text="+", command=lambda: self.update("add"))
        # self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
        # self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))

        # Button added
        self.upload_button = Button(master,
                                    text="Upload",
                                    command=lambda: self.update("upload"))
        self.run_button = Button(master,
                                 text="Run",
                                 command=lambda: self.update("run"))

        # Text added
        self.frame_content_text = Text(master,
                                       width=30,
                                       height=20,
                                       bg="black",
                                       fg="white")
        self.individual_info_text = Text(master,
                                         width=60,
                                         height=20,
                                         bg="black",
                                         fg="white")

        # LAYOUT

        # self.label.grid(row=0, column=0, sticky=W)
        # self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        # self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E)
        # self.add_button.grid(row=2, column=0)
        # self.subtract_button.grid(row=2, column=1)
        # self.reset_button.grid(row=2, column=2, sticky=W+E)

        # My components layout
        self.account_label.grid(row=3, column=0, sticky=W)
        self.account_entry.grid(row=4, column=0, columnspan=8, sticky=W + E)
        self.pwd_label.grid(row=5, column=0, sticky=W)
        self.pwd_entry.grid(row=6, column=0, columnspan=8, sticky=W + E)
        self.port_label.grid(row=7, column=0, sticky=W)
        self.port_entry.grid(row=8, column=0, columnspan=8, sticky=W + E)
        self.flag_label.grid(row=9, column=0, sticky=W)
        self.flag_entry.grid(row=10, column=0, columnspan=8, sticky=W + E)
        self.subject_label.grid(row=11, column=0, sticky=W)
        self.subject_entry.grid(row=12, column=0, columnspan=8, sticky=W + E)
        self.upload_button.grid(row=13, column=0, sticky=W + E)
        self.run_button.grid(row=13, column=3, sticky=W + E)
        self.my_label.grid(row=14, column=0, columnspan=2, sticky=E)

        self.frame_content_label.grid(row=15, column=0, sticky=W)
        self.frame_content_text.grid(row=16, column=0, sticky=W)

        self.individual_info_label.grid(row=15, column=2, sticky=W)
        self.individual_info_text.grid(row=16, column=2, sticky=W)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
            return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def validate2(self, new_text):
        if not new_text:  # the field is being cleared
            self.my_entry = "Hello, master!"
            return True
        try:
            self.my_text = str(new_text)
            return True
        except ValueError:
            return False

    def transfer(self):
        self.guest.sender = self.account_entry.get()
        self.guest.pwd = self.pwd_entry.get()
        self.guest.flag = self.flag_entry.get()
        self.guest.port_num = self.port_entry.get()
        self.guest.subject = self.subject_entry.get()
        self.guest.host_addr = host_name_match(self.guest.sender)
        self.guest.frame_content = self.frame_content_text.get("1.0", END)
        self.guest.individual_content = self.individual_info_text.get(
            "1.0", END)

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        elif method == "reset":
            self.total = 0
        elif method == "upload":
            self.transfer()
            print self.guest
        else:  # run
            print "Running the program"
            self.my_text.set("Send emails automatically!")
            self.guest.run()
Example #55
0
    def __init__(self, master):

        self.fname = ""
        #global variables
        self.t1 = StringVar()
        self.t2 = StringVar()
        self.t3 = StringVar()
        self.t4 = StringVar()
        self.t5 = StringVar()
        self.t6 = StringVar()
        self.t7 = StringVar()
        self.t8 = StringVar()
        self.t9 = StringVar()
        self.t10 = StringVar()
        self.t11 = StringVar()
        self.t12 = StringVar()
        self.t13 = StringVar()
        self.t14 = StringVar()
        self.t15 = StringVar()
        self.t16 = StringVar()
        self.t17 = StringVar()
        self.t18 = StringVar()
        self.t19 = StringVar()
        self.t20 = StringVar()
        self.t21 = StringVar()
        self.t22 = StringVar()
        self.t23 = StringVar()
        self.t24 = StringVar()
        self.t25 = StringVar()
        self.t26 = StringVar()
        self.t27 = StringVar()
        self.t28 = StringVar()
        self.t29 = StringVar()
        self.t30 = StringVar()
        self.t31 = StringVar()
        self.t32 = StringVar()
        self.t33 = StringVar()
        self.t34 = StringVar()

        self.var1 = StringVar()
        self.var2 = StringVar()
        self.var3 = StringVar()
        self.var4 = StringVar()
        self.var5 = StringVar()
        self.var6 = StringVar()
        self.var7 = StringVar()
        self.var8 = StringVar()
        self.var9 = StringVar()
        self.var10 = StringVar()
        self.var11 = StringVar()
        self.var12 = StringVar()
        self.var13 = StringVar()
        self.var14 = StringVar()
        self.var15 = StringVar()
        self.var16 = StringVar()
        self.var17 = StringVar()
        self.var18 = StringVar()
        self.var19 = StringVar()
        self.var20 = StringVar()
        self.var21 = StringVar()
        self.var22 = StringVar()
        self.var23 = StringVar()
        self.var24 = StringVar()
        self.var25 = StringVar()
        self.var26 = StringVar()
        self.var27 = StringVar()
        self.var28 = StringVar()
        self.var29 = StringVar()
        self.var30 = StringVar()
        self.var31 = StringVar()
        self.var32 = StringVar()
        self.var33 = StringVar()
        self.var34 = StringVar()
        #end

        mymaster = Frame(master, name='mymaster')  # create Frame in "root"
        mymaster.pack(fill=BOTH)
        #min and max size of window
        #master.minsize(width=900, height=900)
        #master.maxsize(width=750, height=470)
        #end

        #title of window
        master.title("Aircrack-ng")
        #end

        #for the style of fonts
        self.customFont = tkFont.Font(family="Helvetica", size=12)
        self.myfont = tkFont.Font(family="Helvetica", size=10)
        self.myfont2 = tkFont.Font(family="Helvetica", size=8)
        self.headerfont = tkFont.Font(family="Helvetica",
                                      size=15,
                                      underline=True)
        self.myfontnew = tkFont.Font(family="Helvetica",
                                     size=11,
                                     underline=True)
        #end

        nb = Notebook(mymaster, name='nb')  # create Notebook in "master"
        nb.pack(fill=BOTH, padx=2, pady=3)  # fill "master" but pad sides
        #content frame
        self.frame_content = Frame(nb,
                                   name="frame_content",
                                   bg="lightsteelblue")
        self.frame_content.pack(fill=BOTH, side=TOP, expand=True)
        nb.add(self.frame_content, text="Filter-1")  # add tab to Notebook

        # repeat for each tab
        self.frame_content2 = Frame(nb,
                                    name='frame_content2',
                                    bg="lightsteelblue")
        nb.add(self.frame_content2, text="Filter-2")
        self.frame_content3 = Frame(nb,
                                    name='frame_content3',
                                    bg="lightsteelblue")
        nb.add(self.frame_content3, text="Filter-3")
        self.frame_content4 = Frame(nb,
                                    name='frame_content4',
                                    bg="lightsteelblue")
        nb.add(self.frame_content4, text="Filter-4")
        self.frame_content6 = Frame(nb,
                                    name='frame_content6',
                                    bg="lightsteelblue")
        nb.add(self.frame_content6, text="Filter-5")
        self.frame_content7 = Frame(nb,
                                    name='frame_content7',
                                    bg="lightsteelblue")
        nb.add(self.frame_content7, text="Detect Devices")
        self.frame_content5 = Frame(nb,
                                    name='frame_content5',
                                    bg="lightsteelblue")
        nb.add(self.frame_content5, text="output")

        #End

        #frame content 7
        Label(self.frame_content7,
              text='Aircrack-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        btndetect = Button(self.frame_content7,
                           text='Detect',
                           fg="cornflowerblue",
                           command=self.canvas_detect,
                           height=2,
                           width=15,
                           font=self.customFont).grid(row=1,
                                                      column=0,
                                                      padx=5,
                                                      pady=5)

        btndbrowse = Button(self.frame_content7,
                            text='Attach File',
                            fg="cornflowerblue",
                            command=self.browse_file,
                            height=2,
                            width=15,
                            font=self.customFont).grid(row=3,
                                                       column=0,
                                                       padx=5,
                                                       pady=5)
        self.lilnew1 = Listbox(self.frame_content7,
                               bg="black",
                               fg="firebrick",
                               font=self.myfont,
                               selectmode=SINGLE,
                               width=30,
                               height=15)
        self.lilnew1.grid(row=1, column=1, rowspan=3)
        #End

        Label(self.frame_content,
              text='Aircrack-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        Label(self.frame_content,
              text='Options :',
              font=self.myfontnew,
              bg="midnightblue",
              fg="deepskyblue").grid(row=1, column=1)
        #Button(self.frame_content, text = 'ivs', command =self.canvas_detect, height=2, width=15, font=self.customFont).grid(row = 2, column = 0, padx = 5, pady = 5)
        #Button(self.frame_content, text = 'gpsd', command =self.canvas_detect, height=2, width=15, font=self.customFont).grid(row = 2, column = 1, padx = 5, pady = 5)
        #Button(self.frame_content, text = 'write', command =self.canvas_detect, height=2, width=15, font=self.customFont).grid(row = 2, column = 2, padx = 5, pady = 5)
        #command Listbox
        Label(self.frame_content5,
              text='Edit Command From Here',
              font=self.myfontnew,
              bg="midnightblue",
              fg="deepskyblue",
              justify=LEFT).grid(row=0, column=0)
        TextCommandBox = Text(self.frame_content5, height=5, width=30)
        TextCommandBox.grid(row=1, column=0, padx=5, pady=5)
        self.output = Text(self.frame_content5,
                           bg="black",
                           fg="firebrick",
                           font=self.myfont,
                           height=20,
                           width=42)
        self.output.grid(row=0, column=1, padx=50, pady=5, rowspan=3)
        btnsubmit = Button(self.frame_content5,
                           width=15,
                           height=2,
                           text="Get Result",
                           fg="cornflowerblue",
                           command=self.mycallback)
        btnsubmit.grid(row=2, column=0)
        btnclear = Button(self.frame_content5,
                          width=15,
                          height=2,
                          text="Clear Output",
                          fg="cornflowerblue",
                          command=self.clearoutput)
        btnclear.grid(row=3, column=0)
        #end
        self.C1 = Checkbutton(self.frame_content, text = "-a", fg="deepskyblue", \
                 onvalue = "-a", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var1)
        self.C1.grid(row=2, column=0, padx=5, pady=5)
        self.t1 = Text(self.frame_content, height=1, width=20)
        self.t1.grid(row=2, column=1, padx=5, pady=5)
        l1 = Label(
            self.frame_content,
            text=': Force attack mode (1 = static WEP, 2 = WPA/WPA2-PSK).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=2, column=2, padx=5, pady=5)

        self.C2 = Checkbutton(self.frame_content, text = "-b", fg="deepskyblue", \
                 onvalue = "-b", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var2)
        self.C2.grid(row=3, column=0, padx=5, pady=5)
        self.t2 = Text(self.frame_content, height=1, width=20)
        self.t2.grid(row=3, column=1, padx=5, pady=5)
        l2 = Label(
            self.frame_content,
            text=
            ': Long version bssid. Select the target network based on\n  the access point\'s MAC address.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=3, column=2, padx=5, pady=5)

        self.C3 = Checkbutton(self.frame_content, text = "-e", fg="deepskyblue", \
                 onvalue = "-e", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var3)
        self.C3.grid(row=4, column=0, padx=5, pady=5)
        self.t3 = Text(self.frame_content, height=1, width=20)
        self.t3.grid(row=4, column=1, padx=5, pady=5)
        l3 = Label(
            self.frame_content,
            text=
            ': If set, all IVs from networks with the same ESSID will be used.\n  This option is also required for WPA/WPA2-PSK cracking if the\n  ESSID is not broadcasted (hidden).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=4, column=2, padx=5, pady=5)

        self.C4 = Checkbutton(self.frame_content, text = "-p", fg="deepskyblue", \
                 onvalue = "-p", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var4)
        self.C4.grid(row=5, column=0, padx=5, pady=5)
        self.t4 = Text(self.frame_content, height=1, width=20)
        self.t4.grid(row=5, column=1, padx=5, pady=5)
        l4 = Label(
            self.frame_content,
            text=
            ': On SMP systems: # of CPU to use. This option is invalid on\n  non-SMP systems.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=5, column=2, padx=5, pady=5)

        self.C5 = Checkbutton(self.frame_content, text = "-q", fg="deepskyblue", \
                 onvalue = "-q", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var5)
        self.C5.grid(row=6, column=0, padx=5, pady=5)
        self.t5 = Text(self.frame_content, height=1, width=20)
        self.t5.grid(row=6, column=1, padx=5, pady=5)
        l5 = Label(
            self.frame_content,
            text=
            ': Enable quiet mode (no status output until the key is found, or not).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=6, column=2, padx=5, pady=5)

        self.C6 = Checkbutton(self.frame_content, text = "-c", fg="deepskyblue", \
                 onvalue = "-c", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var6)
        self.C6.grid(row=7, column=0, padx=5, pady=5)
        self.t6 = Text(self.frame_content, height=1, width=20)
        self.t6.grid(row=7, column=1, padx=5, pady=5)
        l6 = Label(
            self.frame_content,
            text=
            ': (WEP cracking) Restrict the search space to alpha-numeric\n  characters only (0x20 - 0x7F).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=7, column=2, padx=5, pady=5)

        self.C7 = Checkbutton(self.frame_content, text = "-t", fg="deepskyblue", \
                 onvalue = "-t", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var7)
        self.C7.grid(row=8, column=0, padx=5, pady=5)
        self.t7 = Text(self.frame_content, height=1, width=20)
        self.t7.grid(row=8, column=1, padx=5, pady=5)
        l7 = Label(
            self.frame_content,
            text=
            ': (WEP cracking) Restrict the search space to binary coded decimal\n  hex characters.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=8, column=2, padx=5, pady=5)

        Label(self.frame_content2,
              text='Aircrack-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        #frame2
        self.C8 = Checkbutton(self.frame_content2, text = "-h", fg="deepskyblue", \
                 onvalue = "-h", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var8)
        self.C8.grid(row=9, column=0, padx=5, pady=5)
        self.t8 = Text(self.frame_content2, height=1, width=20)
        self.t8.grid(row=9, column=1, padx=5, pady=5)
        l8 = Label(
            self.frame_content2,
            text=
            ':  (WEP cracking) Restrict the search space to numeric\n   characters (0x30-0x39) These keys are used by default\n   in most Fritz!BOXes.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=9, column=2, padx=5, pady=5)

        self.C9 = Checkbutton(self.frame_content2, text = "-d", fg="deepskyblue", \
                 onvalue = "-d", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var9)
        self.C9.grid(row=10, column=0, padx=5, pady=5)
        self.t9 = Text(self.frame_content2, height=1, width=20)
        self.t9.grid(row=10, column=1, padx=5, pady=5)
        l9 = Label(
            self.frame_content2,
            text=
            ': (WEP cracking) Long version debug. Set the beginning\n  of the WEP key (in hex), for debugging purposes.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=10, column=2, padx=5, pady=5)


        self.C10 = Checkbutton(self.frame_content2, text = "-m", fg="deepskyblue", \
                 onvalue = "-m", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var10)
        self.C10.grid(row=11, column=0, padx=5, pady=5)
        self.t10 = Text(self.frame_content2, height=1, width=20)
        self.t10.grid(row=11, column=1, padx=5, pady=5)
        l10 = Label(
            self.frame_content2,
            text=
            ': (WEP cracking) MAC address to filter WEP data packets.\n  Alternatively, specify -m ff:ff:ff:ff:ff:ff to use all and every IVs,\n  regardless of the network.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=11, column=2, padx=5, pady=5)

        self.C11 = Checkbutton(self.frame_content2, text = "-M", fg="deepskyblue", \
                 onvalue = "-M", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var11)
        self.C11.grid(row=12, column=0, padx=5, pady=5)
        self.t11 = Text(self.frame_content2, height=1, width=20)
        self.t11.grid(row=12, column=1, padx=5, pady=5)
        l11 = Label(
            self.frame_content2,
            text=': (WEP cracking) Sets the maximum number of ivs to use.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=12, column=2, padx=5, pady=5)

        self.C12 = Checkbutton(self.frame_content2, text = "-n", fg="deepskyblue", \
                 onvalue = "-n", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var12)
        self.C12.grid(row=13, column=0, padx=5, pady=5)
        self.t12 = Text(self.frame_content2, height=1, width=20)
        self.t12.grid(row=13, column=1, padx=5, pady=5)
        l12 = Label(
            self.frame_content2,
            text=
            ': (WEP cracking) Specify the length of the key: 64 for 40-bit\n  WEP, 128 for 104-bit WEP, etc. The default value is 128.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=13, column=2, padx=5, pady=5)

        self.C13 = Checkbutton(self.frame_content2, text = "-i", fg="deepskyblue", \
                 onvalue = "-i", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var13)
        self.C13.grid(row=14, column=0, padx=5, pady=5)
        self.t13 = Text(self.frame_content2, height=1, width=20)
        self.t13.grid(row=14, column=1, padx=5, pady=5)
        l13 = Label(
            self.frame_content2,
            text=
            ': (WEP cracking) Only keep the IVs that have this key index\n  (1 to 4). The default behaviour is to ignore the key index.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=14, column=2, padx=5, pady=5)

        self.C14 = Checkbutton(self.frame_content2, text = "-f", fg="deepskyblue", \
                 onvalue = "-f", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var14)
        self.C14.grid(row=15, column=0, padx=5, pady=5)
        self.t14 = Text(self.frame_content2, height=1, width=20)
        self.t14.grid(row=15, column=1, padx=5, pady=5)
        l14 = Label(
            self.frame_content2,
            text=
            ': (WEP cracking) By default, this parameter is set to 2 for\n  104-bit WEP and to 5 for 40-bit WEP. Specify a higher\n  value to increase the bruteforce level: cracking will take\n  more time, but with a higher likelyhood of success.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=15, column=2, padx=5, pady=5)

        #frame3
        Label(self.frame_content3,
              text='Aircrack-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)

        self.C15 = Checkbutton(self.frame_content3, text = "-H", fg="deepskyblue", \
                 onvalue = "-H", offvalue = "", height=1, \
                 width = 7, bg="midnightblue", font=self.customFont,variable=self.var15)
        self.C15.grid(row=17, column=0, padx=5, pady=5)
        self.t15 = Text(self.frame_content3, height=1, width=20)
        self.t15.grid(row=17, column=1, padx=5, pady=5)
        l15 = Label(self.frame_content3,
                    text=': Long version help. Output help information.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=17, column=2, padx=5, pady=5)

        self.C16 = Checkbutton(self.frame_content3, text = "-l", fg="deepskyblue", \
                 onvalue = "-l", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var16)
        self.C16.grid(row=18, column=0, padx=5, pady=5)
        self.t16 = Text(self.frame_content3, height=1, width=20)
        self.t16.grid(row=18, column=1, padx=5, pady=5)
        l16 = Label(
            self.frame_content3,
            text=': (Lowercase L, ell) logs the key to the file specified.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=18, column=2, padx=5, pady=5)

        self.C17 = Checkbutton(self.frame_content3, text = "-K", fg="deepskyblue", \
                 onvalue = "-K", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var17)
        self.C17.grid(row=19, column=0, padx=5, pady=5)
        self.t17 = Text(self.frame_content3, height=1, width=20)
        self.t17.grid(row=19, column=1, padx=5, pady=5)
        l17 = Label(
            self.frame_content3,
            text=
            ':  (WEP cracking) There are 17 korek statistical attacks.\n   Sometimes one attack creates a huge false positive that\n   prevents the key from being found, even with lots of IVs.\n   Try -k 1, -k 2, -k 17 to disable each attack selectively.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=19, column=2, padx=5, pady=5)


        self.C18 = Checkbutton(self.frame_content3, text = "-k", fg="deepskyblue", \
                 onvalue = "-k", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var18)
        self.C18.grid(row=21, column=0, padx=5, pady=5)
        self.t18 = Text(self.frame_content3, height=1, width=20)
        self.t18.grid(row=21, column=1, padx=5, pady=5)
        l18 = Label(self.frame_content3,
                    text=': number of packets per second (default: 100)',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=21, column=2, padx=5, pady=5)

        self.C19 = Checkbutton(self.frame_content3, text = "-p", fg="deepskyblue", \
                 onvalue = "-p", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var19)
        self.C19.grid(row=22, column=0, padx=5, pady=5)
        self.t19 = Text(self.frame_content3, height=1, width=20)
        self.t19.grid(row=22, column=1, padx=5, pady=5)
        l19 = Label(
            self.frame_content3,
            text=
            ': Allow the number of threads for cracking even if you have\n   a non-SMP computer.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=22, column=2, padx=5, pady=5)


        self.C20 = Checkbutton(self.frame_content3, text = "-r", fg="deepskyblue", \
                 onvalue = "-r", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var20)
        self.C20.grid(row=23, column=0, padx=5, pady=5)
        self.t20 = Text(self.frame_content3, height=1, width=20)
        self.t20.grid(row=23, column=1, padx=5, pady=5)
        l20 = Label(
            self.frame_content3,
            text=
            ': Utilizes a database generated by airolib-ng as input to\n   determine the WPA key. Outputs an error message if\n   aircrack-ng has not been compiled with sqlite support.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=23, column=2, padx=5, pady=5)

        self.C21 = Checkbutton(self.frame_content3, text = "-x/-x0", fg="deepskyblue", \
                 onvalue = "-x/-x0", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var21)
        self.C21.grid(row=24, column=0, padx=5, pady=5)
        self.t21 = Text(self.frame_content3, height=1, width=20)
        self.t21.grid(row=24, column=1, padx=5, pady=5)
        l21 = Label(self.frame_content3,
                    text=':  (WEP cracking) Disable last keybytes brutforce.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=24, column=2, padx=5, pady=5)

        #frame4
        Label(self.frame_content4,
              text='Aircrack-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        self.C22 = Checkbutton(self.frame_content4, text = "-x1", fg="deepskyblue", \
                 onvalue = "-x1", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var22)
        self.C22.grid(row=25, column=0, padx=5, pady=5)
        self.t22 = Text(self.frame_content4, height=1, width=20)
        self.t22.grid(row=25, column=1, padx=5, pady=5)
        l22 = Label(
            self.frame_content4,
            text=
            ':  (WEP cracking) Enable last keybyte bruteforcing (default).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=25, column=2, padx=5, pady=5)

        self.C23 = Checkbutton(self.frame_content4, text = "-x2", fg="deepskyblue", \
                 onvalue = "-x2", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var23)
        self.C23.grid(row=26, column=0, padx=5, pady=5)
        self.t23 = Text(self.frame_content4, height=1, width=20)
        self.t23.grid(row=26, column=1, padx=5, pady=5)
        l23 = Label(
            self.frame_content4,
            text=':  (WEP cracking) Enable last two keybytes bruteforcing.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=26, column=2, padx=5, pady=5)

        self.C24 = Checkbutton(self.frame_content4, text = "-X", fg="deepskyblue", \
                 onvalue = "-X", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var24)
        self.C24.grid(row=27, column=0, padx=5, pady=5)
        self.t24 = Text(self.frame_content4, height=1, width=20)
        self.t24.grid(row=27, column=1, padx=5, pady=5)
        l24 = Label(
            self.frame_content4,
            text=
            ':  (WEP cracking) Disable bruteforce multithreading (SMP only).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=27, column=2, padx=5, pady=5)

        self.C25 = Checkbutton(self.frame_content4, text = "-y", fg="deepskyblue", \
                 onvalue = "-y", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var25)
        self.C25.grid(row=28, column=0, padx=5, pady=5)
        self.t25 = Text(self.frame_content4, height=1, width=20)
        self.t25.grid(row=28, column=1, padx=5, pady=5)
        l25 = Label(
            self.frame_content4,
            text=
            ':  (WEP cracking) Experimental single bruteforce attack which\n   should only be used when the standard attack mode fails with\n   more than one million IVs',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=28, column=2, padx=5, pady=5)


        self.C26 = Checkbutton(self.frame_content4, text = "-u", fg="deepskyblue", \
                 onvalue = "-u", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var26)
        self.C26.grid(row=29, column=0, padx=5, pady=5)
        self.t26 = Text(self.frame_content4, height=1, width=20)
        self.t26.grid(row=29, column=1, padx=5, pady=5)
        l26 = Label(
            self.frame_content4,
            text=
            ':  Long form -cpu-detect. Provide information on the number of\n   CPUs and MMX support. Example responses to "aircrack-ng \n   -cpu-detect" are "Nb CPU detected: 2" or Nb CPU detected: \n   1 (MMX available)".',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=29, column=2, padx=5, pady=5)

        self.C27 = Checkbutton(self.frame_content4, text = "-w", fg="deepskyblue", \
                 onvalue = "-w", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var27)
        self.C27.grid(row=30, column=0, padx=5, pady=5)
        self.t27 = Text(self.frame_content4, height=1, width=20)
        self.t27.grid(row=30, column=1, padx=5, pady=5)
        l27 = Label(
            self.frame_content4,
            text=
            ':   (WPA cracking) Path to a wordlist or "-"without the quotes for \n    standard in (stdin).',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=30, column=2, padx=5, pady=5)

        self.C28 = Checkbutton(self.frame_content4, text = "-z", fg="deepskyblue", \
                 onvalue = "-z", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var28)
        self.C28.grid(row=31, column=0, padx=5, pady=5)
        self.t28 = Text(self.frame_content4, height=1, width=20)
        self.t28.grid(row=31, column=1, padx=5, pady=5)
        l28 = Label(
            self.frame_content4,
            text=':  Invokes the PTW WEP cracking method. (Default in v1.x)',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=31, column=2, padx=5, pady=5)

        #frame4
        Label(self.frame_content6,
              text='Aircrack-ng',
              font=self.headerfont,
              bg="midnightblue",
              fg="firebrick",
              padx=10,
              pady=10).grid(row=0, column=0)
        self.C29 = Checkbutton(self.frame_content6, text = "-P", fg="deepskyblue", \
                 onvalue = "-P", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var29)
        self.C29.grid(row=32, column=0, padx=5, pady=5)
        self.t29 = Text(self.frame_content6, height=1, width=20)
        self.t29.grid(row=32, column=1, padx=5, pady=5)
        l29 = Label(
            self.frame_content6,
            text=':  Long version -ptw-debug. Invokes the PTW debug mode.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=32, column=2, padx=5, pady=5)

        self.C30 = Checkbutton(self.frame_content6, text = "-C", fg="deepskyblue", \
                 onvalue = "-C", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var30)
        self.C30.grid(row=33, column=0, padx=5, pady=5)
        self.t30 = Text(self.frame_content6, height=1, width=20)
        self.t30.grid(row=33, column=1, padx=5, pady=5)
        l30 = Label(
            self.frame_content6,
            text=
            ':   Long version -combine. Merge the given APs to a virtual one.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=33, column=2, padx=5, pady=5)

        self.C31 = Checkbutton(self.frame_content6, text = "-D", fg="deepskyblue", \
                 onvalue = "-D", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var31)
        self.C31.grid(row=34, column=0, padx=5, pady=5)
        self.t31 = Text(self.frame_content6, height=1, width=20)
        self.t31.grid(row=34, column=1, padx=5, pady=5)
        l31 = Label(
            self.frame_content6,
            text=':  Long version -wep-decloak. Run in WEP decloak mode.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=34, column=2, padx=5, pady=5)

        self.C32 = Checkbutton(self.frame_content6, text = "-V", fg="deepskyblue", \
                 onvalue = "-V", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var32)
        self.C32.grid(row=35, column=0, padx=5, pady=5)
        self.t32 = Text(self.frame_content6, height=1, width=20)
        self.t32.grid(row=35, column=1, padx=5, pady=5)
        l32 = Label(
            self.frame_content6,
            text=
            ':  Long version -visual-inspection. Run in visual inspection mode.',
            font=self.myfont,
            bg="midnightblue",
            fg="deepskyblue",
            justify=LEFT).grid(row=35, column=2, padx=5, pady=5)

        self.C33 = Checkbutton(self.frame_content6, text = "-1", fg="deepskyblue", \
                 onvalue = "-1", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var33)
        self.C33.grid(row=36, column=0, padx=5, pady=5)
        self.t33 = Text(self.frame_content6, height=1, width=20)
        self.t33.grid(row=36, column=1, padx=5, pady=5)
        l33 = Label(self.frame_content6,
                    text=':  Long version -oneshot. Run in oneshot mode.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=36, column=2, padx=5, pady=5)

        self.C34 = Checkbutton(self.frame_content6, text = "-S", fg="deepskyblue", \
                 onvalue = "-S", offvalue = "", height=1, \
                 bg="midnightblue", font=self.customFont,variable=self.var34)
        self.C34.grid(row=37, column=0, padx=5, pady=5)
        self.t34 = Text(self.frame_content6, height=1, width=20)
        self.t34.grid(row=37, column=1, padx=5, pady=5)
        l34 = Label(self.frame_content6,
                    text=':  WPA cracking speed test.',
                    font=self.myfont,
                    bg="midnightblue",
                    fg="deepskyblue",
                    justify=LEFT).grid(row=37, column=2, padx=5, pady=5)
Example #56
0
class Database:
    """Opens a window for inputing the properties of a compound."""
    def __init__(self, master, system, database):
        """The constructor method."""

        self.version = system.version
        self.fonttype = system.fonttype
        self.sfont = get_superfont(self.fonttype)
        self.master = master
        self.tframe = Frame(master.tframe)
        self.frame = Frame(master.frame)
        self.bframe = Frame(master.bframe)
        self.top = None

        self.system = system
        self.database = database  #the chemical database

        self.chemicals_list = self.database.keys()
        self.chemicals_list.sort()

        self.chemicaldatas = {}

        for name in self.chemicals_list:
            self.chemicaldatas[name] = ChemicalData(name)
            self.chemicaldatas[name].read_database(self.database[name])

    def make_widgets(self):

        self.insruction = Label(
            self.tframe,
            text=
            'Please provide the following fundamental properties for the chemicals:\n'
        )

        self.blankcolumn = Label(self.tframe, text=' ', width=1)
        self.editcolumn = Label(self.tframe, text=' ', width=6)
        self.delcolumn = Label(self.tframe, text=' ', width=6)
        self.namecolumn = Label(self.tframe, text=' ', width=18)
        self.formcolumn = Label(self.tframe, text=' ', width=10)
        self.tempcolumn = Label(self.tframe, text=' ', width=10)
        self.Dwcolumn = Label(self.tframe, text=' ', width=18)
        self.Koccolumn = Label(self.tframe, text=' ', width=18)
        self.Kdoccolumn = Label(self.tframe, text=' ', width=18)
        self.Refcolumn = Label(self.tframe, text=' ', width=18)
        self.endcolumn = Label(self.tframe, text=' ', width=2)

        self.namelabel = Label(self.tframe, text='Chemical name')
        self.formlabel = Label(self.tframe, text='Formula')
        self.templabel = Label(self.tframe, text='Temperature')
        self.Dwlabel = Label(self.tframe,
                             text='Molecular diffusivity\n in water')
        self.Koclabel = Label(self.tframe,
                              text='Organic carbon\n partition coefficient')
        self.Kdoclabel = Label(
            self.tframe,
            text='Dissolved organic carbon\n partition coefficient')
        self.Reflabel = Label(self.tframe, text='Reference')

        self.tempunits = Label(self.tframe, text=unichr(176) + 'C')
        self.Dwunits = Label(self.tframe, text=u'cm\u00B2/s')
        self.Kocunits = Label(self.tframe, text='log(L/kg)')
        self.Kdocunits = Label(self.tframe, text='log(L/kg)')

        self.addwidget = Button(self.bframe,
                                text='Add new chemicals',
                                command=self.addchemicaldata,
                                width=20)
        self.tempwidget = Button(self.bframe,
                                 text='Add new temperatures',
                                 command=self.addtempdata,
                                 width=20)
        self.importwidget = Button(self.bframe,
                                   text='Import database file',
                                   command=self.importchemicaldata,
                                   width=20)
        self.savebutton = Button(self.bframe,
                                 text='Save',
                                 command=self.OK,
                                 width=20)
        self.cancelbutton = Button(self.bframe,
                                   text='Cancel',
                                   command=self.cancel,
                                   width=20)

        self.botblankcolumn = Label(self.frame, text=' ', width=1)
        self.boteditcolumn = Label(self.frame, text=' ', width=6)
        self.botdelcolumn = Label(self.frame, text=' ', width=6)
        self.botnamecolumn = Label(self.frame, text=' ', width=18)
        self.botformcolumn = Label(self.frame, text=' ', width=10)
        self.bottempcolumn = Label(self.frame, text=' ', width=10)
        self.botDwcolumn = Label(self.frame, text=' ', width=18)
        self.botKoccolumn = Label(self.frame, text=' ', width=18)
        self.botKdoccolumn = Label(self.frame, text=' ', width=18)
        self.botRefcolumn = Label(self.frame, text=' ', width=18)
        self.botendcolumn = Label(self.frame, text=' ', width=2)

        self.blank1 = Label(self.bframe, text=' ')
        self.blank2 = Label(self.bframe, text=' ')
        self.blank3 = Label(self.bframe, text=' ')

        self.insruction.grid(row=0,
                             column=0,
                             sticky='W',
                             padx=1,
                             pady=1,
                             columnspan=11)

        self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1)
        self.editcolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1)
        self.delcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1)
        self.namecolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1)
        self.formcolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1)
        self.tempcolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1)
        self.Dwcolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1)
        self.Koccolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1)
        self.Kdoccolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1)
        self.Refcolumn.grid(row=1, column=9, sticky='WE', padx=1, pady=1)
        self.endcolumn.grid(row=1, column=10, sticky='WE', padx=1, pady=1)

        self.namelabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1)
        self.formlabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1)
        self.templabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1)
        self.Dwlabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1)
        self.Koclabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1)
        self.Kdoclabel.grid(row=2, column=8, sticky='WE', padx=1, pady=1)
        self.Reflabel.grid(row=2, column=9, sticky='WE', padx=1, pady=1)

        self.tempunits.grid(row=3, column=5, sticky='WE', padx=1, pady=1)
        self.Dwunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1)
        self.Kocunits.grid(row=3, column=7, sticky='WE', padx=1, pady=1)
        self.Kdocunits.grid(row=3, column=8, sticky='WE', padx=1, pady=1)

        #Bind the "return key" to the buttons

        self.updatechemicals()

    def updatechemicals(self, event=None):

        self.addwidget.grid_forget()
        self.tempwidget.grid_forget()
        self.savebutton.grid_forget()
        self.cancelbutton.grid_forget()
        self.blank1.grid_forget()
        self.blank2.grid_forget()

        self.chemicals_list = self.chemicaldatas.keys()
        self.chemicals_list.sort()
        row = 4

        namelabellength = 18
        formlabellength = 10
        Reflabellength = 18

        for name in self.chemicals_list:
            try:
                self.chemicaldatas[name].remove_chemicalwidgets()
            except:
                pass
            self.chemicaldatas[name].chemicalwidgets(self.frame, row,
                                                     self.master)
            row = row + 1

            if namelabellength < self.chemicaldatas[
                    name].namelabel.winfo_reqwidth() / 8:
                namelabellength = int(
                    self.chemicaldatas[name].namelabel.winfo_reqwidth() /
                    8) + 1
            if formlabellength < self.chemicaldatas[
                    name].formlabel.winfo_reqwidth() / 8:
                formlabellength = int(
                    self.chemicaldatas[name].formlabel.winfo_reqwidth() /
                    8) + 1
            if Reflabellength < self.chemicaldatas[
                    name].Reflabel.winfo_reqwidth() / 8:
                Reflabellength = int(
                    self.chemicaldatas[name].Reflabel.winfo_reqwidth() / 8) + 1

        self.namecolumn.config(width=namelabellength)
        self.formcolumn.config(width=formlabellength)
        self.Refcolumn.config(width=Reflabellength)

        self.botnamecolumn.config(width=namelabellength)
        self.botformcolumn.config(width=formlabellength)
        self.botRefcolumn.config(width=Reflabellength)

        self.botblankcolumn.grid(row=row,
                                 column=0,
                                 sticky='WE',
                                 padx=1,
                                 pady=1)
        self.boteditcolumn.grid(row=row, column=1, sticky='WE', padx=1, pady=1)
        self.botdelcolumn.grid(row=row, column=2, sticky='WE', padx=1, pady=1)
        self.botnamecolumn.grid(row=row, column=3, sticky='WE', padx=1, pady=1)
        self.botformcolumn.grid(row=row, column=4, sticky='WE', padx=1, pady=1)
        self.bottempcolumn.grid(row=row, column=5, sticky='WE', padx=1, pady=1)
        self.botDwcolumn.grid(row=row, column=6, sticky='WE', padx=1, pady=1)
        self.botKoccolumn.grid(row=row, column=7, sticky='WE', padx=1, pady=1)
        self.botKdoccolumn.grid(row=row, column=8, sticky='WE', padx=1, pady=1)
        self.botRefcolumn.grid(row=row, column=9, sticky='WE', padx=1, pady=1)
        self.botendcolumn.grid(row=row, column=10, sticky='WE', padx=1, pady=1)

        self.blank2.grid(row=row)
        row = row + 1
        self.addwidget.grid(row=row, columnspan=11)
        row = row + 1
        self.tempwidget.grid(row=row, columnspan=11)
        row = row + 1
        self.importwidget.grid(row=row, columnspan=11)
        row = row + 1
        self.savebutton.grid(row=row, columnspan=11)
        row = row + 1
        self.cancelbutton.grid(row=row, columnspan=11)
        row = row + 1
        self.blank3.grid(row=row)
        row = row + 1

        self.savebutton.bind('<Return>', self.OK)
        self.cancelbutton.bind('<Return>', self.cancel)

        self.focusbutton = self.cancelbutton
        self.master.geometry()
        self.master.center()

    def addchemicaldata(self, event=None):

        new_name = 'chemical' + str(len(self.chemicals_list))

        self.chemicaldatas[new_name] = ChemicalData(new_name)

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                DatabaseEditor(self.top,
                               self.system,
                               self.chemicaldatas[new_name],
                               self.chemicaldatas,
                               editflag=0,
                               tempflag=0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicaldatas[new_name].get_chemicaldata(self.top.window)
                self.chemicaldatas[self.chemicaldatas[new_name].
                                   name] = self.chemicaldatas[new_name].copy()

            del self.chemicaldatas[new_name]

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatechemicals()

    def importchemicaldata(self):

        UserPath = os.environ['USERPROFILE']
        Filepath = tkfd.askopenfilename(initialdir=UserPath)

        if Filepath != '':
            data = open(Filepath, 'r')
            database_imported = pickle.load(data)
            data.close()
            if self.top is None:
                self.top = CapSimWindow(master=self.master, buttons=2)
                self.top.make_window(
                    DatabaseImporter(self.top, self.system, database_imported))
                self.top.tk.mainloop()

                duplicate_name = []
                duplicate_temp = []

                if self.top.window.cancelflag == 0:
                    error_check = 0
                    for name in self.top.window.chemicals_list:
                        if self.top.window.importedchemicals[name].check == 1:
                            if self.chemicals_list.count(
                                    self.top.window.importedchemicals[name].
                                    name_new) == 0:
                                self.chemicals_list.append(
                                    self.top.window.importedchemicals[name].
                                    name_new)
                                self.chemicaldatas[
                                    self.top.window.importedchemicals[name].
                                    name_new] = ChemicalData(
                                        self.top.window.
                                        importedchemicals[name].name_new)
                                self.chemicaldatas[
                                    self.top.window.importedchemicals[name].
                                    name_new].read_database(
                                        self.top.window.importedchemicals[name]
                                    )
                            else:
                                for temp in self.top.window.importedchemicals[
                                        name].temps:
                                    if self.chemicaldatas[
                                            self.top.window.
                                            importedchemicals[name].
                                            name_new].temps.count(temp) == 0:
                                        self.chemicaldatas[
                                            self.top.window.
                                            importedchemicals[name].
                                            name_new].read_temperature(
                                                self.top.window.
                                                importedchemicals[name], temp)
                                    else:
                                        duplicate_name.append(
                                            self.top.window.
                                            importedchemicals[name].name_new)
                                        duplicate_temp.append(temp)
                                        error_check = 1
                    error_message = 'The following compound information are duplicated:\n\n'
                    for na in range(len(duplicate_name)):
                        error_message = error_message + '              ' + str(
                            duplicate_name[na]) + ' @ ' + str(
                                duplicate_temp[na]) + 'C \n'

                    if error_check == 1:
                        tkmb.showerror(title=self.system.version,
                                       message=error_message)

                if self.top is not None:
                    self.top.destroy()
                    self.top = None

            elif self.top is not None:
                tkmb.showerror(
                    title=self.system.version,
                    message=
                    'Please close the existing parameter input window first.')
                self.top.tk.focus()

        self.updatechemicals()

    def addtempdata(self, event=None):

        name = self.chemicals_list[0]

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                DatabaseEditor(self.top,
                               self.system,
                               self.chemicaldatas[name],
                               self.chemicaldatas,
                               editflag=0,
                               tempflag=1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicaldatas[
                    self.top.window.name.get()].get_chemicaldata(
                        self.top.window)

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatechemicals()

    def editchemicaldata(self, name):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                DatabaseEditor(self.top,
                               self.system,
                               self.chemicaldatas[name],
                               self.chemicaldatas,
                               editflag=1,
                               tempflag=0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicaldatas[name].get_chemicaldata(self.top.window)

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatechemicals()

    def deletechemicaldata(self, name):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                DatabaseDeleter(self.top, self.system,
                                self.chemicaldatas[name]))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicaldatas[name].get_chemicaldata(self.top.window)
            if self.top.window.cancelflag == 2:
                self.chemicaldatas[name].remove_chemicalwidgets()
                del self.chemicaldatas[name]

            if self.top is not None:
                self.top.destroy()
                self.top = None

        self.updatechemicals()

    def cancel(self, event=None):

        self.exitflag = 1
        self.frame.quit()

    def OK(self, event=None):
        """Finish and move on."""

        self.database = {}
        for name in self.chemicals_list:
            chemicaldata = self.chemicaldatas[name]
            index = self.chemicals_list.index(name)
            self.database[name] = ChemicalDatabase(chemicaldata.name,
                                                   chemicaldata.formula,
                                                   index + 1, chemicaldata.MW)
            for temp in chemicaldata.temps:
                Dw = chemicaldata.Dw[temp]
                Kow = chemicaldata.Kow[temp]
                density = chemicaldata.density[temp]
                Ref = chemicaldata.Ref[temp]
                Koc = chemicaldata.Koc[temp]
                Kdoc = chemicaldata.Kdoc[temp]
                Kf = chemicaldata.Kf[temp]
                N = chemicaldata.N[temp]

                self.database[name].add_properties(temp, Kow, density, Ref, Dw,
                                                   Koc, Kdoc, Kf, N)

        self.exitflag = 1
        self.frame.quit()
L1 = Label(my_app, text='Figure of Geometry', font=('Arial', 24))
L1.grid(row=0, column=0)

L2 = Label(
    my_app,
    text='Sphare, dimensions three, examples: ball, meatball, and others.')
L2.grid(row=1, column=0)

L3 = Label(my_app, text='Radius : ')
L3.grid(row=2, column=0)
str1 = StringVar()
E1 = Entry(my_app, textvariable=str1)
E1.grid(row=2, column=1)

L5 = Label(my_app, text='result = ')
L5.grid(row=3, column=0)
L6 = Label(my_app, text='0')
L6.grid(row=3, column=1)


def area():
    s = float(str1.get())
    result = 4 * 3.14 * (s * s)
    L6.config(text=result)


B1 = Button(my_app, text='Calculate area', command=area)
B1.grid(row=3, column=0)

my_app.mainloop()
Example #58
0
def createWidgets():
    nRow = 0
    Frame1 = Frame(root, height=200, width=200)
    Frame1.grid(sticky=W)

    Label7 = Label(Frame1, text='(V1)类型说明:')
    Label7.grid(
        row=nRow,
        column=0,
    )
    Label7 = Label(Frame1, text='(0:oracle  / 1:SQL)')
    Label7.grid(
        row=nRow,
        column=1,
    )
    nRow += 1
    Label7 = Label(Frame1, text='数据库类型:')
    Label7.grid(
        row=nRow,
        column=0,
    )
    Dbtype = Entry(Frame1, textvariable=varDBType)
    Dbtype.grid(row=nRow, column=1)

    Label1 = Label(Frame1, text='数据库地址:')
    # Label1.pack(anchor=W)
    Label1.grid(row=nRow, column=0)
    IPInput = Entry(Frame1, textvariable=varIP)
    IPInput.grid(row=nRow, column=1)
    nRow += 1
    #
    Label2 = Label(Frame1, text='数据库名称:')
    Label2.grid(
        row=nRow,
        column=0,
    )
    ServerName = Entry(Frame1, textvariable=varDateBase)
    ServerName.grid(row=nRow, column=1)
    nRow += 1

    Label3 = Label(Frame1, text='用户名:')
    Label3.grid(
        row=nRow,
        column=0,
    )
    User = Entry(Frame1, textvariable=varUser)
    User.grid(row=nRow, column=1)
    nRow += 1

    Label4 = Label(Frame1, text='数据库密码:')
    Label4.grid(
        row=nRow,
        column=0,
    )
    DBPass = Entry(Frame1, show='*', textvariable=varPaswd)
    DBPass.grid(row=nRow, column=1)
    nRow += 1

    Label5 = Label(Frame1, text='接口地址:')
    Label5.grid(
        row=nRow,
        column=0,
    )
    WebSerIp = Entry(Frame1, textvariable=varWebSerIp)
    WebSerIp.grid(row=nRow, column=1)
    nRow += 1

    Label12 = Label(Frame1, text='        上传间隔:')
    Label12.grid(row=nRow, column=0)
    Input3 = Entry(Frame1, textvariable=varSleeptime)
    Input3.bind('<KeyRelease>', keyPress)
    Input3.grid(row=nRow, column=1)
    nRow += 1

    Frame2 = Frame(Frame1, height=50, width=200)
    Frame2.grid(sticky=W, row=nRow, column=1)

    nRow = 0
    BtnConnet = Button(Frame2, text='写入配置', command=Connet)
    BtnConnet.grid(row=nRow, column=0)

    Frame3 = Frame(root, height=50, width=300)
    Frame3.grid(sticky=N)

    LabMess = Label(Frame3, text='等待连接。。', font=13, fg='red')
    LabMess.grid(row=0, column=0)

    TestBtn = Button(Frame3,
                     text='数据库连接',
                     command=lambda: TestDBConnet(LabMess))
    TestBtn.grid(row=1, column=0)

    Btn1 = Button(Frame3, text='接口测试', command=lambda: IntfConnetTest(LabMess))
    Btn1.grid(row=1, column=2, padx=10)

    Btn2 = Button(Frame3,
                  text='开始上传',
                  command=lambda: Thread_SaveLoad(LabMess))
    Btn2.grid(row=1, column=4, padx=10)

    quitButton = Button(Frame3, text='关闭', command=Quit)
    quitButton.grid(row=1, column=5, padx=10)

    #接口部分
    nRow = 0
    Label8 = Label(Frame1, text='        接口参数: ')
    Label8.grid(row=nRow, column=2, columnspan=2)
    nRow += 1

    Label9 = Label(Frame1, text='        景区编码:')
    Label9.grid(row=nRow, column=2)
    IPInput = Entry(Frame1, textvariable=varParkCode)
    IPInput.grid(row=nRow, column=3)
    nRow += 1

    Label10 = Label(Frame1, text='        业务编码:')
    Label10.grid(row=nRow, column=2)
    combox1 = Combobox(
        Frame1,
        textvariable=varinfoCode,
        values=GetinfoCode(),
        width=18,
    )
    combox1.bind(
        "<<ComboboxSelected>>",
        comboxChanged,
    )
    combox1.grid(
        row=nRow,
        column=3,
    )
    nRow += 1

    Label11 = Label(Frame1, text='        存储过程:')
    Label11.grid(row=nRow, column=2)
    Input3 = Entry(Frame1, textvariable=varProc)
    Input3.grid(row=nRow, column=3)
    nRow += 2

    SaveBtn = Button(Frame1, text='保存存储过程', command=SaveProc)
    SaveBtn.grid(row=nRow, column=3)
Example #59
0
class Automation(Frame):
    """The Automation class is a GUI that provides radio automation."""
    _state = None
    _button_text = None
    _button = None

    _meter = None
    _cart_queue = None

    _list_time = None
    _list_track = None
    _list_artist = None

    def __init__(self):
        """Construct an Automation window."""
        Frame.__init__(self)

        # initialize title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=3)

        # initialize button and state
        self._state = STATE_STOPPED

        self._button_text = StringVar()

        self._button = Button(self.master,
                              textvariable=self._button_text,
                              command=self._update_state,
                              width=16,
                              height=2)
        self._button.config(bd=2)
        self._button.grid(row=0, column=3)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=4)

        # initialize playlist view
        playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=16,
              text=TEXT_PLAYLIST_TIME).grid(row=0, column=0)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=32,
              text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=32,
              text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2)

        inner_playlist = Frame(playlist)
        scroll = Scrollbar(inner_playlist,
                           orient=Tkinter.VERTICAL,
                           command=self._scroll_playlist)
        self._list_time = Listbox(inner_playlist,
                                  selectmode=Tkinter.SINGLE,
                                  yscrollcommand=scroll.set,
                                  exportselection=0,
                                  width=16,
                                  height=20)
        self._list_track = Listbox(inner_playlist,
                                   selectmode=Tkinter.SINGLE,
                                   yscrollcommand=scroll.set,
                                   exportselection=0,
                                   width=32,
                                   height=20)
        self._list_artist = Listbox(inner_playlist,
                                    selectmode=Tkinter.SINGLE,
                                    yscrollcommand=scroll.set,
                                    exportselection=0,
                                    width=32,
                                    height=20)

        scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
        self._list_time.pack(side=Tkinter.LEFT,
                             fill=Tkinter.X,
                             expand=True,
                             padx=2,
                             pady=2)
        self._list_track.pack(side=Tkinter.LEFT,
                              fill=Tkinter.X,
                              expand=True,
                              padx=2,
                              pady=2)
        self._list_artist.pack(side=Tkinter.LEFT,
                               fill=Tkinter.X,
                               expand=True,
                               padx=2,
                               pady=2)

        inner_playlist.grid(row=1, column=0, columnspan=3)
        playlist.grid(row=4, column=0, columnspan=4)

        # initialize cart queue
        self._cart_queue = CartQueue(self._cart_start, self._cart_stop)
        self._cart_queue.add_tracks()
        self._update_ui()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()

    def _scroll_playlist(self, *args):
        """Scroll the playlist view.

        :param args
        """
        self._list_time.yview(*args)
        self._list_track.yview(*args)
        self._list_artist.yview(*args)

    def _update_state(self):
        """Move Automation to the next state.

        The state machine is as follows:
        STATE_STOPPED -> STATE_PLAYING -> STATE_STOPPING -> STATE_STOPPED
        """
        if self._state is STATE_STOPPED:
            print "Starting Automation..."
            self._cart_queue.start()
            self._state = STATE_PLAYING
        elif self._state is STATE_PLAYING:
            print "Stopping Automation after this track..."
            self._cart_queue.stop_soft()
            self._state = STATE_STOPPING
        elif self._state is STATE_STOPPING:
            print "Stopping Automation immediately."
            self._cart_queue.transition()
            self._state = STATE_STOPPED
        self._update_ui()

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()
        self._update_ui()

    def _cart_stop(self):
        """Reset the meter when a cart stops.

        Also, if a soft stop occured, update the button state.
        """
        self._meter.reset()

        if self._state is STATE_STOPPING:
            self._state = STATE_STOPPED
            self._update_ui()

    def _update_ui(self):
        """Update the button and playlist."""
        self._button_text.set(TEXT_BUTTON[self._state])
        self._button.config(bg=COLOR_BUTTON[self._state],
                            highlightbackground=COLOR_BUTTON[self._state])

        self._list_time.delete(0, Tkinter.END)
        self._list_track.delete(0, Tkinter.END)
        self._list_artist.delete(0, Tkinter.END)

        for cart in self._cart_queue.get_queue():
            self._list_time.insert(Tkinter.END,
                                   cart.start_time.strftime("%I:%M:%S %p"))
            self._list_track.insert(Tkinter.END, cart.title)
            self._list_artist.insert(Tkinter.END, cart.issuer)

    def _get_meter_data(self):
        """Get meter data for the first track in the queue."""
        queue = self._cart_queue.get_queue()

        if len(queue) > 0:
            return queue[0].get_meter_data()
        else:
            return None
Example #60
-1
    def startUI(self):

        self.parent.title("Testing")

        self.file_list = listdir(getcwd())

        fileBox = Listbox(self.parent, selectmode=SINGLE)
        fileBox.pack()
        fileBox.grid(column=0, row=1, columnspan=3, rowspan=10, sticky=N + S)

        textBox = Text(self.parent)
        textBox.grid(column=4, row=0, columnspan=4, rowspan=10, sticky=N + S + E)

        ipBox = Entry(self.parent)
        ipBox.grid(column=0, row=0)

        btn = Button(text="Open ->", command=lambda: self.readFile(fileBox, textBox))
        btn.grid(column=3, row=2)

        btnFire = Button(text="Fire away!", command=lambda: self.fireTorpedoes(ipBox, textBox))
        btnFire.grid(column=3, row=3)

        scrlBar = Scrollbar(self.parent, command=textBox.yview)
        scrlBar.grid(column=8, row=0, rowspan=10, sticky=N + S)
        textBox.config(yscrollcommand=scrlBar.set)

        for i in self.file_list:
            fileBox.insert(END, i)