Ejemplo n.º 1
0
    def nuevoPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaPais(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)
Ejemplo n.º 2
0
class NodeInfoDialog(tkSimpleDialog.Dialog):

    _label_var = None
    _theta_var = None

    def body(self, master):

        Label(master, text="Label:").grid(row=0, sticky=W)
        Label(master, text="Theta (deg):").grid(row=1, sticky=W)

        self._label_var = StringVar(master, value=NodeInfoDialog._label_var)
        self._theta_var = StringVar(master, value=NodeInfoDialog._theta_var)

        self.e1 = Entry(master, textvariable=self._label_var)
        self.e2 = Entry(master, textvariable=self._theta_var)

        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        return self.e1  # initial focus

    def validate(self):
        if not self.e2.get() == "":
            theta = float(self.e2.get())
            if theta < -360.0 or theta > 360.0:
                tkMessageBox.showerror(
                    "Invalid Theta value",
                    "Insert a value between -360° and 360°")
                self.e2.delete(0, 'end')
                return 0
            else:
                return 1
        else:
            return 1

    def apply(self):
        label = self.e1.get()
        theta = self.e2.get()

        self.result = label, theta

    @staticmethod
    def setLabelField(label):
        NodeInfoDialog._label_var = str(label)

    @staticmethod
    def setThetaField(theta):
        NodeInfoDialog._theta_var = str(theta)
Ejemplo n.º 3
0
class Login(Frame):
    """******** Funcion: __init__ **************
    Descripcion: Constructor de Login
    Parametros:
    self Login
    parent Tk
    Retorno: void
    *****************************************************"""
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()


    """******** Funcion: initUI **************
    Descripcion: Inicia la interfaz grafica de un Login,
                para ello hace uso de Frames y Widgets.
    Parametros:
    self Login
    Retorno: void
    *****************************************************"""
    def initUI(self):
        self.parent.title("Pythagram: Login")
        self.style = Style()
        self.style.theme_use("default")

        self.frame = Frame(self, relief=RAISED)
        self.frame.pack(fill=BOTH, expand=1)
        self.instructions = Label(self.frame,text="A new Web Browser window will open, you must log-in and accept the permissions to use this app.\nThen you have to copy the code that appears and paste it on the next text box.")
        self.instructions.pack(fill=BOTH, padx=5,pady=5)
        self.codeLabel = Label(self.frame,text="Code:")
        self.codeLabel.pack(fill=BOTH, padx=5,pady=5)
        self.codeEntry = Entry(self.frame)
        self.codeEntry.pack(fill=BOTH, padx=5,pady=5)
        self.pack(fill=BOTH, expand=1)

        self.closeButton = Button(self, text="Cancel", command=self.quit)
        self.closeButton.pack(side=RIGHT, padx=5, pady=5)
        self.okButton = Button(self, text="OK", command=self.login)
        self.okButton.pack(side=RIGHT)

    """******** Funcion: login **************
    Descripcion: Luego que el usuario ingresa su codigo de acceso, hace
                la solicitud al servidor para cargar su cuenta en una
                ventana de tipo Profile
    Parametros:
    self
    Retorno: Retorna...
    *****************************************************"""
    def login(self):
        code = self.codeEntry.get()
        api = InstagramAPI(code)
        raw = api.call_resource('users', 'info', user_id='self')
        data = raw['data']
        self.newWindow = Toplevel(self.parent)
        global GlobalID
        GlobalID = data['id']
        p = Profile(self.newWindow,api,data['id'])
Ejemplo n.º 4
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("simple")
        self.i0 = IntVar()
        self.nvt = IntVar()
        self.R = IntVar()

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(3, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(4, pad=3)

        #        i0
        self.entryi0 = Entry(self)
        self.entryi0.grid(row=0, column=1, sticky=W + E)
        cb = Checkbutton(self, text="i0", variable=self.i0)
        cb.select()
        cb.grid(row=1, column=1)
        cblabel = Label(self, text="use Value?")
        cblabel.grid(row=2, column=1)

        #        nvt
        self.entrynvt = Entry(self)
        self.entrynvt.grid(row=0, column=2, sticky=W + E)
        cb = Checkbutton(self, text="nVt", variable=self.nvt)
        cb.select()
        cb.grid(row=1, column=2)
        cblabel = Label(self, text="use Value?")
        cblabel.grid(row=2, column=2)

        #       R
        self.entryR = Entry(self)
        self.entryR.grid(row=0, column=3, sticky=W + E)
        cb = Checkbutton(self, text="R", variable=self.R)
        cb.select()
        cb.grid(row=1, column=3)
        cblabel = Label(self, text="use Value?")
        cblabel.grid(row=2, column=3)

        quitbutton = Button(self, text="quit", command=self.parent.destroy)
        quitbutton.grid(row=8, column=0)

        refreshbutton = Button(self, text="refresh", command=self.onClick)
        refreshbutton.grid(row=8, column=4)

        self.pack()

    def onClick(self):
        #        self.i0 = self.entryi0.get()
        print("i0:" + str(self.entryi0.get()))
Ejemplo n.º 5
0
    def initUI(self):
        self.parent.title("Software Activation")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        if(self.needsActivated()):
            idEntry = Entry(self, width=36)
            idEntry.place(x=175, y=20)
            idEntry.delete(0, END)
            idEntry.insert(0, "Enter a product id")
            
            keyEntry = Entry(self, width=36)
            keyEntry.place(x=175, y=40)
            keyEntry.delete(0, END)
            keyEntry.insert(0, "Enter your license key")
            
            activateButton = Button(self, text="Activate",
                                    command=lambda:self.activate(
                                        idEntry.get(), keyEntry.get()))
            activateButton.place(x=250, y=65)
        else:
            label = Label(self, text="Product has already been activated")
            label.pack()
Ejemplo n.º 6
0
    def editarParroquia(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorParroquial.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorParroquial.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarParroquia(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)
Ejemplo n.º 7
0
class MyEntry:
#Класс для уменьшений объёма кода однотипных элементов для ввода параметров.
    def __init__(self, place_class, string_class, DefaultValue, choise_class = False, button_add = False):
#При создании принимается место прикрепления виджета и строковое значение для надписи.
# A string value to add a combobox or a button could be also inputed.

        def button_finfo():
            messagebox.showinfo(locale(u"ui_iftxt", Settingz["str_langu"]), button_add)
# Here it is a function to show information window.

        self.frame_class = Frame(place_class)
        self.frame_class.pack(side = TOP, fill = BOTH)
#Внутри – рамка для виджетов, растягивается по ширине окна.
        self.label_class = Label(self.frame_class, text = string_class)
        self.label_class.pack(side = LEFT)
#В ней – надписи для описания вводимых значений выровнены по левому краю.
        self.entry_class = Entry(self.frame_class, width = 15)
        self.entry_class.pack(side = RIGHT)
        self.entry_class.insert(0, DefaultValue)
#И элементы для ввода значений шириной в 15 знаков выровнены по правому краю.
        if choise_class:
            self.box_class = Combobox(self.frame_class, values = choise_class, width = 2)
            self.box_class.set(choise_class[0])
            self.box_class.pack(side = RIGHT)
        elif button_add:
            self.button_class = Button(self.frame_class, text = u"?", command = button_finfo, width = -1)
            self.button_class.pack(side = RIGHT)
# The combobox widget or the button will be created if it is set.

    def get(self):
        return(self.entry_class.get())
#Метод .get() передаётся от элемента для ввода объекту описываемого класса.
    def getbox(self):
        if self.box_class.get() in ["+", "~"]:
            return(True)
        else:
            return(False)
Ejemplo n.º 8
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack(fill=BOTH, expand=1)
        self.initUI()
        self.setGeometry()
        self.component = NewComponent()

    def setGeometry(self):
        x = 300
        y = 100
        self.master.geometry("400x300+%d+%d" % (x, y))
        self.master.update()


    def initUI(self):
        #setup title
        self.master.title("Component Creator")
        self.style = Style()
        self.style.theme_use("clam")

        #indicator label
        self.labelName = Label(self, text="Component Name:")
        self.labelName.place(x=10, y=10)
        self.master.update()

        # create variable and namefield for input of component name
        sv = StringVar()
        sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv))
        self.nameField = Entry(self, textvariable=sv)
        self.nameField.place(x=10+self.labelName.winfo_width() + 10, y=10)
        self.master.update()

        # label for image name that will show img name for a given component name
        self.imgNameVar = StringVar()
        self.imgNameVar.set('imageName:')
        self.labelImageName = Label(self, textvariable=self.imgNameVar)
        self.labelImageName.place(x=10+self.labelName.winfo_width()+10,y=40)

        # checkbox for visible component or not
        self.cbVar = IntVar()
        self.cb = Checkbutton(self, text="Visible Component",  variable=self.cbVar)
        self.cb.place(x=10, y=70)

        # dropdown list for category
        self.labelCategory = Label(self, text="Category:")
        self.labelCategory.place(x=10, y=110)
        self.master.update()

        acts = ['UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage',
                'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized']

        self.catBox = Combobox(self, values=acts)
        self.catBox.place(x=10+self.labelCategory.winfo_width()+10, y=110)

        # button to select icon image
        self.getImageButton = Button(self, text="Select icon", command=self.getImage)
        self.getImageButton.place(x=10, y=150)
        self.master.update()

        # explanation for resizing
        self.resizeVar = IntVar()
        self.resizeCB = Checkbutton(self,
            text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar)
        self.resizeCB.place(x=10+self.getImageButton.winfo_width()+10, y=150)

        # create button
        self.createButton = Button(self, text="Create", command=self.create)
        self.createButton.place(x=10, y=230)

        #cancel button
        self.cancelButton = Button(self, text="Cancel", command=self.quit)
        self.cancelButton.place(x=200, y=230)


    # open file picker for selecting an icon
    def getImage(self):
        ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')), ('All files', '*')]
        self.component.imgFile = askopenfilename(filetypes=ftypes, title="Select an Icon file")

    # update component name and image name for component by lowercasing first letter
    def nameChanged(self, sv):
        s = sv.get()
        self.component.compName = s
        self.component.compImgName = s[:1].lower() + s[1:] if s else ''
        self.imgNameVar.set('imageName: %s' % self.component.compImgName)

    # tries to create component
    def create(self):
        # sets parameters for new component based on input values
        self.component.visibleComponent = bool(self.cbVar.get())
        self.component.resizeImage = bool(self.resizeVar.get())
        self.component.category = self.catBox.get().upper()
        self.component.compName = self.nameField.get()

        try:
            # check if component already exists
            try:
                open('../../components/src/com/google/appinentor/components/runtime/%s.java', 'r')
                tkMessageBox.showerror("Duplicate Component","%s already exists" % self.component.compName)
            # if doesnt exist will raise error
            except IOError:
                # check for name input
                if not self.component.compImgName:
                    tkMessageBox.showerror("Missing Name","Please enter component name")
                    return

                #check for category selection
                if not self.component.category:
                    tkMessageBox.showerror("Missing Category","Please select a category")
                    return

                # check if selected an icon
                if not self.component.imgFile:
                    tkMessageBox.showerror("Missing Icon","Please select an icon image")
                    return

                # copy image file to folder, can get error if user checked resize and doest have PIL installed
                try:
                    self.component.copyImageToFolder()
                except ImportError, e:
                    tkMessageBox.showerror("Unable to import PIL","Please install PIL or unselect checkbox")
                    return

                # add references to the image file, can get error if component already exists
                try:
                    self.component.addImageReference()
                except DuplicateError, e:
                    tkMessageBox.showerror("Duplicate Component","%s already exists" % self.component.compName)
                    return

                # will create mock component if is visible and add references to SimpleComponentDescriptor
                self.component.createMockComponent()

                # will create the actual component file
                self.component.createComponent()

                tkMessageBox.showinfo('Success', 'Component created successfully')
Ejemplo n.º 9
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'登录')
        self.root.resizable(False, False)
        self.root.geometry('+450+250')
        self.sysfont = Font(self.root, size=15)
        self.lb_user = Label(self.root,
                             text=u'用户名:',
                             width=20,
                             height=10,
                             font=("黑体", 15, "bold"))
        self.lb_passwd1 = Label(self.root, text=u'')
        self.lb_passwd = Label(self.root,
                               text=u'密码:',
                               width=20,
                               height=5,
                               font=("黑体", 15, "bold"))
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd1.grid(row=1, column=0, sticky=W)
        self.lb_passwd.grid(row=2, column=0, sticky=W)

        self.en_user = Entry(self.root, font=self.sysfont, width=24)
        self.en_passwd = Entry(self.root, font=self.sysfont, width=24)
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=2, column=1, columnspan=1)
        self.en_user.insert(0, u'请输入用户名')
        self.en_passwd.insert(0, u'请输入密码')
        self.en_user.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_user'),
            invalidcommand=lambda: self.invalid_func('self.en_user'))
        self.en_passwd.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_passwd'),
            invalidcommand=lambda: self.invalid_func('self.en_passwd'))

        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码',
                               underline=0,
                               variable=self.var,
                               font=(15))
        self.ckb.grid(row=3, column=0)
        self.bt_print = Button(self.root, text=u'登陆')
        self.bt_print.grid(row=3, column=1, sticky=E, pady=50, padx=10)
        self.bt_print.config(command=self.print_info)

        self.bt_http = Button(self.root, text=u'http登录')
        self.bt_http.grid(row=3, column=2, sticky=E, pady=50, padx=50)
        self.bt_http.config(command=self.http_info)

        self.bt_register = Button(self.root, text=u'注册')
        self.bt_register.grid(row=3, column=3, sticky=E, pady=50, padx=50)
        self.bt_register.config(command=self.register_info)
        self.root.mainloop()

    def validate_func(self, en):
        return False if eval(en).get().strip() != '' else True

    def invalid_func(self, en):
        value = eval(en).get().strip()
        if value == u'输入用户名' or value == u'输入密码':
            eval(en).delete(0, END)
        if en == 'self.en_passwd':
            eval(en).config(show='*')

    def print_info(self):
        en1_value = self.en_user.get().strip()
        en2_value = self.en_passwd.get().strip()
        txt = u'''用户名: %s \n密码  : %s ''' % (self.en_user.get(),
                                            self.en_passwd.get())
        if en1_value == '' or en1_value == u'输入用户名':
            showwarning(u'无用户名', u'请输入用户名')
        elif en2_value == '' or en2_value == u'输入密码':
            showwarning(u'无密码', u'请输入密码')
        else:
            a = 0

            ip_port = ('127.0.0.1', 9999)
            regInfo = [en1_value, en2_value]

            tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            tcpCliSock.connect(ip_port)
            datastr = json.dumps(regInfo)
            tcpCliSock.send(datastr.encode('utf-8'))
            data_sign = tcpCliSock.recv(1024)
            tcpCliSock.close()

            if data_sign == '0':
                a = 1
                print "数据库连接及验证成功!!!".decode("utf-8").encode("gb2312")
                showinfo('登陆成功!!!', txt)
                self.Chat()
                # # 打印结果
            else:
                print "Error: unable to fecth data"

            if (a == 0):
                showinfo('用户名或密码错误!!!', txt)

    def Chat(self):
        self.rootC = Toplevel()
        ChatClient(self.rootC)
        self.root.withdraw()

    def http_info(self):
        webbrowser.open("http://localhost:3000/login", new=0, autoraise=True)

    def register_info(self):
        self.rootR = Toplevel()
        loginPage(self.rootR)
        #self.root.withdraw()

    def enter_print(self, event):
        self.print_info()
Ejemplo n.º 10
0
class MainFrame(Frame):

    TOP_FRAME_BACKGROUND_COLOR = 'gray75'

    w_ = 500
    h_ = 400

    a_ = 5.
    b_ = 5.

    pad_l = 10

    def __init__(self, parent):
        Frame.__init__(self, parent, background='white')

        self.parent_ = parent

        # this is the main frame we are working on
        self.img_frame = Frame(self, background='navy')
        self.entry1 = None
        self.entry2 = None
        self.cb = None

        #
        self.init_ui()
        self.centering()

        # broken TV app))
        # while True:
        self.state = 0
        self.init_random_image()
        # time.sleep(0.05)

    def centering(self):
        pos_x = (self.parent_.winfo_screenwidth() - self.w_) / 2
        pos_y = (self.parent_.winfo_screenheight() - self.h_) / 2

        self.parent_.geometry('{}x{}+{}+{}'.format(self.w_, self.h_, pos_x, pos_y))

    def init_ui(self):
        self.parent_.title('Rough surface generator')
        self.pack(fill=BOTH, expand=True)

        # top panel with controls
        frame_top = Frame(self, background=self.TOP_FRAME_BACKGROUND_COLOR)
        frame_top.pack(fill=X)

        self.cb = Combobox(frame_top, values=('Gaussian', 'Laplace'))
        self.cb.current(0)
        self.cb.pack(side=LEFT, padx=5, expand=True)

        l1 = Label(frame_top, text=r'Cx', background=self.TOP_FRAME_BACKGROUND_COLOR, width=4)
        l1.pack(side=LEFT, padx=5, expand=True)

        self.entry1 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry1.pack(side=LEFT, padx=5, expand=True)
        self.entry1.insert(0, str(self.a_))

        l1 = Label(frame_top, text=r'Cy', width=4, background=self.TOP_FRAME_BACKGROUND_COLOR)
        l1.pack(side=LEFT, padx=5)

        self.entry2 = Entry(frame_top,
                            validate='key',
                            validatecommand=(self.register(self.on_validate),
                                             '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'),
                            width=10)
        self.entry2.pack(side=LEFT, padx=5, expand=True)
        self.entry2.insert(0, str(self.b_))

        but1 = Button(frame_top, text='RUN', command=self.button_action)
        but1.pack(side=RIGHT, padx=5, pady=5)

        # central panel. It will have a label with an image. Image may have a random noise state, or
        # transformed image state
        self.img_frame.pack(fill=BOTH, expand=True)
        img_label = Label(self.img_frame, background=None)
        img_label.pack(expand=True, fill=BOTH, padx=5, pady=5)

    def on_validate(self, d, i, P, s, S, v, V, W):
        """
        :param d: type of action: 1 - insert, 0 - delete, -1 - other
        :param i: index of char string to be inserted/deleted, or -1
        :param P: value of the entry if the edit is allowed
        :param s: value of entry prior to editing
        :param S: the text string being inserted or deleted, if any
        :param v: the type of validation that is currently set
        :param V: the type of validation that triggered the callback
                    (key, focusin, focusout, forced)
        :param W: the tk name of the widget
        :return: True/False -> Valid / Invalid

        Found it here:
            https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter
        Very good answer!
        """

        if d == '1':
            if W == str(self.entry1):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry1.delete(0, 'end')
                    self.entry1.insert(0, s)

                    print("Not a number, entry 1")
                    return False
            if W == str(self.entry2):
                try:
                    float(s + S)
                    return True
                except ValueError:
                    self.entry2.delete(0, 'end')
                    self.entry2.insert(0, s)

                    print("Not a number, entry 2")
                    return False
        return True

    def init_random_image(self):
        """
            Create a rough surface image from a random noise
        """
        self.update()

        # set a colormap
        c_map = cm.get_cmap('bwr')

        # width and height of the image
        w_ = self.img_frame.winfo_width()-self.pad_l
        h_ = self.img_frame.winfo_height()-self.pad_l

        # generate random noise
        random_map = np.random.random((h_, w_))

        # generate a meshgrid for the filter
        xv, yv = np.meshgrid(np.linspace(-int(w_ / 2.), int(w_ / 2.), w_),
                             np.linspace(-int(h_ / 2.), int(h_ / 2.), h_))

        # define correlation length and width
        if len(self.entry1.get()) > 0:
            clx = float(self.entry1.get())
        else:
            return

        if len(self.entry2.get()) > 0:
            cly = float(self.entry2.get())
        else:
            return

        #
        if self.cb.get().startswith('G'):
            # Gaussian filter
            filter_ = np.exp(-np.power(xv, 2) / clx - np.power(yv, 2) / cly)
        else:
            # Laplace filter
            filter_ = np.exp(-np.abs(xv) / clx - np.abs(yv) / cly)

        # this is a resulting map
        random_map = np.fft.ifft2(np.multiply(np.fft.fft2(random_map), np.fft.fft2(filter_)))
        random_map = np.real(random_map)

        # normalize to [0, 1]
        random_map -= np.min(random_map)
        random_map /= np.max(random_map)

        # create PhotoImage object to add on the panel
        img = ImageTk.PhotoImage(
            Image.fromarray(
                # image really likes unsigned ints))
                np.uint8(
                    # convert to colormap you like
                    c_map(
                        # give a random image to color map with values between 0 and 1
                        # np.random.random(
                        #     (self.img_frame.winfo_height()-self.pad_l, self.img_frame.winfo_width()-self.pad_l)
                        # )
                        random_map
                    )*255
                )
            )
        )

        # Gray colormap
        # img = ImageTk.PhotoImage(
        #     Image.fromarray(np.random.random_integers(0, 255,
        #                                   (self.img_frame.winfo_height()-self.pad_l,
        #                                    self.img_frame.winfo_width()-self.pad_l)).astype(np.int8)
        #                     ).convert('L')
        # )

        keys = self.img_frame.children.keys()
        for key in keys:
            self.img_frame.children[key].configure(image=img)
            self.img_frame.children[key].image = img

    def button_action(self):
        """
        """
        self.init_random_image()
Ejemplo n.º 11
0
class Search(Frame):
    """******** Funcion: __init__ **************
    Descripcion: Constructor de Search
    Parametros:
    self Search
    parent Tk
    api InstagramAPI
    id str
    Retorno: void
    *****************************************************"""
    def __init__(self,parent,api,id):
        Frame.__init__(self, parent)
        self.parent = parent
        self.api = api
        self.id = id
        self.anySearch = False
        self.initUI()

    """******** Funcion: initUI **************
    Descripcion: Crea una nueva ventana de busqueda con un
                text box y un boton
    Parametros:
    self Search
    Retorno: void
    *****************************************************"""
    def initUI(self):
        self.parent.title("Pythagram: Search")
        self.style = Style()
        self.style.theme_use("default")

        self.frame = Frame(self,relief=RAISED)
        self.frame.pack(fill=BOTH, expand=1)
        searchLabel = Label(self.frame, text="Search")
        self.searchEntry = Entry(self.frame)
        searchLabel.pack(fill=BOTH, padx=5,pady=5)
        self.searchEntry.pack(fill=BOTH, padx=5,pady=5)
        self.pack(fill=BOTH, expand=1)

        okButton = Button(self, text="OK", command=self.search)
        okButton.pack(side=RIGHT, padx=5, pady=5)

    """******** Funcion: search **************
    Descripcion: realiza la busqueda en el servidor segun el
                texto ingresado en el campo de texto
    Parametros:
    self Search
    Retorno: void
    *****************************************************"""
    def search(self):
        if (self.anySearch):
            self.lb.pack_forget()
        query = self.searchEntry.get()
        p = { "q": query}
        raw = self.api.call_resource('users', 'search', params=p)
        data = raw['data']
        self.results = []
        self.lb = Listbox(self.frame, width=100)
        for element in data:
            try:
                self.lb.insert(END, "@{0}: {1}".format(element['username'],element['full_name']))
            except:
                continue
            self.results.append(element['id'])
        self.lb.bind("<<ListboxSelect>>", self.onSelect)
        self.lb.pack(side=LEFT, padx=5, pady=5)
        self.pack(fill=BOTH, expand=1)
        self.anySearch = True

    """******** Funcion: onSelect **************
    Descripcion: abre una nueva ventana con el perfil seleccionado
                en la lista de resultados
    Parametros:
    self Profile
    val
    Retorno: void
    *****************************************************"""
    def onSelect(self,val):
        sender = val.widget
        idx = sender.curselection()
        self.newWindow = Toplevel(self.parent)
        p = Profile(self.newWindow,self.api,self.results[int(idx[0])])
Ejemplo n.º 12
0
    def ventanaVoluntarios(self,row):

        id = -1
        guardar = TRUE
        # Creamos una ventana nueva
        t = Toplevel(self)
        t.wm_title("Crear Voluntario")

        # Etiqueta y entrada de nombre
        Label(t, text="Nombre").grid(row=0)
        entradaNombre = Entry(t)
        entradaNombre.grid(row=0, column=1,sticky = "ew")

        # Etiqueta y entrada de apellidos
        Label(t, text="Apellidos").grid(row=1)
        entradaApellidos = Entry(t)
        entradaApellidos.grid(row=1, column=1,sticky = "ew")

        # Etiqueta y entrada de DNI
        Label(t, text="DNI").grid(row=2)
        entradaDNI = Entry(t)
        entradaDNI.grid(row=2, column=1,sticky = "ew")

        # Etiqueta y entrada de Dirreccion
        Label(t, text="Direccion").grid(row=3)
        entradaDireccion = Entry(t)
        entradaDireccion.grid(row=3, column=1)

        # Etiqueta y seleccion de Estudios
        Label(t, text="Estudios").grid(row=4)
        box_value = StringVar()
        self.getEstudios()
        self.selectorEstudios = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorEstudios['values'] = self.listadoEstudios[0]
        self.selectorEstudios.configure(width=25)
        self.selectorEstudios.current(0)
        self.selectorEstudios.grid(row=4, column=1)

        botonEditarEstudios = Button(t, text="Editar", command=self.editarEstudio)
        botonNuevosEstudios = Button(t, text="Nuevo", command=self.nuevoEstudio)
        botonEditarEstudios.grid(row=4, column=2)
        botonNuevosEstudios.grid(row=4, column=3)

        # Etiqueta y seleccion de Genero
        Label(t, text="Genero").grid(row=5)
        seleccionGenero = Combobox(t, values=["Masculino (M)", "Femenino (F)"], state='readonly')
        seleccionGenero.grid(row=5, column=1)

        # Etiqueta y seleccion de Parroquial
        Label(t, text="Parroquial").grid(row=6)
        box_value = StringVar()
        self.getParroquial()
        self.selectorParroquial = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorParroquial['values'] = self.listadoParroquial[0]
        self.selectorParroquial.configure(width=25)
        self.selectorParroquial.current(0)
        self.selectorParroquial.grid(row=6, column=1)

        botonEditarParroquial = Button(t, text="Editar", command=self.editarParroquia)
        botonNuevaParroqual = Button(t, text="Nuevo", command=self.nuevaParroquia)
        botonEditarParroquial.grid(row=6, column=2)
        botonNuevaParroqual.grid(row=6, column=3)

        # Etiqueta y seleccion de Correo
        Label(t, text="Correo").grid(row=0, column=4)
        entradaCorreo = Entry(t)
        entradaCorreo.grid(row=0, column=5)

        Label(t, text="Telefono 1").grid(row=1, column=4)
        entradaTelefono1 = Entry(t)
        entradaTelefono1.grid(row=1, column=5)

        Label(t, text="Telefono 2").grid(row=2, column=4)
        entradaTelefono2 = Entry(t)
        entradaTelefono2.grid(row=2, column=5)

        # Etiqueta y entrada de Fecha
        Label(t, text="Fecha").grid(row=3, column=4)
        entradaAno = Entry(t)
        entradaMes = Entry(t)
        entradaDia = Entry(t)
        entradaAno.grid(row=3, column=5)
        entradaMes.grid(row=3, column=6)
        entradaDia.grid(row=3, column=7)

        # Etiqueta y seleccion de Pais
        Label(t, text="Pais").grid(row=4, column=4)
        box_value = StringVar()
        self.getPais()
        self.selectorPais = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorPais['values'] = self.listadoPais[0]
        self.selectorPais.configure(width=25)
        self.selectorPais.current(0)
        self.selectorPais.grid(row=4, column=5)

        botonEditarPais = Button(t, text="Editar", command=self.editarPais)
        botonNuevaPais = Button(t, text="Nuevo", command=self.nuevoPais)
        botonEditarPais.grid(row=4, column=6)
        botonNuevaPais.grid(row=4, column=7)

        #Rellenamos los cambos si estamos editando
        if row > -1:
            voluntario = self.table.model.getRecordAtRow(row)
            entradaNombre.insert(END,voluntario['nombre'])
            entradaApellidos.insert(END,voluntario['apellidos'])
            entradaCorreo.insert(END,voluntario['correo_electronico'])
            entradaTelefono1.insert(END,voluntario['telefono_1'])
            entradaTelefono2.insert(END,voluntario['telefono_2'])
            entradaDireccion.insert(END,voluntario['direccion'])
            entradaDNI.insert(END,voluntario['dni'])
            self.selectorEstudios.set(voluntario['estudio'])
            self.selectorParroquial.set(voluntario['parroquial'])
            guardar = FALSE
            id = voluntario['id']





        button5 = Button(t, text="Guardar", command=lambda: self.nuevoVoluntario(entradaNombre.get(),
                                                                                 entradaApellidos.get(),entradaDNI.get(),entradaDireccion.get(),
                                                                                 entradaCorreo.get(),1,self.listadoEstudios[1][self.selectorEstudios.current()],
                                                                                 self.listadoParroquial[1][self.selectorParroquial.current()],
                                                                                 1,entradaTelefono1.get(),entradaTelefono2.get(),"M","2001-01-01",t,guardar,id))
        button6 = Button(t, text="Cancelar", command=t.destroy)

        button5.grid(row=7, column=4)
        button6.grid(row=7, column=5)
Ejemplo n.º 13
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 20, 'bold')
        labelfont12 = ('Roboto', 12, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi USER")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Search here")
        lbl00.config(font=labelfont12)
        lbl00.pack(padx=5, pady=5)

        frame1 = Frame(self)
        frame1.pack()

        lbl1 = Label(frame1, text="min %", width=9)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        frame6 = Frame(self)
        frame6.pack()
        closeButton = Button(frame6,
                             text="Get Names",
                             width=12,
                             command=self.getDate)
        closeButton.pack(padx=5, pady=5)

        frame7 = Frame(self)
        frame7.pack()
        closeButton1 = Button(frame7,
                              text="Open in excel",
                              width=15,
                              command=self.openDate)
        closeButton1.pack(padx=5, pady=5)

        frame000 = Frame(self)
        frame000.pack()
        self.lbl000 = Label(frame000, text=" ")
        self.lbl000.config(font=labelfont12)
        self.lbl000.pack(padx=5, pady=5)

        frame00a = Frame(self)
        frame00a.pack()
        self.lbl00a = Label(frame000, text=" ")
        self.lbl00a.pack(padx=5, pady=5)

    def getDate(self):
        x1 = self.entry1.get()
        nx = ""

        self.entry1.delete(0, 'end')

        self.lbl000.config(text="Names Are:")

        #read csv, and split on "," the line
        csv_file = csv.reader(open('test.csv', "rb"), delimiter=",")
        #loop through csv list
        for row in csv_file:
            if row[2] >= x1:
                nx += str(row[0] + ", ")
                with open("output5.csv", "ab") as fp:
                    wr = csv.writer(fp, dialect='excel')
                    wr.writerow(row)
                fp.close()
        self.lbl00a.config(text=nx)

    def openDate(self):
        os.system("start " + 'output5.csv')
Ejemplo n.º 14
0
        self.event_generate('<Expose>')

    def last_page(self):
        """Return the last page in the notebook."""
        return self.pages[self.tab(self.index('end') - 1)['text']]

if __name__ == '__main__':
    from Tkinter import Tk
    from Tkconstants import TOP, BOTH
    from ttk import Label, Entry, Button, Style
    # test dialog
    root=Tk()
    style = Style()
    style.configure('C.TLabel', padding=20)
    tabPage=TabbedPageSet(root, page_names=['Foobar','Baz'])
    tabPage.pack(side=TOP, expand=True, fill=BOTH)
    Label(tabPage.pages['Foobar'].frame, text='Foo', style='C.TLabel').pack()
    Label(tabPage.pages['Foobar'].frame, text='Bar', style='C.TLabel').pack()
    Label(tabPage.pages['Baz'].frame, text='Baz').pack()
    entryPgName=Entry(root)
    buttonAdd=Button(root, text='Add Page',
            command=lambda:tabPage.add_page(entryPgName.get()))
    buttonRemove=Button(root, text='Remove Page',
            command=lambda:tabPage.remove_page(entryPgName.get()))
    labelPgName=Label(root, text='name of page to add/remove:')
    buttonAdd.pack(padx=5, pady=5)
    buttonRemove.pack(padx=5, pady=5)
    labelPgName.pack(padx=5)
    entryPgName.pack(padx=5)
    root.mainloop()
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack(fill=BOTH, expand=1)
        self.initUI()
        self.setGeometry()
        self.component = NewComponent()

    def setGeometry(self):
        x = 300
        y = 100
        self.master.geometry("400x300+%d+%d" % (x, y))
        self.master.update()

    def initUI(self):
        #setup title
        self.master.title("Component Creator")
        self.style = Style()
        self.style.theme_use("clam")

        #indicator label
        self.labelName = Label(self, text="Component Name:")
        self.labelName.place(x=10, y=10)
        self.master.update()

        # create variable and namefield for input of component name
        sv = StringVar()
        sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv))
        self.nameField = Entry(self, textvariable=sv)
        self.nameField.place(x=10 + self.labelName.winfo_width() + 10, y=10)
        self.master.update()

        # label for image name that will show img name for a given component name
        self.imgNameVar = StringVar()
        self.imgNameVar.set('imageName:')
        self.labelImageName = Label(self, textvariable=self.imgNameVar)
        self.labelImageName.place(x=10 + self.labelName.winfo_width() + 10,
                                  y=40)

        # checkbox for visible component or not
        self.cbVar = IntVar()
        self.cb = Checkbutton(self,
                              text="Visible Component",
                              variable=self.cbVar)
        self.cb.place(x=10, y=70)

        # dropdown list for category
        self.labelCategory = Label(self, text="Category:")
        self.labelCategory.place(x=10, y=110)
        self.master.update()

        acts = [
            'UserInterface', 'Layout', 'Media', 'Animation', 'Sensors',
            'Social', 'Storage', 'Connectivity', 'LegoMindStorms',
            'Experimental', 'Internal', 'Uninitialized'
        ]

        self.catBox = Combobox(self, values=acts)
        self.catBox.place(x=10 + self.labelCategory.winfo_width() + 10, y=110)

        # button to select icon image
        self.getImageButton = Button(self,
                                     text="Select icon",
                                     command=self.getImage)
        self.getImageButton.place(x=10, y=150)
        self.master.update()

        # explanation for resizing
        self.resizeVar = IntVar()
        self.resizeCB = Checkbutton(
            self,
            text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image",
            variable=self.resizeVar)
        self.resizeCB.place(x=10 + self.getImageButton.winfo_width() + 10,
                            y=150)

        # create button
        self.createButton = Button(self, text="Create", command=self.create)
        self.createButton.place(x=10, y=230)

        #cancel button
        self.cancelButton = Button(self, text="Cancel", command=self.quit)
        self.cancelButton.place(x=200, y=230)

    # open file picker for selecting an icon
    def getImage(self):
        ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')),
                  ('All files', '*')]
        self.component.imgFile = askopenfilename(filetypes=ftypes,
                                                 title="Select an Icon file")

    # update component name and image name for component by lowercasing first letter
    def nameChanged(self, sv):
        s = sv.get()
        self.component.compName = s
        self.component.compImgName = s[:1].lower() + s[1:] if s else ''
        self.imgNameVar.set('imageName: %s' % self.component.compImgName)

    # tries to create component
    def create(self):
        # sets parameters for new component based on input values
        self.component.visibleComponent = bool(self.cbVar.get())
        self.component.resizeImage = bool(self.resizeVar.get())
        self.component.category = self.catBox.get().upper()
        self.component.compName = self.nameField.get()

        try:
            # check if component already exists
            try:
                open(
                    '../../components/src/com/google/appinentor/components/runtime/%s.java',
                    'r')
                tkMessageBox.showerror(
                    "Duplicate Component",
                    "%s already exists" % self.component.compName)
            # if doesnt exist will raise error
            except IOError:
                # check for name input
                if not self.component.compImgName:
                    tkMessageBox.showerror("Missing Name",
                                           "Please enter component name")
                    return

                #check for category selection
                if not self.component.category:
                    tkMessageBox.showerror("Missing Category",
                                           "Please select a category")
                    return

                # check if selected an icon
                if not self.component.imgFile:
                    tkMessageBox.showerror("Missing Icon",
                                           "Please select an icon image")
                    return

                # copy image file to folder, can get error if user checked resize and doest have PIL installed
                try:
                    self.component.copyImageToFolder()
                except ImportError, e:
                    tkMessageBox.showerror(
                        "Unable to import PIL",
                        "Please install PIL or unselect checkbox")
                    return

                # add references to the image file, can get error if component already exists
                try:
                    self.component.addImageReference()
                except DuplicateError, e:
                    tkMessageBox.showerror(
                        "Duplicate Component",
                        "%s already exists" % self.component.compName)
                    return

                # will create mock component if is visible and add references to SimpleComponentDescriptor
                self.component.createMockComponent()

                # will create the actual component file
                self.component.createComponent()

                tkMessageBox.showinfo('Success',
                                      'Component created successfully')
class IniGenGui(Frame):

  def __init__(self, parent):
    Frame.__init__(self, parent)
    self.parent = parent
    self.initUIGlobals()

  def initUIGlobals(self):
   
    self.parent.title("Ini Generator")

    Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10')

    f1 = Frame(self)
    f1.grid(row=0, column=0, padx=10, sticky=N+S+E+W)

    f11 = LabelFrame(f1, text="Algorithms to Run")
    f11.grid(row=0, column=0)
    row = 0

    self.check_algs_value_list = []
    self.check_algs_map = {}
    for alg in algorithms:
      if alg == 'clean':
        continue
      check_alg_value = IntVar()
      check_alg = Checkbutton(f11, text=alg, variable=check_alg_value, justify=LEFT, width=25)
      check_alg.grid(row=row, column=0, sticky=W+E)
      self.check_algs_value_list.append(check_alg_value)
      self.check_algs_map[alg] = check_alg_value
      row += 1

    f111 = Frame(f11)
    f111.grid(row=row, column=0)

    button_checkall = Button(f111, text="All", command=self.checkall)
    button_checkall.grid(row=0, column=0, sticky=W+E)
    button_uncheckall = Button(f111, text="None", command=self.uncheckall)
    button_uncheckall.grid(row=0, column=1, sticky=W+E)

    row = 0

    f12 = Frame(f1)
    f12.grid(row=1, column=0, pady=20, sticky=S+W+E)

    f121 = LabelFrame(f12, text='Location of uPMU')
    f121.grid(row=0, column=0)

    self.radio_loc_string = StringVar()
    locations.append('Other Location')
    for loc in locations:
      radio_loc = Radiobutton(f121, text=loc, variable=self.radio_loc_string, value=loc, command=self.set_loc, justify=LEFT, width=25)
      radio_loc.grid(row=row, column=0, sticky=W+E)
      row += 1

    self.entry_otherloc = Entry(f121)

    f2 = Frame(self)
    f2.grid(row=0, column=1, padx=10, sticky=N+S+E+W)

    f21 = LabelFrame(f2, text='Name of uPMU (raw)')
    f21.grid(row=0)
    row = 0

    f211 = Frame(f21)
    f211.grid(row=row)
    row += 1

    self.entry_namesearch = Entry(f211)
    self.entry_namesearch.grid(row=0, column=0, sticky=E+W)

    button_namesearch = Button(f211, text="Search", command=self.namesearch)
    button_namesearch.grid(row=0, column=1, sticky=W+E)

    self.lstbx_namelist = Listbox(f21)
    self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
    self.lstbx_namelist.grid(row=row, sticky=W+E)
    row += 1

    f212 = Frame(f21)
    f212.grid(row=row)
    row += 1

    label_nameselected = Label(f212, text="Selected:")
    label_nameselected.grid(row=0, column=0)

    self.entry_nameselected = Entry(f212, state=DISABLED)
    self.entry_nameselected.grid(row=0, column=1, sticky=W+E)

    f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
    f22.grid(row=1, sticky=W+E, pady=10)
    self.entry_name = Entry(f22, width=30)
    self.entry_name.grid(row=0, column=0, sticky=E+W)

    f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
    f23.grid(row=2, pady=10)
    row = 0

    f231 = Frame(f23)
    f231.grid(row=row)
    row += 1

    self.entry_refnamesearch = Entry(f231)
    self.entry_refnamesearch.grid(row=0, column=0, sticky=E+W)

    button_refnamesearch = Button(f231, text="Search", command=self.refnamesearch)
    button_refnamesearch.grid(row=0, column=1, sticky=W+E)

    self.lstbx_refnamelist = Listbox(f23)
    self.lstbx_refnamelist.bind("<Double-Button-1>", self.refnamelist_select)
    self.lstbx_refnamelist.grid(row=row, sticky=W+E)
    row += 1

    f232 = Frame(f23)
    f232.grid(row=row)
    row += 1

    label_refnameselected = Label(f232, text="Selected:")
    label_refnameselected.grid(row=0, column=0)

    self.entry_refnameselected = Entry(f232, state=DISABLED)
    self.entry_refnameselected.grid(row=0, column=1, sticky=W+E)

    button_gen = Button(self, text="Generate Files", command=self.generate_files)
    button_gen.grid(row=1, column=0, columnspan=2, sticky=W+E)

    self.pack()

  def generate_files(self):
    algs = []
    for alg in self.check_algs_map:
      if self.check_algs_map[alg].get() == 1:
        algs.append(alg)

    if self.radio_loc_string.get() == "Other Location":
      location = self.entry_otherloc.get()
    else:
      location = self.radio_loc_string.get()

    name_raw = self.entry_nameselected.get()
    name = self.entry_name.get()
    ref_name = self.entry_refnameselected.get()

    uuid_map = self.get_uuid_map(name_raw)
    reference_uuid_map = self.get_ref_uuid_map(ref_name)

    IniGenAutomation(location, name_raw, name, uuid_map, ref_name, reference_uuid_map, algs)

  def namesearch(self):
    searchterm = self.entry_namesearch.get()
    searchphrase = '/upmu/%{0}%/%'.format(searchterm)
    search_results = self.search(searchterm, searchphrase)
    self.lstbx_namelist.delete(0, END)
    if len(search_results) == 0:
      tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm))
    else:
      for result in search_results:
        self.lstbx_namelist.insert(END, result)
        
  def refnamesearch(self):
    searchterm = self.entry_refnamesearch.get()
    searchphrase = '/Clean/%{0}%/%'.format(searchterm)
    search_results = self.search(searchterm, searchphrase, ref=True)
    self.lstbx_refnamelist.delete(0, END)
    if len(search_results) == 0:
      tkMessageBox.showwarning('Search Error', 'No matches from search for \'{0}\''.format(searchterm))
    else:
      for result in search_results:
        self.lstbx_refnamelist.insert(END, result)
  
  def search(self, searchterm, searchphrase, ref=False):
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(searchphrase))
    results = connection.store_result()
    queried_data = {}
    result = results.fetch_row()
    while result != tuple():
      queried_data[result[0][0]] = result[0][1]
      result = results.fetch_row()
    search_results = set()
    for path in queried_data:
      dirs = path.split('/')
      if ref:
        if searchterm in '/'.join(dirs[2:-2]):
          search_results.add('/'.join(dirs[2:-2]))
      else:
        if searchterm in '/'.join(dirs[2:-1]):
          search_results.add('/'.join(dirs[2:-1]))
    return search_results

  def set_loc(self):
    if self.radio_loc_string.get() == "Other Location":
      self.entry_otherloc.grid(sticky=W+E)
    else:
      self.entry_otherloc.grid_forget()

  def checkall(self):
    for check in self.check_algs_value_list:
      check.set(1)
  
  def uncheckall(self):
    for check in self.check_algs_value_list:
      check.set(0)

  def namelist_select(self, event):
    selected_index = self.lstbx_namelist.curselection()
    selected = self.lstbx_namelist.get(selected_index)
    self.entry_nameselected.configure(state=NORMAL)
    self.entry_nameselected.delete(0, END)
    self.entry_nameselected.insert(0, selected)
    self.entry_nameselected.configure(state=DISABLED)

  def refnamelist_select(self, event):
    selected_index = self.lstbx_refnamelist.curselection()
    selected = self.lstbx_refnamelist.get(selected_index)
    self.entry_refnameselected.configure(state=NORMAL)
    self.entry_refnameselected.delete(0, END)
    self.entry_refnameselected.insert(0, selected)
    self.entry_refnameselected.configure(state=DISABLED)

  def get_uuid_map(self, name):
    uuid_map = {}
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(name))
    results = connection.store_result()
    result = results.fetch_row()
    while result != tuple():
      path = result[0][0].split('/')
      uuid_map[path[-1]] = result[0][1]
      result = results.fetch_row()
    return uuid_map
    
  def get_ref_uuid_map(self, name):
    uuid_map = {}
    connection = _mysql.connect(host="128.32.37.231", port=3306, user="******",
                                passwd="moresecuredataftw", db='upmu')
    connection.query("SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(name))
    results = connection.store_result()
    result = results.fetch_row()
    while result != tuple():
      path = result[0][0].split('/')
      uuid_map[path[-2]] = result[0][1]
      result = results.fetch_row()
    return uuid_map
Ejemplo n.º 17
0
class CHEWDDialog(ModelessDialog):
    name = "Energy Visualizer"
    buttons = ("Apply", "Close")
    help = ("Energy.html", CHEWD)
    title = "CHemical Energy Wise Decomposition"

    def fillInUI(self, parent):

        #parent.resizable(0, 0)
        frame4 = Frame(parent)
        frame4.grid(row=0, column=0, sticky="nsew")
        self.wat = IntVar()
        self.wat.set(1)
        self.waterswap = Checkbutton(frame4,
                                     text="Water Swap",
                                     command=self.optionws,
                                     variable=self.wat)
        self.waterswap.grid(row=0, column=0)
        self.lig = IntVar()
        self.lig.set(0)
        self.ligandswap = Checkbutton(frame4,
                                      text="Ligand Swap",
                                      command=self.optionls,
                                      variable=self.lig)
        self.ligandswap.grid(row=0, column=1)
        self.mm = IntVar()
        self.mm.set(0)
        self.mmpbsa = Checkbutton(frame4,
                                  text="MMPBSA",
                                  command=self.optionmm,
                                  variable=self.mm)
        self.mmpbsa.grid(row=0, column=2)

        frame1 = Frame(parent)
        frame1.grid(row=1, column=0, sticky="nsew")
        lbl1 = Label(frame1, text="Log file folder", width=12)
        lbl1.grid(row=0, column=0)
        self.entry1 = Entry(frame1)
        self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E)
        self.browserButton = Button(frame1,
                                    text="Browser",
                                    command=self.onOpen)
        self.browserButton.grid(row=0, column=5, sticky="e")

        lbl2 = Label(frame1, text="MMPBSA log file", width=12)
        lbl2.grid(row=1, column=0)
        self.entry2 = Entry(frame1, state=DISABLED)
        self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E)
        self.browserButtonMM = Button(frame1,
                                      text="Browser",
                                      command=self.onOpenMM,
                                      state=DISABLED)
        self.browserButtonMM.grid(row=1, column=5, sticky="e")

        lbl3 = Label(frame1, text="MMPBSA PDB file", width=12)
        lbl3.grid(row=2, column=0)
        self.entry3 = Entry(frame1, state=DISABLED)
        self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E)
        self.browserButtonPDB = Button(frame1,
                                       text="Browser",
                                       command=self.onOpenPDB,
                                       state=DISABLED)
        self.browserButtonPDB.grid(row=2, column=5, sticky="e")

        lbl4 = Label(frame1, text="Ligand Name", width=12)
        lbl4.grid(row=3, column=0)
        self.entry4 = Entry(frame1)
        self.entry4.grid(row=3, column=1)
        self.lblswap = Label(frame1,
                             text="Swap Ligand",
                             width=12,
                             state=DISABLED)
        self.lblswap.grid(row=3, column=2)
        self.swapentry = Entry(frame1, state=DISABLED)
        self.swapentry.grid(row=3, column=3)
        self.l1v = IntVar()
        self.l1v.set(1)
        self.lig1ck = Checkbutton(frame1,
                                  text="Ligand 1",
                                  command=self.changelig1,
                                  state=DISABLED,
                                  variable=self.l1v)
        self.lig1ck.grid(row=4, column=0)
        self.l2v = IntVar()
        self.l2v.set(0)
        self.lig2ck = Checkbutton(frame1,
                                  text="Ligand 2",
                                  command=self.changelig2,
                                  state=DISABLED,
                                  variable=self.l2v)
        self.lig2ck.grid(row=4, column=2)
        lbl5 = Label(frame1, text="Display Radius", width=12)
        lbl5.grid(row=5, column=0)
        self.entry5 = Entry(frame1)
        self.entry5.grid(row=5, column=1)
        self.entry5.insert(0, "5.0")
        self.sv = IntVar()
        self.sv.set(0)
        self.surface = Checkbutton(frame1,
                                   text="View Surface",
                                   command=self.viewsurface,
                                   variable=self.sv)
        self.surface.grid(row=5, column=2)
        self.vl = IntVar()
        self.vl.set(1)
        self.label = Checkbutton(frame1,
                                 text="View Label",
                                 command=self.viewlabel,
                                 variable=self.vl)
        self.label.grid(row=5, column=3)

        lbl6 = Label(frame1, text="Min Value", width=12)
        lbl6.grid(row=6, column=0)
        self.entry6 = Entry(frame1)
        self.entry6.grid(row=6, column=1)
        self.entry6.insert(0, "-5")
        lbl7 = Label(frame1, text="Max Value", width=12)
        lbl7.grid(row=6, column=2)
        self.entry7 = Entry(frame1)
        self.entry7.grid(row=6, column=3)
        self.entry7.insert(0, "+5")

        lbl8 = Label(frame1, text="Starting log file", width=12)
        lbl8.grid(row=7, column=0)
        self.entry8 = Entry(frame1)
        self.entry8.grid(row=7, column=1)
        self.entry8.insert(0, "400")
        lbl9 = Label(frame1, text="Ending log file", width=12)
        lbl9.grid(row=7, column=2)
        self.entry9 = Entry(frame1)
        self.entry9.grid(row=7, column=3)
        self.entry9.insert(0, "1000")

        frame2 = Frame(parent)
        frame2.grid(row=2, column=0, sticky="nsew")
        self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb)
        self.vsb.grid(row=1, column=3, sticky="ns")
        self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb1.grid(row=1, column=0)
        self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb2.grid(row=1, column=1)
        self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb3.grid(row=1, column=2)

        self.b1 = Button(frame2,
                         text="Residue Number",
                         state=DISABLED,
                         command=lambda: self.sortdata(0))
        self.b1.grid(row=0, column=0, sticky=W + E)
        self.b2 = Button(frame2,
                         text="Residue Name",
                         state=DISABLED,
                         command=lambda: self.sortdata(1))
        self.b2.grid(row=0, column=1, sticky=W + E)
        self.b3 = Button(frame2,
                         text="Energy Value",
                         state=DISABLED,
                         command=lambda: self.sortdata(2))
        self.b3.grid(row=0, column=2, sticky=W + E)

        self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
        self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
        self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
        self.lb3.bind("<MouseWheel>", self.OnMouseWheel)

        frame3 = Frame(parent)
        frame3.grid(row=3, column=0, sticky="nsew")

        self.previous = Button(frame3,
                               text="Previous Frame",
                               state=DISABLED,
                               command=self.prevframe)
        self.previous.grid(row=0, column=0, sticky=W + E)
        self.scale = Scale(frame3,
                           command=self.onScale,
                           state=DISABLED,
                           orient=HORIZONTAL,
                           length=320,
                           showvalue=0)
        self.scale.grid(row=0, column=1, sticky=W + E)
        self.next = Button(frame3,
                           text="Next Frame",
                           state=DISABLED,
                           command=self.nextframe)
        self.next.grid(row=0, column=2, sticky=W + E)

        self.var = IntVar()
        v = 000
        self.var.set(v)
        self.label = Label(frame3, text=0, textvariable=self.var)
        self.label.grid(row=0, column=3)

        ToolTip(lbl1, "Load the result directory of Sire Analysis")
        ToolTip(self.browserButton,
                "Load the result directory of Sire Analysis")
        ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file")
        ToolTip(
            lbl5,
            "The radially distributed zone around ligand you want to be displayed"
        )
        ToolTip(
            lbl6,
            "Minimum scale value for the color distribution and it will be treated as blue"
        )
        ToolTip(
            lbl7,
            "Maximum scale value for the color distribution and it will be treated as red"
        )

    def viewlabel(self):
        if (load > 0):
            if (self.wat.get() == 1):
                CHEWD.togglelabelws(self.vl.get(), str(self.scale.get()),
                                    self.entry4.get(), self.entry5.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.togglelabells(self.vl.get(), str(self.scale.get()), vl,
                                    self.entry5.get(), hl)
            elif (self.mm.get() == 1):
                CHEWD.togglelabelws(self.vl.get(), "0", self.entry4.get(),
                                    self.entry5.get())

    def viewsurface(self):
        if (load > 0):
            CHEWD.togglesurface(self.sv.get())

    def optionws(self):
        if (self.wat.get() == 1):
            self.lig.set(0)
            self.mm.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.wat.set(0)
            self.lig.set(1)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionls(self):
        if (self.lig.get() == 1):
            self.wat.set(0)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.lig.set(0)
            self.mm.set(0)
            self.wat.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionmm(self):
        if (self.mm.get() == 1):
            self.lig.set(0)
            self.wat.set(0)
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry8.config(state=DISABLED)
            self.entry9.config(state=DISABLED)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.entry2.config(state="normal")
            self.entry3.config(state="normal")
            self.browserButtonMM.config(state="normal")
            self.browserButtonPDB.config(state="normal")
        else:
            self.wat.set(1)
            self.lig.set(0)
            self.mm.set(0)
            self.entry8.config(state="normal")
            self.entry9.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def changelig1(self):
        if (self.l1v.get() == 1):
            self.l2v.set(0)
        else:
            self.l2v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                               self.entry7.get(), prevz, str(self.scale.get()),
                               hl, self.vl.get())

    def changelig2(self):
        if (self.l2v.get() == 1):
            self.l1v.set(0)
        else:
            self.l1v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                               self.entry7.get(), prevz, str(self.scale.get()),
                               hl, self.vl.get())

    def loadmmpbsaresults(self):
        fp = open(self.entry2.get(), "r")
        resv = list()
        for line in fp:
            t = line.split(',')
            t2 = t[0].split()
            if (len(t) == 20 and len(t2) == 2 and t2[0] != self.entry4.get()):
                resv.append([int(t2[1]), float(t[17]), t2[0]])
            matchObj = re.match(r'Sidechain Energy Decomposition:', line,
                                re.M | re.I)
            if matchObj:
                break
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)
        x = len(resv)
        for i in range(x):
            self.lb1.insert(END, resv[i][0])
            self.lb2.insert(END, resv[i][2])
            self.lb3.insert(END, resv[i][1])
        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        fc = open(tempfile.gettempdir() + "/clear.txt", "w")
        fp.write("attribute: sireEnergy\n")
        fp.write("recipient: residues\n")
        fc.write("attribute: sireEnergy\n")
        fc.write("recipient: residues\n")
        for i in range(x):
            fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n")
            fc.write("\t:" + str(resv[i][0]) + "\t0.0\n")
        fp.close()
        fc.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def changestate(self):
        x = list()
        tempx = list()
        if (self.wat.get() == 1):
            base = os.listdir(self.entry1.get())
        else:
            base = os.listdir(self.entry1.get() + "/")
        for a in base:
            if a.endswith(".log"):
                tempx.append(a)
        tempx.sort()
        tlen = len(tempx)
        ia = int(self.entry8.get()) - 1
        while (ia <= int(self.entry9.get()) and ia < tlen):
            x.append(tempx[ia])
            ia += 1
        resv = list()
        c = 0
        i = 0
        for fn in x:
            if (self.wat.get() == 1):
                fp = open(self.entry1.get() + "/" + fn, "r")
            else:
                fp = open(self.entry1.get() + "/" + fn, "r")
            if (c == 0):
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            resv.append([int(t[3]), float(t[5]), t[1]])
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            else:
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            resv[i][1] = resv[i][1] + float(t[5])
                            i = i + 1
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            fp.close()
        x = len(resv)
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)
        for i in range(x):
            resv[i][1] = resv[i][1] / c
        for i in range(x):
            self.lb1.insert(END, resv[i][0])
            self.lb2.insert(END, resv[i][2])
            self.lb3.insert(END, round(resv[i][1], 3))

        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        fc = open(tempfile.gettempdir() + "/clear.txt", "w")
        fp.write("attribute: sireEnergy\n")
        fp.write("recipient: residues\n")
        fc.write("attribute: sireEnergy\n")
        fc.write("recipient: residues\n")
        for i in range(x):
            fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n")
            fc.write("\t:" + str(resv[i][0]) + "\t0.0\n")
        fp.close()
        fc.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def prevframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() - 1)

    def nextframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() + 1)

    def onScale(self, val):
        global prevz, load
        if (load > 0):
            v = self.lig1pdb[int(float(val))][14:19]
            self.var.set(v)
            if (self.scale.get() == 0):
                self.previous.config(state=DISABLED)
            if (self.scale.get() == len(self.lig1pdb) - 2):
                self.next.config(state="normal")
            if (self.scale.get() == 1):
                self.previous.config(state="normal")
            if (self.scale.get() == len(self.lig1pdb) - 1):
                self.next.config(state=DISABLED)
            if (self.wat.get() == 1):
                CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   str(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), prevz,
                                   str(self.scale.get()), hl, self.vl.get())

    def OnSelect(self, val):
        global prev
        sender = val.widget
        idx = sender.curselection()
        dis = self.lb1.get(idx)
        if (self.wat.get() == 1):
            CHEWD.wslistdisplay(self.entry4.get(), self.entry5.get(), prev,
                                dis, str(self.scale.get()), self.vl.get())
        elif (self.lig.get() == 1):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            CHEWD.lslistdisplay(vl, self.entry5.get(), prev, dis,
                                str(self.scale.get()), hl, self.vl.get())
        elif (self.mm.get() == 1):
            CHEWD.mmlistdisplay(self.entry4.get(), self.entry5.get(), prev,
                                dis, "0", self.vl.get())
        prev = dis

    def sortdata(self, sc):
        global dr1, dr2, dr3
        tableData1 = self.lb1.get(0, END)
        tableData2 = self.lb2.get(0, END)
        tableData3 = self.lb3.get(0, END)

        data = list()
        nv = len(tableData1)
        for x in range(nv):
            data.append([tableData1[x], tableData2[x], tableData3[x]])

        if (sc == 0):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b1.cget('text')
            if dr1 == 1: self.b1.config(text='[+] ' + lab)
            else: self.b1.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr1 == 1)
            dr1 = dr1 * -1
        if (sc == 1):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b2.cget('text')
            if dr2 == 1: self.b2.config(text='[+] ' + lab)
            else: self.b2.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1)
            dr2 = dr2 * -1
        if (sc == 2):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b3.cget('text')
            if dr3 == 1: self.b3.config(text='[+] ' + lab)
            else: self.b3.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr3 == 1)
            dr3 = dr3 * -1
        nv = len(data)
        self.lb1.delete(0, 'end')
        self.lb2.delete(0, 'end')
        self.lb3.delete(0, 'end')
        for x in range(nv):
            self.lb1.insert(END, data[x][0])
            self.lb2.insert(END, data[x][1])
            self.lb3.insert(END, data[x][2])

    def onOpen(self):
        global load
        fold = tkFileDialog.askdirectory()
        self.entry1.delete(0, 'end')
        self.entry1.insert(0, fold)
        load = 0

    def onOpenMM(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry2.delete(0, 'end')
        self.entry2.insert(0, fold)
        load = 0

    def onOpenPDB(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry3.delete(0, 'end')
        self.entry3.insert(0, fold)
        load = 0

    def OnVsb(self, *args):
        self.lb1.yview(*args)
        self.lb2.yview(*args)
        self.lb3.yview(*args)

    def OnMouseWheel(self, event):
        self.lb1.yview("scroll", event.delta, "units")
        self.lb2.yview("scroll", event.delta, "units")
        self.lb3.yview("scroll", event.delta, "units")
        return "break"

    def Apply(self):
        global load, prevz
        if (load == 0):

            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.changestate()
                self.base = os.listdir(self.entry1.get())
                pdb1 = list()
                for a in self.base:
                    matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a,
                                        re.M | re.I)
                    if matchObj:
                        pdb1.append(a)
                self.lig1pdb = list()
                self.lig2pdb = list()
                #print x
                x = pdb1[1][22:27]

                for a in pdb1:

                    matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb',
                                        a, re.M | re.I)
                    if matchObj:
                        self.lig1pdb.append(a)
                    else:
                        self.lig2pdb.append(a)
                self.lig1pdb.sort()
                self.lig2pdb.sort()
                self.scale.configure(from_=0, to=len(self.lig1pdb) - 1)
                self.scale.config(state="normal")

            elif (self.mm.get() == 1):
                self.loadmmpbsaresults()
                CHEWD.mmloadpdb(self.entry3.get())
                CHEWD.mmvisualizer("0", tempfile.gettempdir(),
                                   self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(),
                                   self.vl.get())

            if (self.wat.get() == 1):
                CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                CHEWD.wsvisualizer(str(self.scale.get()),
                                   tempfile.gettempdir(), self.entry4.get(),
                                   self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                CHEWD.lsvisualizer(str(self.scale.get()),
                                   tempfile.gettempdir(), vl,
                                   self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), hl, self.vl.get())
            load = 1

        else:

            if (self.wat.get() == 1):
                self.changestate()
                CHEWD.clear(tempfile.gettempdir())
                CHEWD.loadresults(tempfile.gettempdir())
                CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   str(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                self.changestate()
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()

                CHEWD.clear(tempfile.gettempdir())
                CHEWD.loadresults(tempfile.gettempdir())
                CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                   self.entry7.get(), prevz,
                                   str(self.scale.get()), hl, self.vl.get())
            elif (self.mm.get() == 1):
                CHEWD.mmupdateview(self.entry4.get(), self.entry5.get(),
                                   self.entry6.get(), self.entry7.get(), prevz,
                                   "0", self.vl.get())
        prevz = self.entry5.get()
Ejemplo n.º 18
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
        self.parent.title("Filter Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Filter Data")
        lbl00.config(font=labelfont10)
        lbl00.pack( padx=5, pady=5)
        
        ####################################
        
        
        ##########################################
        
        
        ############################################
        #####printing line
        
        lbl5a = Label(text="__________________________________")
        lbl5a.pack()
        lbl5a.place(x=170, y=300)
        
        lbl5b = Label(text="__________________________________")
        lbl5b.pack()
        lbl5b.place(x=480, y=300)
        
        self.lbl5c = Label(text="Search Result Will Appear Here")
        self.lbl5c.pack()
        self.lbl5c.place(x=170, y=320)
        
        self.lbl5d = Label(text="File Name Will Appear Here")
        self.lbl5d.pack()
        self.lbl5d.place(x=480, y=320)
        
        ############################################
        
        
        #############################################
        
        ###############################################
        
        
        ##############################################
        
        #############################################
        
        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=200, y=100)
        
        lbl11x = Label(frame11,text="Class 10th %")
        lbl11x.pack(padx=0, pady=0)
        
               

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=200, y=120) 
        
        
        
        
        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=380, y=100)
        
        lbl12x = Label(frame12,text="Class 12th %")
        lbl12x.pack(padx=0, pady=0)
        
               

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=380, y=120) 
        
        

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=550, y=100)
        
        lbl13x = Label(frame13,text="B.Tech %")
        lbl13x.pack(padx=0, pady=0)
        
               

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=550, y=120) 
        
        
        
        ####################################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=350, y=160)
        
        lbl9 = Label(frame9, text="HomeTown:")
        lbl9.pack()        

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)
        
        
             
         
        
        
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=190, y=250)
        closeButton = Button(frame16, text="Filter",width=20,command=self.getDatax2)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        frame17 = Frame(self)
        frame17.pack()
        frame17.place(x=500, y=250)
        closeButton = Button(frame17, text="Save & Open",width=20,command=self.getDatax3)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        
        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)
        
        self.lbl000= Label(frame000, text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)    
        self.lbl000.pack( padx=5, pady=5)
        
        
        
    def getDatax2(self):
        x1 = self.entry11.get()
        if x1 != "":
            x1 = int(x1)
        
        x2 = self.entry12.get()
        if x2 != "":
            x2 = int(x2)
        x3 = self.entry13.get()
        if x3 != "":
            x3 = int(x3)
        x4 = self.entry9.get()
        list1=[x1,x2,x3,x4]
        
        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        max_col = ws.get_highest_column()
        global temp
        global tempx
        temp = []
        tempx = []
        for i in xrange(2,max_row+1):
            temp.append(i)
        #print temp
        
        if isinstance(x1, int):
            for i in temp:
                if ws.cell(row = i, column = 11).value >= x1:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
            
        if isinstance(x2, int):
            for i in temp:
                if ws.cell(row = i, column = 14).value >= x2:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
        if isinstance(x3, int):
            for i in temp:
                if ws.cell(row = i, column = 17).value >= x3:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
            
        if isinstance(x3, str) and x3 != "":
            for i in temp:
                if ws.cell(row = i, column = 9).value == x4:
                    tempx.append(i)
            temp = tempx
            tempx = []
            print temp
        self.lbl5c.config(text=""+str(len(temp))+" result(s) found")
            
    def getDatax3(self):
        import datetime
        now = datetime.datetime.now()
        now = now.replace(microsecond=0,second = 0)
        now = now.strftime("%d_%B_%y,%I-%M_%p")
        now = now+".xlsx"
        
       
        
        
        if len(temp) != 0:
            wb1 = openpyxl.load_workbook('..\database\database.xlsx')
            ws1 = wb1.active
            wb2 = openpyxl.load_workbook('..\_frame\_frame.xlsx')
            ws2 = wb2.active
        
            for i in xrange(2,len(temp)+2):
                for j in xrange(1,22):
                    ws2.cell(row = i, column = j).value = ws1.cell(row = temp[i-2], column = j).value
        
        wb2.save('..\Result\\'+now)
        tempstart = '..\Result\\'+now
        self.lbl5d.config(text="File is :: "+"\""+now+"\"")
        os.system("start "+tempstart)
        
        self.entry11.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry9.delete(0, 'end')
Ejemplo n.º 19
0
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W + E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)
Ejemplo n.º 20
0
class fileExplorer(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        #Determines which checkbox is active.
        self.option = 0
        
        #Setup window.
        self.parent.title("REA5PE")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
		
        #Create label
        lbl = Label(self, text="Select the format PE file.")
        lbl.grid(sticky=W)
		
        #Create checkbox 1
        self.var = IntVar()
        cb = Checkbutton(self, text="Show .txt",
        variable=self.var, command=self.onClick)
        cb.grid(row=1, column=0, sticky=W)
        
        #Create checkbox 2
        self.var2 = IntVar()
        cb2 = Checkbutton(self, text="Show Console",
        variable=self.var2, command=self.onClick2)
        cb2.grid(row=2, column=0, sticky=W)
        
        #Entry form
        self.e1 = Entry(self)
        self.e1.grid(row=3, column=0)
        self.e1.focus_set() #Currently owns focus
   
        #Submission
        abtn = Button(self, text="Disassemble", command=self.onClickDisassemble)
        abtn.grid(row=4, column=0, sticky=W+E)
        
        
     #checkbox1
    def onClick(self):
       
        if self.var.get() == 1:
            self.option+=1 
        else:
            self.option-=1
            
	#checkbox2		
    def onClick2(self):
       
        if self.var2.get() == 1:
            self.option+=2
        else:
            self.option-=2
                
   
    #Disassemble button
    def onClickDisassemble(self):
        #Grab the string from the entry field.
        print "Attempting to launch file: " + self.e1.get()
        decoded = self.e1.get()
        
        if(os.path.isfile(self.e1.get())==True):
            #Launch the process.
            process = Popen(["xed.exe", "-i", decoded], stdout=PIPE)
            (output, err) = process.communicate()
            exit_code = process.wait()
        else:
            print "File does not exist. Terminating application."
            sys.exit()
        
        #Save to file.
        print "Saving to file...."
        fx = open('xeddumptext.txt', 'w')
        fx.write(output)
        fx.close()
        fb = open('xeddumpbinary.txt', 'wb')
        fb.write(output)
        fb.close()
        print "done"
        
        if(self.option==0):
            print "No selection. Please choose a section."
        elif(self.option==1):
            print "Displaying text section only."
            self.extractText();
        elif(self.option==2):
            print "Displaying Console section only."
            self.extractConsole();
        elif(self.option==3):
            print "Displaying both sections."
            self.extractText();
            self.extractConsole();
        else:
            print "Unknown error."
            
    def extractText(self):
        # create child window
        win = Toplevel()
        # display message
        message = "Assembly Dump for .text section"
        Label(win, text=message).pack()
        self.scrollbar = Scrollbar(win)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.T = Text(win, height=20, width=100)
        self.T.pack()
        self.scrollbar.config(command=self.T.yview)
        
        #Fill out the window with the data.
        with open("xeddumpbinary.txt") as input_data:
            for line in input_data:
                if line.strip() == '# IA32 format':
                    break
                #Reads text until the end of the block.
            for line in input_data: #keep reading
                if line.strip() == '# end of text section.':
                    break
                self.T.insert(END, line)
        message2 = "Search:"
        Label(win,text=message2).pack()
        self.es = Entry(win)
        self.es.pack()
        self.es.focus_set()

        Button(win, text='OK', command=self.searchTerm).pack()
        
    def searchTerm(self):
        self.T.tag_remove('search', '1.0', END)
        s = self.es.get()
        if s:
            idx = '1.0'
            while 1:
                idx = self.T.search(s, idx, nocase=1, stopindex=END)
                if not idx: break
                lastidx = '%s+%dc' % (idx, len(s))
                self.T.tag_add('search', idx, lastidx)
                idx = lastidx
            self.T.tag_config("search", foreground="red")
        self.es.focus_set()       
        
    def extractConsole(self):
       # create child window
       win2 = Toplevel()
       # display message
       message = "Dump for Console"
       Label(win2, text=message).pack()
       self.scrollbarc = Scrollbar(win2)
       self.scrollbarc.pack(side=RIGHT, fill=Y)
       self.T2 = Text(win2, height=20, width=100, yscrollcommand=self.scrollbarc.set)
       self.T2.pack()
       
       self.scrollbarc.config(command=self.T2.yview)
       # quit child window and return to root window
       # the button is optional here, simply use the corner x of the child window
       with open('xeddumpbinary.txt') as input_datac:
            for line in input_datac:
                if line.strip() == '# end of text section.':
                    break
                #Reads text until the end of the block.
            for line in input_datac: #keep reading
                self.T2.insert(END, line)
       Button(win2, text='OK', command=win2.destroy).pack()
Ejemplo n.º 21
0
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        canvas = tk.Canvas(self,
                           height=self.master.winfo_screenheight(),
                           width=self.master.winfo_screenwidth())
        canvas.pack()

        frame = tk.Frame(canvas, bg="#282C34")
        frame.place(x=0, y=0, relwidth=1.0, relheight=1.0)

        instruction_label = tk.Label(frame,
                                     text="What would you like to do?",
                                     font=50)
        instruction_label.pack()

        tree_list = []
        # Create the treeview to display the data sets
        for data_set in settings.data_set:
            tree = ttk.Treeview(frame)

            # Set Vertical Scrollbar to the Trees
            tree_scrollbar_vertical = ttk.Scrollbar(tree,
                                                    orient='vertical',
                                                    command=tree.yview)
            tree_scrollbar_horizontal = ttk.Scrollbar(tree,
                                                      orient='horizontal',
                                                      command=tree.xview)
            tree_scrollbar_vertical.pack(side=RIGHT, fill=Y)
            tree_scrollbar_horizontal.pack(side=BOTTOM, fill=X)
            tree.configure(xscrollcommand=tree_scrollbar_horizontal.set,
                           yscrollcommand=tree_scrollbar_vertical.set)

            for i in range(0, len(data_set)):
                heading_list = []
                value_list = []

                for x in data_set[i]:
                    heading_list.append(x)
                    value_list.append(data_set[i].get(x))
                    value_list[-1] = value_list[-1].decode('utf-8', 'ignore')

                tree["columns"] = heading_list
                tree['show'] = 'headings'

                for x in range(0, len(heading_list)):
                    tree.heading(heading_list[x], text=heading_list[x])

                tree.insert("", 0, values=value_list)

            tree.pack(fill=BOTH, expand=True)

            # Fill the trees with data
            tree_list.append(tree)

            def treeview_sort_column(tv, col, reverse):
                l = [(tv.set(k, col), k) for k in tv.get_children('')]
                l.sort(reverse=reverse)

                # rearrange items in sorted positions
                for index, (val, k) in enumerate(l):
                    tv.move(k, '', index)

                # reverse sort next time
                tv.heading(
                    col,
                    command=lambda: treeview_sort_column(tv, col, not reverse))

            for col in heading_list:
                tree.heading(col,
                             text=col,
                             command=lambda _col=col: treeview_sort_column(
                                 tree, _col, False))
        """
        Bottom Frame - Seperator for Input Widgets
        """
        bottom_frame = Frame(frame, bg="#282C34")
        bottom_frame.pack(fill=BOTH, expand=True)

        ## Sub-Frame [1] for Input ##
        frame_Input_1 = Frame(bottom_frame, bg="#282C34")
        frame_Input_1.pack(expand=True)

        input_label_UEN = Label(frame_Input_1, text="UEN:", bg='gray65')
        input_label_UEN.pack(side=LEFT)

        input_Entry_1 = Entry(frame_Input_1)
        input_Entry_1.pack(side=LEFT)

        btn_get_company_by_uen = tk.Button(
            frame_Input_1,
            text="Search Company By UEN",
            command=lambda: self.get_company_by_uen(
                tree_list=tree_list, uen_number=input_Entry_1.get()))
        btn_get_company_by_uen.pack(side=LEFT, padx="10")

        input_label_keyword = Label(frame_Input_1,
                                    text="Keyword:",
                                    bg='gray65')
        input_label_keyword.pack(side=LEFT, padx="1")

        input_Entry_2 = Entry(frame_Input_1)
        input_Entry_2.pack(side=LEFT)

        btn_list_company_from_keyword = tk.Button(
            frame_Input_1,
            text="Search Company by Name",
            command=lambda: self.list_company_from_keyword(
                tree_list=tree_list, keyword=input_Entry_2.get()))
        btn_list_company_from_keyword.pack(side=LEFT, padx="10")

        input_label_filter_top = Label(frame_Input_1,
                                       text="No. of Contractors:",
                                       bg='gray65')
        input_label_filter_top.pack(side=LEFT, padx="1")

        input_Entry_4 = Entry(frame_Input_1)
        input_Entry_4.pack(side=LEFT, padx="1")

        btn_get_top_contractors = tk.Button(
            frame_Input_1,
            text="Get Top Contractors",
            command=lambda: self.get_top_contractors(
                frame, n=int(input_Entry_4.get())))
        btn_get_top_contractors.pack(side=LEFT, padx="10")

        ## Sub-Frame [2] for Input ##
        frame_Input_2 = Frame(bottom_frame, bg="#282C34")
        frame_Input_2.pack(expand=True)

        input_label_filter_qual = Label(frame_Input_2,
                                        text="Tender Amt:",
                                        bg='gray65')
        input_label_filter_qual.pack(side=LEFT, padx="1")

        input_Entry_5 = Entry(frame_Input_2)
        input_Entry_5.pack(side=LEFT, padx="1")

        btn_get_qualified_contractors = tk.Button(
            frame_Input_2,
            text="Get Qualified Contractors",
            command=lambda: self.get_qualified_contractors(
                input_Entry_5.get(), tree_list=tree_list))

        btn_get_qualified_contractors.pack(side=LEFT, padx="10")

        input_label_award_year = Label(frame_Input_2,
                                       text="Award Year:",
                                       bg='gray65')
        input_label_award_year.pack(side=LEFT, padx="1")

        input_Entry_6 = Entry(frame_Input_2)
        input_Entry_6.pack(side=LEFT, padx="1")

        btn_get_award_year = tk.Button(
            frame_Input_2,
            text="List Procurements during Award Year",
            command=lambda: self.get_award_year(
                tree_list=tree_list, _year=int(input_Entry_6.get())))

        btn_get_award_year.pack(side=LEFT, padx="10")

        ## Sub-Frame [1] for Buttons ##
        frame_button_1 = Frame(bottom_frame, bg="#282C34")
        frame_button_1.pack(side=TOP, expand=True)

        btn_get_procurement_by_category = tk.Button(
            frame_button_1,
            text="List Procurements by Category",
            command=lambda: self.get_procurement_by_cat(frame))

        btn_get_procurement_by_category.pack(side=LEFT, padx="10")

        btn_get_agency = tk.Button(frame_button_1,
                                   text="List of Agencies",
                                   command=lambda: self.get_agency(frame))
        btn_get_agency.pack(side=LEFT, padx="10")

        btn_get_awarded_contractors = tk.Button(
            frame_button_1,
            text="List of Awarded Contractors",
            command=lambda: self.get_awarded_contractors(tree_list=tree_list))

        btn_get_awarded_contractors.pack(side=LEFT, padx="10")

        btn_get_expired_contracts = tk.Button(
            frame_button_1,
            text="Get Expired Contracts",
            command=lambda tree_variable=tree: self.get_expiry_date(
                tree=tree_variable))

        btn_get_expired_contracts.pack(side=LEFT, padx="10")

        btn_sort_procure = tk.Button(
            frame_button_1,
            text="Sort by Procurement Amt",
            command=lambda: self.sort_col("awarded_amt",
                                          settings.data_set[0],
                                          False,
                                          tree_list=tree_list))

        btn_sort_procure.pack(side=LEFT, padx="10")

        ## Sub-Frame [2] for Buttons ##
        frame_button_2 = Frame(bottom_frame, bg="#282C34")
        frame_button_2.pack(expand=True)

        function4_button = tk.Button(
            frame_button_2,
            text="Export Agency Procurement to Text File",
            command=lambda: self.export_file())
        function4_button.pack(side=LEFT, expand=True, padx="10")

        back_button = tk.Button(
            frame_button_2,
            text="Return to start page",
            command=lambda: master.switch_frame(main.StartPage))
        back_button.pack(side=LEFT, expand=True, padx="1")
Ejemplo n.º 22
0
class CreateServer(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        CreateServer.local_world = None
        label_1 = Label(self, text="Create server\n\n\n\n", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label_2 = Label(self, text="Server name:")
        label_3 = Label(self, text="Gamefield (MxN):")
        CreateServer.plx_name = 'none'
        CreateServer.game_dim = '10X10'
        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self)
        self.entry_2.insert(0, '10x10')
        self.entry_1.bind("<Key>", self.checkString)

        self.button1 = Button(self, text="Create",state="disabled", command= self.callback_set)
        self.button2 = Button(self, text="Back", command=lambda: controller.show_frame("StartPage"))

        label_1.pack(side="top", fill="x", pady=10)
        label_2.pack()
        self.entry_1.pack()
        label_3.pack()
        self.entry_2.pack()
        self.button1.pack(pady=10)
        self.button2.pack(pady=20)
    
    
    def com(self, controller, next_frame):
        controller.show_frame(next_frame)
        
    def checkString(self, event):
        if self.entry_1:
            self.button1.config(state="normal")
    
    def callback_set(self):
        set_global_state(1)
        if self.get_name_field():
            self.controller.show_frame("ChooseType")
    
    # process user inputs
    def get_name_field(self):
        CreateServer.plx_name = self.entry_1.get()
        CreateServer.game_dim = self.entry_2.get().upper()
        
        flag2 = False
        
        flag1 = self.string_check(CreateServer.plx_name,"Invalid server name")
        if flag1:
            flag2 = self.string_check(CreateServer.game_dim,"Invalid game field parameters")
        
        if flag2:
            m_split=CreateServer.game_dim.split('X')
            if len(m_split)==2:
                try:
                    _ = int(m_split[0])
                except:
                    flag2 = False  
                try:
                    _ = int(m_split[1])
                except:
                    flag2 = False
            else:
                flag2 = False
                
            if flag2 == False:
                tkMessageBox.showwarning("Error message", "Invalid game field parameters!")
        return flag1 & flag2
    
    # check if the string is usable
    def string_check(self,s,msg):
        temp = False
        try:
            s.decode('ascii')
        except UnicodeEncodeError:
            print "it was not an ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", msg)
        except UnicodeDecodeError:
            print "it was not an ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", msg)
        else:
            if len(CreateServer.plx_name) < 11 and len(CreateServer.plx_name) >= 1:
                temp = True
            else:
                tkMessageBox.showwarning("Error message", "Please input 1-10 characters!")
        return temp
Ejemplo n.º 23
0
class CHEWD(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        self.selection = ""
        self.pdb = ""

    def initUI(self):
        self.parent.title("CHemical Energy Wise Decomposition")
        frame4 = Frame(self.parent)
        frame4.grid(row=0, column=0, sticky="nsew")
        self.wat = IntVar()
        self.wat.set(1)
        self.waterswap = Checkbutton(frame4,
                                     text="Water Swap",
                                     command=self.optionws,
                                     variable=self.wat)
        self.waterswap.grid(row=0, column=0)
        self.lig = IntVar()
        self.lig.set(0)
        self.ligandswap = Checkbutton(frame4,
                                      text="Ligand Swap",
                                      command=self.optionls,
                                      variable=self.lig)
        self.ligandswap.grid(row=0, column=1)
        self.mm = IntVar()
        self.mm.set(0)
        self.mmpbsa = Checkbutton(frame4,
                                  text="MMPBSA",
                                  command=self.optionmm,
                                  variable=self.mm)
        self.mmpbsa.grid(row=0, column=2)

        frame1 = Frame(self.parent)
        frame1.grid(row=1, column=0, sticky="nsew")
        lbl1 = Label(frame1, text="Log file folder", width=12)
        lbl1.grid(row=0, column=0)
        self.entry1 = Entry(frame1)
        self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E)
        self.browserButton = Button(frame1,
                                    text="Browser",
                                    command=self.onOpen)
        self.browserButton.grid(row=0, column=5, sticky="e")

        lbl2 = Label(frame1, text="MMPBSA log file", width=12)
        lbl2.grid(row=1, column=0)
        self.entry2 = Entry(frame1, state=DISABLED)
        self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E)
        self.browserButtonMM = Button(frame1,
                                      text="Browser",
                                      command=self.onOpenMM,
                                      state=DISABLED)
        self.browserButtonMM.grid(row=1, column=5, sticky="e")

        lbl3 = Label(frame1, text="MMPBSA PDB file", width=12)
        lbl3.grid(row=2, column=0)
        self.entry3 = Entry(frame1, state=DISABLED)
        self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E)
        self.browserButtonPDB = Button(frame1,
                                       text="Browser",
                                       command=self.onOpenPDB,
                                       state=DISABLED)
        self.browserButtonPDB.grid(row=2, column=5, sticky="e")

        lbl4 = Label(frame1, text="Ligand Name", width=12)
        lbl4.grid(row=3, column=0)
        self.entry4 = Entry(frame1)
        self.entry4.grid(row=3, column=1)
        self.lblswap = Label(frame1,
                             text="Swap Ligand",
                             width=12,
                             state=DISABLED)
        self.lblswap.grid(row=3, column=2)
        self.swapentry = Entry(frame1, state=DISABLED)
        self.swapentry.grid(row=3, column=3)
        self.l1v = IntVar()
        self.l1v.set(1)
        self.lig1ck = Checkbutton(frame1,
                                  text="Ligand 1",
                                  command=self.changelig1,
                                  state=DISABLED,
                                  variable=self.l1v)
        self.lig1ck.grid(row=4, column=0)
        self.l2v = IntVar()
        self.l2v.set(0)
        self.lig2ck = Checkbutton(frame1,
                                  text="Ligand 2",
                                  command=self.changelig2,
                                  state=DISABLED,
                                  variable=self.l2v)
        self.lig2ck.grid(row=4, column=2)
        lbl5 = Label(frame1, text="Display Radius", width=12)
        lbl5.grid(row=5, column=0)
        self.entry5 = Entry(frame1)
        self.entry5.grid(row=5, column=1)
        self.entry5.insert(0, "5.0")
        self.sv = IntVar()
        self.sv.set(0)
        self.surface = Checkbutton(frame1,
                                   text="View Surface",
                                   command=self.viewsurface,
                                   variable=self.sv)
        self.surface.grid(row=5, column=2)
        self.vl = IntVar()
        self.vl.set(1)
        self.label = Checkbutton(frame1,
                                 text="View Label",
                                 command=self.viewlabel,
                                 variable=self.vl)
        self.label.grid(row=5, column=3)

        lbl6 = Label(frame1, text="Min Value", width=12)
        lbl6.grid(row=6, column=0)
        self.entry6 = Entry(frame1)
        self.entry6.grid(row=6, column=1)
        self.entry6.insert(0, "-5")
        lbl7 = Label(frame1, text="Max Value", width=12)
        lbl7.grid(row=6, column=2)
        self.entry7 = Entry(frame1)
        self.entry7.grid(row=6, column=3)
        self.entry7.insert(0, "+5")

        lbl8 = Label(frame1, text="Starting log file", width=12)
        lbl8.grid(row=7, column=0)
        self.entry8 = Entry(frame1)
        self.entry8.grid(row=7, column=1)
        self.entry8.insert(0, "400")
        lbl9 = Label(frame1, text="Ending log file", width=12)
        lbl9.grid(row=7, column=2)
        self.entry9 = Entry(frame1)
        self.entry9.grid(row=7, column=3)
        self.entry9.insert(0, "1000")

        frame2 = Frame(self.parent)
        frame2.grid(row=2, column=0, sticky="nsew")
        self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb)
        self.vsb.grid(row=1, column=3, sticky="ns")
        self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb1.grid(row=1, column=0)
        self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb2.grid(row=1, column=1)
        self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set)
        self.lb3.grid(row=1, column=2)

        self.b1 = Button(frame2,
                         text="Residue Number",
                         state=DISABLED,
                         command=lambda: self.sortdata(0))
        self.b1.grid(row=0, column=0, sticky=W + E)
        self.b2 = Button(frame2,
                         text="Residue Name",
                         state=DISABLED,
                         command=lambda: self.sortdata(1))
        self.b2.grid(row=0, column=1, sticky=W + E)
        self.b3 = Button(frame2,
                         text="Energy Value",
                         state=DISABLED,
                         command=lambda: self.sortdata(2))
        self.b3.grid(row=0, column=2, sticky=W + E)

        OS = platform.system()
        if (OS == "Linux"):
            self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb1.bind("<4>", self.OnMouseWheel)
            self.lb1.bind("<5>", self.OnMouseWheel)
            self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb2.bind("<4>", self.OnMouseWheel)
            self.lb2.bind("<5>", self.OnMouseWheel)
            self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb3.bind("<4>", self.OnMouseWheel)
            self.lb3.bind("<5>", self.OnMouseWheel)
        else:
            self.lb1.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
            self.lb2.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
            self.lb3.bind("<<ListboxSelect>>", self.OnSelect)
            self.lb3.bind("<MouseWheel>", self.OnMouseWheel)

        frame3 = Frame(self.parent)
        frame3.grid(row=3, column=0, sticky="nsew")

        self.previous = Button(frame3,
                               text="Previous Frame",
                               state=DISABLED,
                               command=self.prevframe)
        self.previous.grid(row=0, column=0, sticky=W + E)
        self.scale = Scale(frame3,
                           command=self.onScale,
                           state=DISABLED,
                           orient=HORIZONTAL,
                           length=320,
                           showvalue=0)
        self.scale.grid(row=0, column=1, sticky=W + E)
        self.next = Button(frame3,
                           text="Next Frame",
                           state=DISABLED,
                           command=self.nextframe)
        self.next.grid(row=0, column=2, sticky=W + E)

        self.var = IntVar()
        v = 000
        self.var.set(v)
        self.label = Label(frame3, text=0, textvariable=self.var)
        self.label.grid(row=0, column=3)
        self.ApplyButton = Button(frame3, text="Apply", command=self.Apply)
        self.ApplyButton.grid(row=1, column=3, sticky="e")

        ToolTip(lbl1, "Load the result directory of Sire Analysis")
        ToolTip(self.browserButton,
                "Load the result directory of Sire Analysis")
        ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file")
        ToolTip(
            lbl5,
            "The radially distributed zone around ligand you want to be displayed"
        )
        ToolTip(
            lbl6,
            "Minimum scale value for the color distribution and it will be treated as blue"
        )
        ToolTip(
            lbl7,
            "Maximum scale value for the color distribution and it will be treated as red"
        )

    def wsvisualizer(self, index, lig, zone, min, max, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        #tt=0
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
            #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
            #tt=tt+1
        #print(tt)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        self.togglelabelws(label, index, lig, zone)

    def lsvisualizer(self, index, lig, zone, min, max, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)

    def wsupdateview(self, lig, zone, min, max, prev, index, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")
        #tt=0
        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)
            #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt))
            #tt=tt+1
        #print(tt)
        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        self.togglelabelws(label, index, lig, zone)

    def lsupdateview(self, lig, zone, min, max, prev, index, hlig, label):
        cmd.hide("all")
        x = cmd.get_names("all")
        cmd.label(
            "( " + x[index] + " and (r. " + lig + " a. " + prev +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"")
        cmd.show("cartoon", "bo. " + x[index])
        cmd.show("sticks", x[index] + " and r. " + lig)
        cmd.color("white", x[index] + " and pol.")
        fp = open(tempfile.gettempdir() + "/temp.txt", "r")

        stored.bfact = []
        for line in fp:
            stored.bfact.append(line)

        fp.close()
        cmd.alter(x[index], "b=stored.bfact.pop(0)")
        cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max)
        cmd.ramp_new("ramp_obj",
                     x[index],
                     range=[min, 0, max],
                     color="[blue, white, red ]")
        cmd.util.cbaw(x[index] + " and r. " + lig)
        cmd.show(
            "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone +
            ") ) and (not (" + x[index] +
            " and (r. SWT or r. BWT or r. SWP))) ")
        cmd.hide("licorice", x[index] + " and r. " + hlig)
        self.togglelabells(label, index, lig, zone, hlig)

    def wsloadallpdb(self, pdblist, path):
        for x in pdblist:
            cmd.load(path + "/" + x)
            #print(path +"/"+ x)
        cmd.hide("all")

    def mmloadpdb(self, path):
        cmd.load(path)

    def togglesurface(self, sur):
        x = cmd.get_names("all")
        if (sur):
            cmd.show("surf", x[int(self.scale.get())])
            cmd.set("transparency", "0.7")
        else:
            cmd.hide("surf", x[int(self.scale.get())])

    def wslistdisplay(self, prev, cur, index):
        x = cmd.get_names("all")
        cmd.hide("sticks", x[index] + " and i. " + prev)
        cmd.label(x[index] + " and i. " + prev + " and name CA", "\" \"")
        cmd.show("sticks", x[index] + " and i. " + cur)
        cmd.label(x[index] + " and i. " + cur + " and name CA",
                  "\"%s %s\"%(resn,resi)")

    def togglelabelws(self, label, index, lig, zone):
        global prevz
        x = cmd.get_names("all")
        if (label):
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + zone +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\"%s %s\"%(resn,resi)")
            prevz = self.entry5.get()
        else:
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + prevz +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\" \"")

    def togglelabells(self, label, index, lig, zone, hlig):
        global prevz
        x = cmd.get_names("all")
        if (label):
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + zone +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\"%s %s\"%(resn,resi)")
            cmd.label(x[index] + " and r. " + hlig + " and name CA", "\" \"")
            prevz = self.entry5.get()
        else:
            cmd.label(
                "( " + x[index] + " and (r. " + lig + " a. " + prevz +
                ") ) and (not (" + x[index] +
                " and (r. SWT or r. BWT or r. SWP))) " + " and name CA",
                "\" \"")

    def viewlabel(self):
        if (load > 0):
            if (self.wat.get() == 1):
                self.togglelabelws(self.vl.get(), int(self.scale.get()),
                                   self.entry4.get(), self.entry5.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.togglelabells(self.vl.get(), int(self.scale.get()), vl,
                                   self.entry5.get(), hl)
            elif (self.mm.get() == 1):
                self.togglelabelws(self.vl.get(), 0, self.entry4.get(),
                                   self.entry5.get())

    def viewsurface(self):  ##
        if (load > 0):
            self.togglesurface(self.sv.get())

    def optionws(self):
        if (self.wat.get() == 1):
            self.lig.set(0)
            self.mm.set(0)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.wat.set(0)
            self.lig.set(1)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionls(self):
        if (self.lig.get() == 1):
            self.wat.set(0)
            self.mm.set(0)
            self.swapentry.config(state="normal")
            self.lig1ck.config(state="normal")
            self.lig2ck.config(state="normal")
            self.lblswap.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)
        else:
            self.lig.set(0)
            self.mm.set(0)
            self.wat.set(1)
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def optionmm(self):
        if (self.mm.get() == 1):
            self.lig.set(0)
            self.wat.set(0)
            self.swapentry.config(state=DISABLED)
            self.lig1ck.config(state=DISABLED)
            self.lig2ck.config(state=DISABLED)
            self.lblswap.config(state=DISABLED)
            self.entry8.config(state=DISABLED)
            self.entry9.config(state=DISABLED)
            self.entry1.config(state=DISABLED)
            self.browserButton.config(state=DISABLED)
            self.entry2.config(state="normal")
            self.entry3.config(state="normal")
            self.browserButtonMM.config(state="normal")
            self.browserButtonPDB.config(state="normal")
        else:
            self.wat.set(1)
            self.lig.set(0)
            self.mm.set(0)
            self.entry8.config(state="normal")
            self.entry9.config(state="normal")
            self.entry1.config(state="normal")
            self.browserButton.config(state="normal")
            self.entry2.config(state=DISABLED)
            self.entry3.config(state=DISABLED)
            self.browserButtonMM.config(state=DISABLED)
            self.browserButtonPDB.config(state=DISABLED)

    def changelig1(self):  ##
        if (self.l1v.get() == 1):
            self.l2v.set(0)
        else:
            self.l2v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                              self.entry7.get(), prevz, int(self.scale.get()),
                              hl, self.vl.get())

    def changelig2(self):  ##
        if (self.l2v.get() == 1):
            self.l1v.set(0)
        else:
            self.l1v.set(1)
        if (load > 0):
            if (self.l1v.get() == 1):
                vl = self.entry4.get()
                hl = self.swapentry.get()
            if (self.l2v.get() == 1):
                vl = self.swapentry.get()
                hl = self.entry4.get()
            self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                              self.entry7.get(), prevz, int(self.scale.get()),
                              hl, self.vl.get())

    def loadmmpbsaresults(self):
        fp = open(self.entry3.get(), "r")
        e = 0
        atomcount = 0
        resnew = 0
        rescount = 0
        resnum = list()
        residuename = list()
        resv = list()
        atomnum = list()
        atomnums = list()
        score = list()
        r = ""
        rn = ""
        for line in fp:
            if e == 2:
                atomnum.append(atomnums)
                break
            t = line.split()
            if line.find('TER') != -1:
                e = e + 1
            if line.find('ATOM') != -1:
                if (resnew == 0):
                    r = t[4]
                    rn = t[3]
                    resnew = 1
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                elif (r != t[4]):
                    r = t[4]
                    rn = t[3]
                    atomnum.append(atomnums)
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                    atomnums = list()
                atomnums.append(atomcount)
                atomcount = atomcount + 1
        fp.close()
        ll = len(score)
        print(ll)
        resv = list()
        fp = open(self.entry2.get(), "r")
        for line in fp:
            t = line.split(',')
            t2 = t[0].split()
            if (len(t) == 20 and len(t2) == 2 and t2[0] != "LIG"):
                for xx in range(ll):
                    if (int(resnum[xx]) == int(t2[1])):
                        #print(str(ll)+"\t"+str(len(t)))
                        score[xx] = float(t[17])
            matchObj = re.match(r'Sidechain Energy Decomposition:', line,
                                re.M | re.I)
            if matchObj:
                break
        fp.close()
        x = len(score)
        data = list()
        for i in range(x):
            data.append([resnum[i], score[i], residuename[i], atomnum[i]])
        data.sort(key=lambda s: (int(s[0])))
        scores = list()
        for i in range(len(data)):
            for j in range(len(data[i][3])):
                scores.append("{0:.3f}".format(data[i][1]))
        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        xs = len(scores)
        for i in range(xs):
            fp.write(str(scores[i]) + "\n")
        fp.close()
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)

        for i in range(x):
            self.lb1.insert(END, data[i][0])
            self.lb2.insert(END, data[i][2])
            self.lb3.insert(END, round(data[i][1], 3))

        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def changestate(self):  ##
        fp = open(self.entry1.get() + "/bound_mobile_000100_0.00500.pdb")
        lend = 0
        if (self.wat.get() == 1):
            lend = 2
        elif (self.lig.get() == 1):
            lend = 4
        e = 0
        atomcount = 0
        resnew = 0
        rescount = 0
        resnum = list()
        residuename = list()
        resv = list()
        atomnum = list()
        atomnums = list()
        score = list()
        r = ""
        rn = ""
        for line in fp:
            if e == lend:
                atomnum.append(atomnums)
                break
            t = line.split()
            if line.find('TER') != -1:
                e = e + 1
            if line.find('ATOM') != -1:
                if (resnew == 0):
                    r = t[4]
                    rn = t[3]
                    resnew = 1
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                elif (r != t[4]):
                    r = t[4]
                    rn = t[3]
                    atomnum.append(atomnums)
                    resnum.append(r)
                    residuename.append(rn)
                    score.append(0)
                    atomnums = list()
                atomnums.append(atomcount)
                atomcount = atomcount + 1
        fp.close()
        x = list()
        tempx = list()
        ll = len(score)
        base = os.listdir(self.entry1.get())
        for a in base:
            if a.endswith(".log"):
                tempx.append(a)
        tempx.sort()
        tlen = len(tempx)
        ia = int(self.entry8.get())
        while (ia <= int(self.entry9.get()) and ia < tlen):
            x.append(tempx[ia])
            ia += 1
        c = 0
        i = 0
        for fn in x:
            fp = open(self.entry1.get() + "/" + fn, "r")
            if (c == 0):
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            for xx in range(ll):
                                if (int(resnum[xx]) == int(t[3])):
                                    score[xx] = float(t[5])
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            else:
                for line in fp:
                    t = line.split()
                    if (len(t) == 8):
                        if (t[0] == "Residue("):
                            for xx in range(ll):
                                if (int(t[3]) == int(resnum[xx])):
                                    score[xx] = score[xx] + float(t[5])
                                i = i + 1
                    if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"):
                        c = c + 1
                        i = 0
                        break
            fp.close()
        x = len(score)
        data = list()
        for i in range(x):
            data.append([resnum[i], score[i], residuename[i], atomnum[i]])
        data.sort(key=lambda s: (int(s[0])))
        for i in range(x):
            data[i][1] = data[i][1] / c
        scores = list()
        for i in range(len(data)):
            for j in range(len(data[i][3])):
                scores.append("{0:.3f}".format(data[i][1]))
        self.lb1.delete(0, END)
        self.lb2.delete(0, END)
        self.lb3.delete(0, END)

        for i in range(x):
            self.lb1.insert(END, data[i][0])
            self.lb2.insert(END, data[i][2])
            self.lb3.insert(END, round(data[i][1], 3))

        fp = open(tempfile.gettempdir() + "/temp.txt", "w")
        lx = len(scores)
        for i in range(lx):
            fp.write(str(scores[i]) + "\n")
        fp.close()
        self.b1.config(state="normal")
        self.b2.config(state="normal")
        self.b3.config(state="normal")

    def prevframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() - 1)

    def nextframe(self):
        global prevz, load
        if (load > 0):
            self.scale.set(self.scale.get() + 1)

    def onScale(self, val):
        global prevz, load
        if (load > 0):
            v = self.lig1pdb[int(float(val))][14:19]
            self.var.set(v)
            if (self.scale.get() == 0):
                self.previous.config(state=DISABLED)
            if (self.scale.get() == len(self.lig1pdb) - 2):
                self.next.config(state="normal")
            if (self.scale.get() == 1):
                self.previous.config(state="normal")
            if (self.scale.get() == len(self.lig1pdb) - 1):
                self.next.config(state=DISABLED)
            if (self.wat.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  int(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), prevz,
                                  int(self.scale.get()), hl, self.vl.get())

    def OnSelect(self, val):
        global prev
        sender = val.widget
        idx = sender.curselection()
        if (idx != ()):
            dis = self.lb1.get(idx)
            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.wslistdisplay(prev, dis, int(self.scale.get()))
            elif (self.mm.get() == 1):
                self.wslistdisplay(prev, dis, 0)
            prev = dis

    def sortdata(self, sc):
        global dr1, dr2, dr3
        tableData1 = self.lb1.get(0, END)
        tableData2 = self.lb2.get(0, END)
        tableData3 = self.lb3.get(0, END)

        data = list()
        nv = len(tableData1)
        for x in range(nv):
            data.append([tableData1[x], tableData2[x], tableData3[x]])

        if (sc == 0):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b1.cget('text')
            if dr1 == 1: self.b1.config(text='[+] ' + lab)
            else: self.b1.config(text='[-] ' + lab)
            data.sort(key=lambda s: (int(s[sc])), reverse=dr1 == 1)
            dr1 = dr1 * -1
        if (sc == 1):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b2.cget('text')
            if dr2 == 1: self.b2.config(text='[+] ' + lab)
            else: self.b2.config(text='[-] ' + lab)
            data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1)
            dr2 = dr2 * -1
        if (sc == 2):
            lab = self.b1.cget('text')
            if lab[0] == '[': self.b1.config(text=lab[4:])
            lab = self.b2.cget('text')
            if lab[0] == '[': self.b2.config(text=lab[4:])
            lab = self.b3.cget('text')
            if lab[0] == '[': self.b3.config(text=lab[4:])
            lab = self.b3.cget('text')
            if dr3 == 1: self.b3.config(text='[+] ' + lab)
            else: self.b3.config(text='[-] ' + lab)
            data.sort(key=lambda s: (float(s[sc])), reverse=dr3 == 1)
            dr3 = dr3 * -1
        nv = len(data)
        self.lb1.delete(0, 'end')
        self.lb2.delete(0, 'end')
        self.lb3.delete(0, 'end')
        for x in range(nv):
            self.lb1.insert(END, data[x][0])
            self.lb2.insert(END, data[x][1])
            self.lb3.insert(END, data[x][2])

    def onOpen(self):
        global load
        fold = tkFileDialog.askdirectory()
        self.entry1.delete(0, 'end')
        self.entry1.insert(0, fold)
        load = 0

    def onOpenMM(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry2.delete(0, 'end')
        self.entry2.insert(0, fold)
        load = 0

    def onOpenPDB(self):
        global load
        fold = tkFileDialog.askopenfilename()
        self.entry3.delete(0, 'end')
        self.entry3.insert(0, fold)
        load = 0

    def OnVsb(self, *args):
        self.lb1.yview(*args)
        self.lb2.yview(*args)
        self.lb3.yview(*args)

    def OnMouseWheel(self, event):
        self.lb1.yview("scroll", event.delta, "units")
        self.lb2.yview("scroll", event.delta, "units")
        self.lb3.yview("scroll", event.delta, "units")
        return "break"

    def Apply(self):
        global load, prevz
        if (load == 0):

            if (self.wat.get() == 1 or self.lig.get() == 1):
                self.changestate()
                self.base = os.listdir(self.entry1.get())
                pdb1 = list()
                for a in self.base:
                    matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a,
                                        re.M | re.I)
                    if matchObj:
                        pdb1.append(a)
                self.lig1pdb = list()
                self.lig2pdb = list()
                x = pdb1[1][22:27]

                for a in pdb1:

                    matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb',
                                        a, re.M | re.I)
                    if matchObj:
                        self.lig1pdb.append(a)
                    else:
                        self.lig2pdb.append(a)
                self.lig1pdb.sort()
                self.lig2pdb.sort()
                self.scale.configure(from_=0, to=len(self.lig1pdb) - 1)
                self.scale.config(state="normal")

            elif (self.mm.get() == 1):
                self.loadmmpbsaresults()
                self.mmloadpdb(self.entry3.get())
                self.wsvisualizer(0, self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(),
                                  self.vl.get())

            if (self.wat.get() == 1):
                self.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                self.wsvisualizer(int(self.scale.get()), self.entry4.get(),
                                  self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()
                self.wsloadallpdb(self.lig1pdb, self.entry1.get())
                self.next.config(state="normal")
                v = self.lig1pdb[0][14:19]
                self.var.set(v)
                self.lsvisualizer(int(self.scale.get()), vl, self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), hl,
                                  self.vl.get())
            load = 1

        else:  #old code "else:"

            if (self.wat.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  int(self.scale.get()), self.vl.get())
            elif (self.lig.get() == 1):
                if (self.l1v.get() == 1):
                    vl = self.entry4.get()
                    hl = self.swapentry.get()
                if (self.l2v.get() == 1):
                    vl = self.swapentry.get()
                    hl = self.entry4.get()

                self.lsupdateview(vl, self.entry5.get(), self.entry6.get(),
                                  self.entry7.get(), prevz,
                                  int(self.scale.get()), hl, self.vl.get())
            elif (self.mm.get() == 1):
                self.wsupdateview(self.entry4.get(), self.entry5.get(),
                                  self.entry6.get(), self.entry7.get(), prevz,
                                  0, self.vl.get())
        prevz = self.entry5.get()
Ejemplo n.º 24
0
class Example(Frame):
#Initialise values
    ctrlpt1=[55,55]
    ctrlpt2=[150,120]
    ctrlpt3=[55,215]
    pt1=[50,50]
    pt2=[100,100]
    clickno=2
    toggle = 1
    div_num = 10

#initilise Frame then initialise this Example class using initUI() 
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        
        self.parent = parent
        self.initUI()
        

        
    def initUI(self):
      
        self.parent.title("Grass")
#Configure parent for column layout       
        Style().configure("TButton", padding=(0, 5, 0, 5), 
            font='serif 10')
        
        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)
        self.rowconfigure(7, pad=3)
        self.rowconfigure(8, pad=3)


        frame1 = Frame(self)
        frame1.grid(row=0,columnspan=4)
        self.lbl1 = Label(frame1, text="")
        self.lbl1.pack(side=LEFT, padx=5, pady=5)

        frame2 = Frame(self)
        frame2.grid(row=1,columnspan=4)
        lbl2 = Label(frame2, text="Divisions", width=6)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        self.entry1=Entry(frame2) 
        self.entry1.pack(fill=X, padx=5, expand=True)        
        
        frame3 = Frame(self)
        frame3.grid(row=2,columnspan=4)
        self.lbl3 = Label(frame3, text="Divisions =%r"%self.div_num)
        self.lbl3.pack(side=LEFT, expand=True)
    

        set_point = Button(self, text="Set divisions", command=self.get_div)
        set_point.grid(row=3, columnspan=2)
     
        self.stop_place = Button(self, text="Toggle delete",\
        command=self.change_toggle)
        self.stop_place.grid(row = 3, column = 2,columnspan=2) 
    
        clr_btn = Button(self, text="Clear Canvas", command=self.clear_canvas)
        clr_btn.grid(row = 4, column = 0,columnspan=2)

        drw_btn = Button(self, text="Draw lines", command=self.draw_ctrllines)
        drw_btn.grid(row = 4, column = 2,columnspan=2)

        div = Button(self, text="Divide", command=self.draw_divide)
        div.grid(row = 5, column = 0,columnspan=2)

        strart = Button(self, text="Strings", command=self.string_art)
        strart.grid(row = 5, column = 2,columnspan=2)

        plotpar = Button(self, text="Parabola", command=self.plot_para)
        plotpar.grid(row = 6, column = 0,columnspan=2)

        self.w = Canvas(self, width=200, height=900)
        self.w.grid(row=7, columnspan=4)


#Draw initial control points for user

        self.id1=self.w.create_oval(self.ctrlpt1[0] - 2, self.ctrlpt1[1] - 2,\
        self.ctrlpt1[0] + 2,self.ctrlpt1[1] + 2,fill="black",tags='maybe')
        self.w.tag_bind(self.id1,'<Button-1>',self.del_elem)


        id2=self.w.create_oval(
                            self.ctrlpt2[0] - 2, self.ctrlpt2[1] - 2,
                            self.ctrlpt2[0] + 2,self.ctrlpt2[1] + 2,fill="black"
                              )
        self.w.tag_bind(id2,'<Button-1>',self.del_elem)

        self.id3=self.w.create_oval(self.ctrlpt3[0] - 2, self.ctrlpt3[1] - 2,\
        self.ctrlpt3[0] + 2,self.ctrlpt3[1] + 2,fill="black")
        self.w.tag_bind(self.id3,'<Button-1>',self.del_elem)
        self.w.bind('<Motion>',self.motion)  
        print self.id1

        movebut = Button(self, text="Grass", command=self.grass_polygon)
        movebut.grid(row = 6, column = 2,columnspan=2)
        
        #self.w.bind('<Button-1>',self.clicky) 
 
        self.pack()    

    def get_div(self):
        try:
            self.div_num=int(self.entry1.get())
            self.lbl1.config(text="Division number set")
            self.lbl3.config(text="Divisions =%r"%self.div_num)
        except ValueError:
            self.lbl1.config(text="Incorrect entry type")

    def draw_divide(self):
        self.w.delete("all")
        list1=self.divide_line(self.ctrlpt1,self.ctrlpt2)
        for n in range(len(list1)):  
            id=self.w.create_oval(
                                list1[n][0] - 2, list1[n][1] - 2, 
                                list1[n][0] + 2,list1[n][1] + 2,fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)
        list2=self.divide_line(self.ctrlpt2,self.ctrlpt3)  
        for n in range(len(list2)):  
            id=self.w.create_oval(
                                list2[n][0] - 2, list2[n][1] - 2, 
                                list2[n][0] + 2,list2[n][1] + 2,fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)
    
    def grass_polygon(self):
        lst=self.intersect_list()
        for n in range(len(lst)-1):
            width=5+10*(1-abs(1-2*(n+1)/float(len(lst))))
            m1 = self.slope(lst[n],lst[n+1])
            m = -1/self.slope(lst[n],lst[n+1])
            print lst[n],m1,m
            dx = math.sqrt(width**2/(1+m**2))
            dy = math.sqrt(width**2/(1+1/m**2))
            x1=math.ceil(lst[n][0]-dx)
            y1=math.ceil(lst[n][1]-dy)
            x2=math.ceil(lst[n][0]+dx)
            y2=math.ceil(lst[n][1]+dy)
            x3=lst[n+1][0]+dx
            y3=lst[n+1][1]+dy
            x4=lst[n+1][0]-dx
            y4=lst[n+1][1]-dy
            if n==0:
                x2=x1=lst[n][0]
                y2=y1=lst[n][1]
                
            self.w.create_polygon(x1,y1,x2,y2,x3,y3,x4,y4,fill='green')
    

    def dist(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        distance = math.sqrt(float((x2-x1))**2+(y2-y1)**2)
        return distance
    
    def slope(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        if abs(x2-x1) > 0.00001:
            m1=(y2+y1)/float(x2-x1)
            return m1
        else:
            return none

    def intersect_list(self):
        list1 = self.divide_line(self.ctrlpt1,self.ctrlpt2)
        list2 = self.divide_line(self.ctrlpt2,self.ctrlpt3)
        zplst = zip(list1[0:len(list1)-1],list2[1:len(list1)])
        para_list=[0]*(len(zplst)+1)
        para_list[0]=self.ctrlpt1
        para_list[len(zplst)]=self.ctrlpt3
        for n in range(len(zplst)-1):
            para_list[n+1]=self.intersection(
                                        zplst[n][0],zplst[n][1],
                                        zplst[n+1][0],zplst[n+1][1]
                                        )
        return para_list
            
    def plot_para(self):
        plotlist=self.intersect_list()
        for n in range(len(plotlist)):  
            id=self.w.create_oval(
                                plotlist[n][0]-2, plotlist[n][1]-2, 
                                plotlist[n][0]+2, plotlist[n][1]+2,fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)
                    
    def string_art(self):
        list1 = self.divide_line(self.ctrlpt1,self.ctrlpt2)
        list2 = self.divide_line(self.ctrlpt2,self.ctrlpt3)
        zplst = zip(list1[0:len(list1)-1],list2[1:len(list1)])
        for n in range(len(zplst)):  
            id=self.w.create_line(
                                zplst[n][0][0], zplst[n][0][1], 
                                zplst[n][1][0], zplst[n][1][1],fill="black"
                                  )
            self.w.tag_bind(id,'<Button-1>',self.del_elem)

    def intersection(self,point1,point2,point3,point4):
        x1,y1 = point1
        x2,y2 = point2
        x3,y3 = point3
        x4,y4 = point4
        if abs(x2-x1) > 0.00001 and abs(x4-x3) > 0.00001:
            m1=(y2-y1)/float(x2-x1)
            c1=y1-float(m1)*x1
            m2=(y4-y3)/float(x4-x3)
            c2=y3-float(m2)*x3
            xint = (c2-c1)/float((m1-m2))
            yint = m1*((c2-c1)/float((m1-m2)))+c1
        else:
            if abs(x2-x1) < 0.00001:
                xint=x2
                yint=(y4-y3)*x2/float(x4-x3)+y3-float((y4-y3)/float(x4-x3))*x3
            else:
                xint=x3
                yint=(y2-y1)*x3/float(x2-x1)+y1-float((y2-y1)/float(x2-x1))*x1
            
        return [xint,yint]

    def draw_ctrllines(self):
        x1,y1=self.ctrlpt1
        x2,y2=self.ctrlpt2
        x3,y3=self.ctrlpt3
        line1 = self.w.create_line(x1, y1, x2, y2)
        self.w.tag_bind(line1,'<Button-1>',self.del_elem)
        line2 = self.w.create_line(x2, y2, x3, y3)
        self.w.tag_bind(line2,'<Button-1>',self.del_elem)

    def divide_line(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        list = [0]*(self.div_num+1)
        for n in range(self.div_num+1):
            list[n]=[x1+(n)*(x2-x1)/float(self.div_num),y1+(n)*(y2-y1)/float(self.div_num)]
        return list            

    def change_toggle(self):
        self.toggle=(self.toggle+1)%2
        if self.toggle == 1:
            self.stop_place.config(text="Delete mode off")
        else:
            self.stop_place.config(text="Delete mode on")
    
       
    def del_elem(self,event):
        if self.toggle==1:
            pass
        else:
            print "Hello"
            event.widget.delete("current")
            
    def midpoint(self,x1,x2,y1,y2):
        xmid=(x1+x2)/2
        ymid=(y1+y2)/2
        return xmid,ymid

    def motion(self,event):
        w=self.parent.winfo_screenwidth()
        h=self.parent.winfo_screenheight()
        x,y = self.w.winfo_pointerxy()
        print x-536,y-353
    
    def clear_canvas(self):
        self.w.delete("all") 
Ejemplo n.º 25
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
      
        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 20, 'bold')
        labelfont12 = ('Roboto', 12, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi USER")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Search here")
        lbl00.config(font=labelfont12)
        lbl00.pack( padx=5, pady=5)
        
        
        frame1 = Frame(self)
        frame1.pack()
        
        lbl1 = Label(frame1, text="min %", width=9)
        lbl1.pack(side=LEFT, padx=7, pady=5)           
       
        self.entry1 = Entry(frame1,width=20)
        self.entry1.pack(padx=5, expand=True)
        
        
        
        
        
        frame6 = Frame(self)
        frame6.pack()
        closeButton = Button(frame6, text="Get Names",width=12,command=self.getDate)
        closeButton.pack(padx=5, pady=5)
        
        frame7 = Frame(self)
        frame7.pack()
        closeButton1 = Button(frame7, text="Open in excel",width=15,command=self.openDate)
        closeButton1.pack(padx=5, pady=5)
        
        
        
        frame000 = Frame(self)
        frame000.pack()
        self.lbl000= Label(frame000, text=" ")
        self.lbl000.config(font=labelfont12)    
        self.lbl000.pack( padx=5, pady=5)
        
        frame00a = Frame(self)
        frame00a.pack()
        self.lbl00a= Label(frame000, text=" ")
        self.lbl00a.pack( padx=5, pady=5)
        
        
        
        
    def getDate(self):
        x1 = self.entry1.get()
        nx = ""
        
        
        self.entry1.delete(0, 'end')
        
        self.lbl000.config(text="Names Are:")
        

        
        
        #read csv, and split on "," the line
        csv_file = csv.reader(open('test.csv', "rb"), delimiter=",")
        #loop through csv list
        for row in csv_file:
            if row[2] >= x1:
                nx+=str(row[0]+", ")
                with open("output5.csv", "ab") as fp:
                    wr = csv.writer(fp, dialect='excel')
                    wr.writerow(row)
                fp.close()
        self.lbl00a.config(text=nx)
        
    def openDate(self):
        os.system("start "+'output5.csv')
Ejemplo n.º 26
0
class topFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setUI()

    def setUI(self):
        self.parent.title("ServoGui")
        self.pack(fill=BOTH, expand=1)
        self.comPort = StringVar(self)
        self.laststrm = StringVar(self)

        settingFrame = Frame(self, borderwidth=1, relief=RAISED)
        settingFrame.pack(fill=Y, side=LEFT)

        Label(settingFrame,
              width=50,
              text="Port Settings",
              bg="green",
              fg="black").pack(fill=X)

        ports = self.getComPorts()
        w = apply(OptionMenu, (settingFrame, self.comPort) + tuple(ports))
        w.pack(fill=X)

        BaudFrame = Frame(settingFrame)
        BaudFrame.pack(fill=X)
        Label(BaudFrame, text="Baud:").pack(side=LEFT)
        self.baud_entry = Entry(BaudFrame,
                                width=15,
                                validate="focusout",
                                validatecommand=self.baudValidate)
        self.baud_entry.pack(side=LEFT, expand=True)
        self.baud_entry.insert(0, "115200")

        Button(settingFrame, text="Open Port",
               command=self.openPort).pack(fill=X)
        Button(settingFrame, text="Close Port",
               command=self.closePort).pack(fill=X)

        StreamFrame = Frame(settingFrame)
        StreamFrame.pack()
        self.btnStartStream = Button(StreamFrame,
                                     text="Start Stream",
                                     command=self.startStream,
                                     state=DISABLED)
        self.btnStopStream = Button(StreamFrame,
                                    text="Stop Stream",
                                    command=self.stopStream,
                                    state=DISABLED)
        self.btnGetConfig = Button(StreamFrame,
                                   text="Get Config",
                                   command=self.getConfig,
                                   state=DISABLED)
        self.btnStartStream.pack(side=LEFT)
        self.btnStopStream.pack(side=LEFT)
        self.btnGetConfig.pack(side=LEFT)
        self.queue = Queue.Queue()
        self.writequeue = Queue.Queue()

        Label(settingFrame,
              width=50,
              text="Drive Settings",
              bg="green",
              fg="black").pack(fill=X)
        DriveSettingsFrame = Frame(settingFrame, relief=SUNKEN)
        DriveSettingsFrame.pack(fill=X)

        driveSettingsFrames = []
        self.driveSettingsEntries = []
        for drivesetting in drivesettings:
            driveSettingsFrames.append(Frame(DriveSettingsFrame))
            driveSettingsFrames[-1].pack(fill=X)
            Label(driveSettingsFrames[-1], text=drivesetting).pack(side=LEFT)
            self.driveSettingsEntries.append(Entry(driveSettingsFrames[-1]))
            self.driveSettingsEntries[-1].pack(side=RIGHT)
        Button(DriveSettingsFrame,
               text="Send to drive",
               command=self.sendConfig).pack(fill=X)
        Button(DriveSettingsFrame,
               text="Save config in drive",
               command=self.saveConfig).pack(fill=X)

        Label(settingFrame,
              width=50,
              textvariable=self.laststrm,
              bg="green",
              fg="black").pack(fill=X)

        #MatplotLib stuff

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(311)
        self.a.set_title("Requested and actual position")
        self.b = f.add_subplot(312)
        self.b.set_title("Error")
        self.c = f.add_subplot(313)
        self.c.set_title("Current meas ADC value")

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.hall = []
        self.encoder_count = []
        self.pos_error = []
        self.requested_position = []
        self.requested_delta = []
        self.adc_value = []
        self.pid_output = []
        self.a.set_autoscaley_on(True)

        self.encoder_line, = self.a.plot([], [])
        self.error_line, = self.b.plot([], [])
        self.reqpos_line, = self.a.plot([], [])
        self.ADC_line, = self.c.plot([], [])
        self.updateCanvas()

    def baudValidate(self):
        sVal = self.baud_entry.get()
        try:
            iVal = int(sVal)
        except ValueError:
            print "Illegal baud value"
            self.baud_entry.delete(0, END)
            self.baud_entry.insert(0, "115200")
            return False
        return True

    def openPort(self):
        try:
            self.ser = serial.Serial(self.comPort.get(),
                                     int(self.baud_entry.get()),
                                     timeout=0)
        except serial.SerialException:
            print "unable to open"
            return
        self.btnStartStream['state'] = NORMAL
        self.btnStopStream['state'] = NORMAL
        self.btnGetConfig['state'] = NORMAL

        self.thread = SerialThread(self.queue, self.writequeue, self.ser)
        self.thread.daemon = True
        self.thread.start()
        self.process_serial()

    def closePort(self):
        self.thread.stop()
        self.thread.join()
        self.ser.closePort()

        self.btnStartStream['state'] = DISABLED
        self.btnStopStream['state'] = DISABLED
        self.btnGetConfig['state'] = DISABLED

    def process_serial(self):
        while self.queue.qsize():
            try:
                line = self.queue.get()
                self.handleLine(line)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

    def startStream(self):
        self.writequeue.put(b"STREAM START \r")

    def stopStream(self):
        self.writequeue.put(b"STREAM DIE \r")

    def getConfig(self):
        self.writequeue.put(b"GET\r")

    def saveConfig(self):
        self.writequeue.put(b"SAVE \r")

    def sendConfig(self):
        for setting in drivesettings:
            dataToSend = b"SET " + setting + " " + self.driveSettingsEntries[
                drivesettings.index(setting)].get() + "\r"
            print dataToSend
            self.writequeue.put(dataToSend)
            time.sleep(0.2)

    def getComPorts(self):
        ports = serial.tools.list_ports.comports()
        portNames = []
        for port in ports:
            portNames.append(port[0])
        return portNames

    def handleLine(self, line):
        line = line.replace(" ", "")
        line = line.replace("/n", "")
        line = line.replace("/r", "")
        parts = line.split(":")
        if len(parts) > 1:
            if parts[0] == "STR":
                self.handleStr(parts[1])
                return
            if parts[0] in drivesettings:
                self.driveSettingsEntries[drivesettings.index(
                    parts[0])].delete(0, END)
                self.driveSettingsEntries[drivesettings.index(
                    parts[0])].insert(0, parts[1])

    def handleStr(self, strm):
        #format of the stream line: STR:hall;count;requestedPosition;requestedDelta;error
        parts = strm.split(";")

        self.laststrm.set(strm)
        self.hall.append(int(parts[0]))
        if len(self.hall) > 5000:
            self.hall.pop(0)

        self.encoder_count.append(parts[1])
        if len(self.encoder_count) > 5000:
            self.encoder_count.pop(0)

        self.requested_position.append(parts[2])
        if len(self.requested_position) > 5000:
            self.requested_position.pop(0)

        self.requested_delta.append(parts[3])
        if len(self.requested_delta) > 5000:
            self.requested_delta.pop(0)

        self.pos_error.append(parts[4])
        if len(self.pos_error) > 5000:
            self.pos_error.pop(0)

        self.adc_value.append(parts[5])
        if len(self.adc_value) > 5000:
            self.adc_value.pop(0)

        self.pid_output.append(parts[5])
        if len(self.pid_output) > 5000:
            self.pid_output.pop(0)

    def updateCanvas(self):

        self.encoder_line.set_xdata(range(len(self.encoder_count)))
        self.encoder_line.set_ydata(self.encoder_count)
        self.error_line.set_xdata(range(len(self.pos_error)))
        self.error_line.set_ydata(self.pos_error)
        self.reqpos_line.set_xdata(range(len(self.requested_position)))
        self.reqpos_line.set_ydata(self.requested_position)
        self.ADC_line.set_xdata(range(len(self.adc_value)))
        self.ADC_line.set_ydata(self.adc_value)
        self.a.relim()
        self.a.autoscale_view()
        self.b.relim()
        self.b.autoscale_view()
        self.c.relim()
        self.c.autoscale_view()
        self.canvas.draw()
        self.after(100, self.updateCanvas)
Ejemplo n.º 27
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg=None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W + N, pady=4, padx=5)

        check_box = {"work": IntVar(), "boost": IntVar()}

        check1 = Checkbutton(self,
                             text="work-Mode",
                             variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self,
                             text="boost games",
                             variable=check_box["boost"])
        check2.grid(row=7, column=1)

        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand=self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(working_bans, self.entry.get(), self.
                                        entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(boosted, self.entry2.get(), self.
                                        entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

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

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(degraded, self.entry3.get(), self.
                                        entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_music(music_list, self.entry5.get(
            ), self.entry4.get(), self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)

        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self,
                       text="TaskManager",
                       command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(
            self,
            text="start",
            command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
class Test_Wifi(tk.Frame):
	_title = "Wifi Demo"
	def __init__(self, parent, controller):
		tk.Frame.__init__(self, parent)
		self.controller = controller

		label = tk.Label(self, text=self._title, font=TITLE_FONT)
		label.pack(side="top", fill="x", pady=10)

		frame_ssid = tk.Frame(self)
		frame_ssid.pack(fill=tk.X)
		lbl_ssid = tk.Label(frame_ssid, text="ssid", width=6)
		lbl_ssid.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_ssid = Entry(frame_ssid)
		self.entry_ssid.pack(fill=tk.X, padx=5, expand=True)

		frame_password = tk.Frame(self)
		frame_password.pack(fill=tk.X)
		lbl_password = tk.Label(frame_password, text="password", width=6)
		lbl_password.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_password = Entry(frame_password)
		self.entry_password.pack(fill=tk.X, padx=5, expand=True)

		frame_url = tk.Frame(self)
		frame_url.pack(fill=tk.X)
		lbl_url = tk.Label(frame_url, text="url", width=6)
		lbl_url.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_url = Entry(frame_url)
		self.entry_url.insert(tk.END, 'google.com')
		self.entry_url.pack(fill=tk.X, padx=5, expand=True)

		btn_exit = tk.Button(self, text="Back",
						   command=self.OnClose)
		btn_exit.pack(side=tk.RIGHT, padx=5, pady=5)

		self.btn_test = tk.Button(self, text="Run",
						   command=self.WifiTest)
		self.btn_test.pack(side=tk.RIGHT, padx=5, pady=5)

	def OnClose(self):
		self.btn_test.config(state=tk.NORMAL)
		self.controller.show_frame("StartPage")

	def WifiTest(self):
		if self.entry_ssid.get() == "":
			mbox.showerror("Error", "ssid should not be blank")
			return
		if self.entry_password.get() == "":
			mbox.showerror("Error", "password should not be blank")
			return
		if self.entry_url.get() == "":
			mbox.showerror("Error", "url should not be blank")
			return

		App_Argument = ""
		if ENABLE_ARGUMENT == True:
			App_Argument += " -t wifi -s " + self.entry_ssid.get() + \
						" -p " + self.entry_password.get() + \
						" -l " + self.entry_url.get()
		else:
			App_Argument = LED_WIFI
		print RUN_SCRIPT + WIFI_TEST_APP + App_Argument

		if ssh_session.CreateSshSession(RUN_SCRIPT + WIFI_TEST_APP + App_Argument, WIFI_TEST_APP) != 0:
			return self.OnClose()

		self.btn_test.config(state=tk.DISABLED)
Ejemplo n.º 29
0
class MainForm(Frame):
    """
    If method is handling some GUI shit, its written in camelCase style
    """
    def __init__(self, parent, caller_instance):
        Frame.__init__(self, parent)
        self.caller_instance = caller_instance
        self.running_on = "%s:%s" % (get_local_addr(),
                                     getattr(self.caller_instance, 'port',
                                             None) or "8888")
        self.parent = parent
        caller_instance.messangers.append(self)
        self.initUI()

    def initUI(self):
        self.__centerWindow()
        self.parent.title("epyks %s" % self.running_on)
        #
        # Addr textbox
        #
        addr_validate = (self.parent.register(self.addrValidation), '%S', '%d')
        self.EntryAddress = Entry(self,
                                  validate='key',
                                  validatecommand=addr_validate,
                                  width=17)
        self.EntryAddress.grid(row=0,
                               column=0,
                               padx=10,
                               pady=5,
                               columnspan=2,
                               sticky=W)
        self.EntryAddress.delete(0, END)
        self.EntryAddress.insert(0, "192.168.0.102:8889")
        #
        # Call button
        #
        self.ButtonCall = Button(self,
                                 text="Call",
                                 command=self.onButtonCallClick)
        self.ButtonCall.grid(row=0, column=1, pady=5)
        #
        #   Callmode status canvas
        #
        self.CanvasCallmode = Canvas(self,
                                     width=20,
                                     height=20,
                                     bg="light grey")
        self.CanvasCallmode.create_oval(1,
                                        1,
                                        20,
                                        20,
                                        fill="red",
                                        outline="light grey")
        self.CanvasCallmode.grid(row=1,
                                 column=0,
                                 pady=0,
                                 padx=10,
                                 sticky=W,
                                 columnspan=2)
        #
        #   Callmode status label
        #
        self.LabelCallmode = Label(self, text="Not connected")
        self.LabelCallmode.grid(row=1, column=0, padx=35)
        #
        #   End call button
        #
        self.ButtonEndCall = Button(self,
                                    text="End call",
                                    command=self.onButtonEndCallClick)
        self.ButtonEndCall.grid(row=1, column=1)

        #
        #   Message listbox
        #
        self.MessagesListBox = Listbox(self)
        self.MessagesListBox.grid(row=2,
                                  column=0,
                                  columnspan=2,
                                  padx=2,
                                  pady=2,
                                  sticky="EW")
        #
        # Message entry
        #
        self.EntryMessage = Entry(self)
        self.EntryMessage.grid(row=3, column=0, padx=2)
        #
        # Send message
        #
        self.ButtonSendMessage = Button(self,
                                        text="Send",
                                        command=self.onButtonSendMessageClick)
        self.ButtonSendMessage.grid(row=3, column=1)

        # Testing

        # Pack all
        self.pack(fill=BOTH, expand=1)

    def onGetAnswerMessageBox(self, interlocutor):
        return tkMessageBox.askyesno(
            title="Incoming call",
            message="A call from {}, wanna answer?".format(interlocutor))

    def addrValidation(self, string, action):
        print string
        if action != 1:
            # 0 - delete, 1 - insert, -1 - focus in/out
            return True
        print "addrValidation: %s" % string
        if len(string) > 1:
            return full_ipv4_check(fulladdr=string)
        return string in ACCEPTABLE_CHARS

    def onTextBoxChange(self, *args, **kwargs):
        print 'lol ' + str(args) + str(kwargs)

    def onButtonCallClick(self):
        address = (self.EntryAddress.get())
        if not full_ipv4_check(fulladdr=address):
            tkMessageBox.showerror(message="Incorrect address")
        ip, port = address.split(':')
        self.caller_instance.call((ip, int(port)))

    def onButtonSendMessageClick(self):
        message = self.EntryMessage.get()
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author="self", message=message))
        ip, port = self.EntryAddress.get().split(':')
        self.caller_instance.send(message=message, address=(ip, int(port)))

    def onButtonEndCallClick(self):
        self.caller_instance.hang_up()

    def onMessageRecieved(self, author, message):
        """
        :param author: Address of author, tuple (ip, port)
        :param message: Content
        """
        author = ''.join([author[0], ':', str(author[1])])
        self.MessagesListBox.insert(
            END, "{author}> {message}".format(author=author, message=message))

    def checkStatus(self):
        status = self.caller_instance.status
        if status.startswith('On'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="green",
                                            outline="light grey")
            self.EntryAddress.delete(0, END)
            self.EntryAddress.insert(
                0, "{}:{}".format(self.caller_instance.interlocutor[0],
                                  self.caller_instance.interlocutor[1]))
            self.EntryAddress.configure(state='readonly')

        elif status.startswith('Not'):
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="red",
                                            outline="light grey")
            self.EntryAddress.configure(state='')
        else:
            self.CanvasCallmode.create_oval(1,
                                            1,
                                            20,
                                            20,
                                            fill="yellow",
                                            outline="light grey")
            self.EntryAddress.configure(state='readonly')
        self.LabelCallmode['text'] = status
        self.parent.after(ms=100, func=self.checkStatus)

    def __centerWindow(self):
        w = 260
        h = 270
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
Ejemplo n.º 30
0
    def init_ui(cls, self):
        """ Init the UI, creating all the frames """

        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)

        ## Frame 0 - Description Only
        frame0 = Frame(self)
        frame0.pack(fill=X)

        descrizione = Label(frame0, text="Compilare tutti i campi e poi " \
        "salvare per inserire una nuova riga nel file", width=100)
        descrizione.pack(side=LEFT, padx=5, pady=5)

        ### Frame 1
        frame1 = Frame(self)
        frame1.pack(fill=X)

        domanda = Label(frame1, text="Domanda", width=20)
        domanda.pack(side=LEFT, padx=5, pady=5)

        entry1 = Entry(frame1)
        entry1.pack(fill=X, padx=5, expand=True)

        ### Frame 2
        frame2 = Frame(self)
        frame2.pack(fill=X)

        risposta1 = Label(frame2, text="Risposta 1 - ERRATA", width=20)
        risposta1.pack(side=LEFT, padx=5, pady=5)

        entry2 = Entry(frame2)
        entry2.pack(fill=X, padx=5, expand=False)

        ### Frame 3
        frame3 = Frame(self)
        frame3.pack(fill=X)

        risposta2 = Label(frame3, text="Risposta 2 - ERRATA", width=20)
        risposta2.pack(side=LEFT, padx=5, pady=5)

        entry3 = Entry(frame3)
        entry3.pack(fill=X, padx=5, expand=True)

        ### Frame 4
        frame4 = Frame(self)
        frame4.pack(fill=X)

        risposta_giusta = Label(frame4, text="Risposta CORRETTA", width=20)
        risposta_giusta.pack(side=LEFT, padx=5, pady=5)

        entry4 = Entry(frame4)
        entry4.pack(fill=X, padx=5, expand=True)

        ### Frame 6
        frame6 = Frame(self)
        frame6.pack(fill=BOTH, expand=True)

        # Close button -> close on click
        close_button = Button(self, text="Chiudi", command=self.master.quit)
        close_button.pack(side=RIGHT, padx=5, pady=5)

        # Save button -> save a new line in the file and continues the exec
        ok_button = Button(self, text="Salva",
                        command=lambda: self.value_get(self, \
                                Question(entry1.get(), entry2.get(), \
                                entry3.get(), entry4.get())))
        ok_button.pack(side=RIGHT)
Ejemplo n.º 31
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Review")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 20, 'bold')
        labelfont12 = ('Roboto', 12, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi USER")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont12)
        lbl00.pack(padx=5, pady=5)

        frame1 = Frame(self)
        frame1.pack()

        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        frame2 = Frame(self)
        frame2.pack()

        lbl2 = Label(frame2, text="Branch", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)

        frame3 = Frame(self)
        frame3.pack()

        lbl3 = Label(frame3, text="Percent", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        frame4 = Frame(self)
        frame4.pack()

        lbl4 = Label(frame4, text="Placed(Yes/No)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)

        frame5 = Frame(self)
        frame5.pack()

        lbl5 = Label(frame5, text="Resume_File", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        self.entry5 = Entry(frame5)
        self.entry5.pack(fill=X, padx=5, expand=True)

        frame6 = Frame(self)
        frame6.pack()
        closeButton = Button(frame6,
                             text="SUBMIT",
                             width=15,
                             command=self.getDate)
        closeButton.pack(padx=5, pady=5)

        frame000 = Frame(self)
        frame000.pack()

        self.lbl000 = Label(frame000, text="Enter the data and click SUBMIT")
        self.lbl000.config(font=labelfont12)
        self.lbl000.pack(padx=5, pady=5)

    def getDate(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()
        x5 = self.entry5.get()

        list1 = [x1, x2, x3, x4, "=HYPERLINK(" + "\"" + x5 + "\"" + ")"]
        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')
        self.entry5.delete(0, 'end')
        self.lbl000.config(text="YO")

        with open("test.csv", "ab") as fp:
            wr = csv.writer(fp, dialect='excel')
            wr.writerow(list1)
        fp.close()
Ejemplo n.º 32
0
    def initUI(self):

        self.parent.title("Caritas")
        self.style = Style()
        self.style.theme_use("default")

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

        frameMenu = Frame(self)
        frameMenu.pack(fill="both", expand="0", side=RIGHT)

        labelBusqueda = LabelFrame(frameMenu, text="Busqueda")
        labelBusqueda.pack(fill="x",expand =1)

        labelVoluntarios = LabelFrame(frameMenu)
        labelVoluntarios.pack(fill="both",expand =0)

        frameTabla = Frame(self)
        frameTabla.pack(fill="both", expand="1", side=LEFT)

        labelTabla = LabelFrame(frameTabla)
        labelTabla.pack(fill="both", expand="1")

        labelBotonera = LabelFrame(frameTabla)
        labelTabla.pack(fill="both", expand="1")

        labelSelect = LabelFrame(frameTabla)
        labelSelect.pack(fill="both", expand="1")

        model = TableModel()
        modelSelect = TableModel()

        model.addColumn("nombre")
        model.addColumn("apellidos")
        model.addColumn("dni")
        model.addColumn("direccion")
        model.addColumn("correo_electronico")
        model.addColumn("estudio")
        model.addColumn("parroquial")
        model.addColumn("proyecto")
        model.addColumn("genero")
        model.addColumn("fecha_nacimiento")
        model.addColumn("telefono_1")
        model.addColumn("telefono_2")

        modelSelect.addColumn("nombre")
        modelSelect.addColumn("apellidos")
        modelSelect.addColumn("dni")
        modelSelect.addColumn("direccion")
        modelSelect.addColumn("correo_electronico")
        modelSelect.addColumn("estudio")
        modelSelect.addColumn("parroquial")
        modelSelect.addColumn("proyecto")
        modelSelect.addColumn("genero")
        modelSelect.addColumn("fecha_nacimiento")
        modelSelect.addColumn("telefono_1")
        modelSelect.addColumn("telefono_2")

        #Tabla Voluntarios
        self.listilla= queryAllVoluntarios()
        model.importDict(self.listilla)
        self.table = TableCanvas(labelTabla, model=model,editable=False)
        self.table.createTableFrame()
        self.table.handle_double_click(self.eventoClic)

        #Tabla Seleccionados
        self.selectTable = TableCanvas(labelSelect, model=modelSelect,editable=False)
        self.selectTable.createTableFrame()
        self.listadoSeleccionado = []

        L1 = Label(labelBusqueda, text="Nombre")
        L1.pack()
        E1 = Entry(labelBusqueda)
        E1.pack()

        L2 = Label(labelBusqueda, text="Apellidos")
        L2.pack()
        E2 = Entry(labelBusqueda)
        E2.pack()

        botonArriba = Button(labelVoluntarios, text="Agregar al listado",  command=lambda:self.agregarListado(self.table.getSelectedRow()))
        botonArriba.pack()
        botonAbajo = Button(labelVoluntarios, text="Quitar del listado",  command=lambda:self.quitarListado(self.selectTable.getSelectedRow()))
        botonAbajo.pack()

        button = Button(labelBusqueda, text="Buscar", command=lambda: self.buscar(E1.get(),E2.get()))
        button.pack()

        button = Button(labelVoluntarios, text="Nuevo Voluntario",  command=lambda:self.ventanaVoluntarios(-1))
        button.pack()

        buttonEditar = Button(labelVoluntarios, text="Editar Voluntario",  command=lambda:self.ventanaVoluntarios(self.table.getSelectedRow()))
        buttonEditar.pack()

        buttonImprimir = Button(labelVoluntarios, text="Imprimir",  command=lambda:self.ventanaImprimir())
        buttonImprimir.pack()
Ejemplo n.º 33
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
        
    def initUI(self):
   
      
        self.parent.title("Append Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')
        
        frame0 = Frame(self)
        frame0.pack()
        
        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)    
        lbl0.pack( padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont10)
        lbl00.pack( padx=5, pady=5)
        
        ####################################
        frame1 = Frame(self)
        frame1.pack()
        frame1.place(x=50, y=100)        
        
        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT,padx=7, pady=5) 
             
        self.entry1 = Entry(frame1,width=20)
        self.entry1.pack(padx=5, expand=True)
    
        ####################################
        frame2 = Frame(self)
        frame2.pack()
        frame2.place(x=50, y=130)
        
        lbl2 = Label(frame2, text="F Name", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)
        
        ######################################
        frame3 = Frame(self)
        frame3.pack()
        frame3.place(x=50, y=160)
        
        lbl3 = Label(frame3, text="DOB(D/M/Y)", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)        

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True) 
        
        #######################################
        frame4 = Frame(self)
        frame4.pack()
        frame4.place(x=50, y=190)
        
        lbl4 = Label(frame4, text="Medium(H/E)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)        

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)
        
        ##########################################
        frame5 = Frame(self)
        frame5.pack()
        frame5.place(x=50, y=225)  
        MODES = [
            ("M", "Male"),
            ("F", "Female"),
            ]
        lbl5 = Label(frame5, text="Gender", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        global v
        v = StringVar()
        v.set("Male") # initialize

        for text, mode in MODES:
            b = Radiobutton(frame5, text=text,variable=v, value=mode)
            b.pack(side=LEFT,padx=10)
        
        ############################################
        #####printing line
        lbl5a = Label(text="___________________________________________________")
        lbl5a.pack()
        lbl5a.place(x=45, y=255)  
        
        ############################################
        frame6 = Frame(self)
        frame6.pack()
        frame6.place(x=50, y=290)
        
        lbl6 = Label(frame6, text="Phone No:", width=15)
        lbl6.pack(side=LEFT, padx=7, pady=5)        

        self.entry6 = Entry(frame6)
        self.entry6.pack(fill=X, padx=5, expand=True)
        
        ################################################
        
        frame7 = Frame(self)
        frame7.pack()
        frame7.place(x=50, y=320)
        
        lbl7 = Label(frame7, text="Landline No:", width=15)
        lbl7.pack(side=LEFT, padx=7, pady=5)        

        self.entry7 = Entry(frame7)
        self.entry7.pack(fill=X, padx=5, expand=True)
        
        ###############################################
        frame8 = Frame(self)
        frame8.pack()
        frame8.place(x=50, y=350)
        
        lbl8 = Label(frame8, text="Email:", width=15)
        lbl8.pack(side=LEFT, padx=7, pady=5)        

        self.entry8 = Entry(frame8)
        self.entry8.pack(fill=X, padx=5, expand=True)
        
        #############################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=50, y=380)
        
        lbl9 = Label(frame9, text="HomeTown:", width=15)
        lbl9.pack(side=LEFT, padx=7, pady=5)        

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)
        
        ###############################################
        frame10 = Frame(self)
        frame10.pack()
        frame10.place(x=60, y=415)
        
        lbl10 = Label(frame10, text="Address:")
        lbl10.pack( padx=5, pady=5)        

        self.entry10 = Text(frame10,height=5, width=28)
        self.entry10.pack(padx=5, expand=True)
        
        ##############################################
        
        #############################################
        
        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=350, y=100)
        
        lbl11x = Label(frame11,text="_______Class 10th Data_______")
        lbl11x.pack(padx=0, pady=0)
        
        lbl11 = Label(text="%",width=15)
        lbl11.pack(side=LEFT,padx=0, pady=0)
        lbl11.place(x=350, y=130)        

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=420, y=130) 
        
        lbl11a = Label(text="Passing Year",width=15)
        lbl11a.pack(padx=0, pady=2)   
        lbl11a.place(x=350, y=160)   

        self.entry11a = Entry(width=12)
        self.entry11a.pack(padx=1, expand=True)
        self.entry11a.place(x=420, y=160) 
        
        lbl11b = Label(text="Board Name",width=15)
        lbl11b.pack(padx=0, pady=2)   
        lbl11b.place(x=350, y=190)   

        self.entry11b = Entry(width=12)
        self.entry11b.pack(padx=1, expand=True)
        self.entry11b.place(x=420, y=190)
        
        
        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=510, y=100)
        
        lbl12x = Label(frame12,text="_______Class 12th Data_______")
        lbl12x.pack(padx=0, pady=0)
        
        lbl12 = Label(text="%",width=15)
        lbl12.pack(side=LEFT,padx=0, pady=0)
        lbl12.place(x=510, y=130)        

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=580, y=130) 
        
        lbl12a = Label(text="Passing Year",width=15)
        lbl12a.pack(padx=0, pady=2)   
        lbl12a.place(x=510, y=160)   

        self.entry12a = Entry(width=12)
        self.entry12a.pack(padx=1, expand=True)
        self.entry12a.place(x=580, y=160) 
        
        lbl12b = Label(text="Board Name",width=15)
        lbl12b.pack(padx=0, pady=2)   
        lbl12b.place(x=510, y=190)   

        self.entry12b = Entry(width=12)
        self.entry12b.pack(padx=1, expand=True)
        self.entry12b.place(x=580, y=190)

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=670, y=100)
        
        lbl13x = Label(frame13,text="________B.Tech Data_________")
        lbl13x.pack(padx=0, pady=0)
        
        lbl13 = Label(text="%",width=15)
        lbl13.pack(side=LEFT,padx=0, pady=0)
        lbl13.place(x=670, y=130)        

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=740, y=130) 
        
        lbl13a = Label(text="Passing Year",width=15)
        lbl13a.pack(padx=0, pady=2)   
        lbl13a.place(x=670, y=160)   

        self.entry13a = Entry(width=12)
        self.entry13a.pack(padx=1, expand=True)
        self.entry13a.place(x=740, y=160) 
        
        lbl13b = Label(text="College",width=15)
        lbl13b.pack(padx=0, pady=2)   
        lbl13b.place(x=670, y=190)   

        self.entry13b = Entry(width=12)
        self.entry13b.pack(padx=1, expand=True)
        self.entry13b.place(x=740, y=190)
        
        ####################################################
        
        frame14 = Frame(self)
        frame14.pack()
        frame14.place(x=380, y=255)
        
        lbl14 = Label(frame14, text="Any Other Info:")
        lbl14.pack( padx=5, pady=5)        

        self.entry14 = Text(frame14,height=5, width=28)
        self.entry14.pack(padx=5, expand=True)
             
         
        
        frame15 = Frame(self)
        frame15.pack()
        frame15.place(x=650, y=290)
        
        openButton = Button(frame15, text="Attatch Resume",width=15,command=self.openResume)
        openButton.pack(padx=5, pady=5)
        self.entry15 = Entry(frame15)
        self.entry15.pack(fill=X, padx=4, expand=True)
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=450, y=500)
        
        closeButton = Button(frame16, text="SUBMIT",width=35,command=self.getDatax)
        closeButton.pack(padx=5, pady=5)
        
        #######################################
        framexxx = Frame(self)
        framexxx.pack()
        framexxx.place(x=700, y=600)
        self.xxx = Label(framexxx,text="Recent Changes Will Appear Here")
        self.xxx.config(font=labelfont8) 
        self.xxx.pack()
        
        #######################################
        
        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)
        
        self.lbl000= Label(frame000, text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)    
        self.lbl000.pack( padx=5, pady=5)
        
        
           

    def openResume(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes,initialdir='C:/Users/')
        global x15
        fl = dlg.show()
        #file name
        x15 = fl
        temp1 = os.path.basename(fl)
        global temp2
        temp2 = os.path.splitext(temp1)[0]
        
        self.entry15.delete(0, 'end')
        self.entry15.insert(0,temp2)
        
      
        
        
        
        #####################
        
        
        
        
        
    def getDatax(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()
        
        x5 = v.get()
        
        x6 = int(self.entry6.get())
        x7 = int(self.entry7.get())
        x8 = self.entry8.get()
        x9 = self.entry9.get()
        
        x10 = self.entry10.get('1.0', 'end')
        
        x11 = int(self.entry11.get())
        x11a = int(self.entry11a.get())
        x11b = self.entry11b.get()
        
        x12 = int(self.entry12.get())
        x12a = int(self.entry12a.get())
        x12b = self.entry12b.get()
        
        x13 = int(self.entry13.get())
        x13a = int(self.entry13a.get())
        x13b = self.entry13b.get()
        
        x14 = self.entry14.get('1.0', 'end')
        
        
        
        
        
        list1=[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x11a,x11b,x12,x12a,x12b,x13,x13a,x13b,x14,"=HYPERLINK("+"\""+x15+"\""+","+"\""+temp2+"\""+")"]
        
        
        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        #max_col = ws.get_highest_column()
        max_col = 21
        print max_row
        
        for i in xrange(1,max_col+1):
            #print list1[i]
            ws.cell(row = max_row+1, column = i).value = list1[i-1]
        ws.cell(row = max_row+1, column = max_col).font = Font(color="0000FF", underline='single')
        ws.cell(row = max_row+1, column = max_col).alignment = Alignment(horizontal='center')
        wb.save('..\database\database.xlsx')
        
        
        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')
        
        self.entry6.delete(0, 'end')
        self.entry7.delete(0, 'end')
        self.entry8.delete(0, 'end')
        self.entry9.delete(0, 'end')
        self.entry10.delete('1.0', '2.0')
        self.entry11.delete(0, 'end')
        self.entry11a.delete(0, 'end')
        self.entry11b.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry12a.delete(0, 'end')
        self.entry12b.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry13a.delete(0, 'end')
        self.entry13b.delete(0, 'end')
        
        self.entry14.delete('1.0', '2.0')
        
        
        self.xxx.config(text="Recent Changes Made For : "+x1)
Ejemplo n.º 34
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUIGlobals()

    def initUIGlobals(self):

        self.parent.title("Ini Generator")

        Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10')

        f1 = Frame(self)
        f1.grid(row=0, column=0, padx=10, sticky=N + S + E + W)

        f11 = LabelFrame(f1, text="Algorithms to Run")
        f11.grid(row=0, column=0)
        row = 0

        self.check_algs_value_list = []
        self.check_algs_map = {}
        for alg in algorithms:
            if alg == 'clean':
                continue
            check_alg_value = IntVar()
            check_alg = Checkbutton(f11,
                                    text=alg,
                                    variable=check_alg_value,
                                    justify=LEFT,
                                    width=25)
            check_alg.grid(row=row, column=0, sticky=W + E)
            self.check_algs_value_list.append(check_alg_value)
            self.check_algs_map[alg] = check_alg_value
            row += 1

        f111 = Frame(f11)
        f111.grid(row=row, column=0)

        button_checkall = Button(f111, text="All", command=self.checkall)
        button_checkall.grid(row=0, column=0, sticky=W + E)
        button_uncheckall = Button(f111, text="None", command=self.uncheckall)
        button_uncheckall.grid(row=0, column=1, sticky=W + E)

        row = 0

        f12 = Frame(f1)
        f12.grid(row=1, column=0, pady=20, sticky=S + W + E)

        f121 = LabelFrame(f12, text='Location of uPMU')
        f121.grid(row=0, column=0)

        self.radio_loc_string = StringVar()
        locations.append('Other Location')
        for loc in locations:
            radio_loc = Radiobutton(f121,
                                    text=loc,
                                    variable=self.radio_loc_string,
                                    value=loc,
                                    command=self.set_loc,
                                    justify=LEFT,
                                    width=25)
            radio_loc.grid(row=row, column=0, sticky=W + E)
            row += 1

        self.entry_otherloc = Entry(f121)

        f2 = Frame(self)
        f2.grid(row=0, column=1, padx=10, sticky=N + S + E + W)

        f21 = LabelFrame(f2, text='Name of uPMU (raw)')
        f21.grid(row=0)
        row = 0

        f211 = Frame(f21)
        f211.grid(row=row)
        row += 1

        self.entry_namesearch = Entry(f211)
        self.entry_namesearch.grid(row=0, column=0, sticky=E + W)

        button_namesearch = Button(f211,
                                   text="Search",
                                   command=self.namesearch)
        button_namesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_namelist = Listbox(f21)
        self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
        self.lstbx_namelist.grid(row=row, sticky=W + E)
        row += 1

        f212 = Frame(f21)
        f212.grid(row=row)
        row += 1

        label_nameselected = Label(f212, text="Selected:")
        label_nameselected.grid(row=0, column=0)

        self.entry_nameselected = Entry(f212, state=DISABLED)
        self.entry_nameselected.grid(row=0, column=1, sticky=W + E)

        f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
        f22.grid(row=1, sticky=W + E, pady=10)
        self.entry_name = Entry(f22, width=30)
        self.entry_name.grid(row=0, column=0, sticky=E + W)

        f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
        f23.grid(row=2, pady=10)
        row = 0

        f231 = Frame(f23)
        f231.grid(row=row)
        row += 1

        self.entry_refnamesearch = Entry(f231)
        self.entry_refnamesearch.grid(row=0, column=0, sticky=E + W)

        button_refnamesearch = Button(f231,
                                      text="Search",
                                      command=self.refnamesearch)
        button_refnamesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_refnamelist = Listbox(f23)
        self.lstbx_refnamelist.bind("<Double-Button-1>",
                                    self.refnamelist_select)
        self.lstbx_refnamelist.grid(row=row, sticky=W + E)
        row += 1

        f232 = Frame(f23)
        f232.grid(row=row)
        row += 1

        label_refnameselected = Label(f232, text="Selected:")
        label_refnameselected.grid(row=0, column=0)

        self.entry_refnameselected = Entry(f232, state=DISABLED)
        self.entry_refnameselected.grid(row=0, column=1, sticky=W + E)

        button_gen = Button(self,
                            text="Generate Files",
                            command=self.generate_files)
        button_gen.grid(row=1, column=0, columnspan=2, sticky=W + E)

        self.pack()

    def generate_files(self):
        algs = []
        for alg in self.check_algs_map:
            if self.check_algs_map[alg].get() == 1:
                algs.append(alg)

        if self.radio_loc_string.get() == "Other Location":
            location = self.entry_otherloc.get()
        else:
            location = self.radio_loc_string.get()

        name_raw = self.entry_nameselected.get()
        name = self.entry_name.get()
        ref_name = self.entry_refnameselected.get()

        uuid_map = self.get_uuid_map(name_raw)
        reference_uuid_map = self.get_ref_uuid_map(ref_name)

        IniGenAutomation(location, name_raw, name, uuid_map, ref_name,
                         reference_uuid_map, algs)

    def namesearch(self):
        searchterm = self.entry_namesearch.get()
        if searchterm.contains("/"):
            loc = searchterm.split('/')
            searchphrase = '/upmu/%{0}%/%{1}%/%'.format(loc[0], loc[1])
        else:
            searchphrase = '/upmu/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_namelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_namelist.insert(END, result)

    def refnamesearch(self):
        searchterm = self.entry_refnamesearch.get()
        searchphrase = '/Clean/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_refnamelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_refnamelist.insert(END, result)

    def search(self, searchterm, searchphrase):
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(
                searchphrase))
        results = connection.store_result()
        queried_data = {}
        result = results.fetch_row()
        while result != tuple():
            queried_data[result[0][0]] = result[0][1]
            result = results.fetch_row()
        search_results = set()
        for path in queried_data:
            dirs = path.split('/')
            if searchterm in dirs[2]:
                search_results.add(dirs[2])
        return search_results

    def set_loc(self):
        if self.radio_loc_string.get() == "Other Location":
            self.entry_otherloc.grid(sticky=W + E)
        else:
            self.entry_otherloc.grid_forget()

    def checkall(self):
        for check in self.check_algs_value_list:
            check.set(1)

    def uncheckall(self):
        for check in self.check_algs_value_list:
            check.set(0)

    def namelist_select(self, event):
        selected_index = self.lstbx_namelist.curselection()
        selected = self.lstbx_namelist.get(selected_index)
        self.entry_nameselected.configure(state=NORMAL)
        self.entry_nameselected.delete(0, END)
        self.entry_nameselected.insert(0, selected)
        self.entry_nameselected.configure(state=DISABLED)

    def refnamelist_select(self, event):
        selected_index = self.lstbx_refnamelist.curselection()
        selected = self.lstbx_refnamelist.get(selected_index)
        self.entry_refnameselected.configure(state=NORMAL)
        self.entry_refnameselected.delete(0, END)
        self.entry_refnameselected.insert(0, selected)
        self.entry_refnameselected.configure(state=DISABLED)

    def get_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-1]] = result[0][1]
            result = results.fetch_row()
        return uuid_map

    def get_ref_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-2]] = result[0][1]
            result = results.fetch_row()
        return uuid_map
Ejemplo n.º 35
0
class CommSearch(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):

        self.entries_found = []

        self.parent.title("Search your command cards")
        self.style = Style()
        self.style.theme_use("default")        
        self.pack()
        
        self.input_title = Label(self, text="Enter your command below")
        self.input_title.grid(row=0, columnspan=2)
        self.input_box = Entry(self, width=90)
        self.input_box.grid(row=1, column=0)
        self.input_box.focus()
        self.input_box.bind("<Key>", self.onUpdateSearch)
        self.search_btn = Button(self, text="Search", command=self.onSearch)
        self.search_btn.grid(row=1, column=1)
        self.output_box = Treeview(self, columns=("Example"))
        ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview)
        xsb = Scrollbar(self, orient='horizontal', command=self.output_box.xview)
        self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.output_box.heading('Example', text='Example', anchor='w')
        self.output_box.column("#0",minwidth=0,width=0, stretch=NO)
        self.output_box.column("Example",minwidth=0,width=785)
        self.output_box.bind("<Button-1>", self.OnEntryClick)
        self.output_box.grid(row=3, columnspan=2)
        self.selected_box = Text(self, width=110, height=19)
        self.selected_box.grid(row=4, columnspan=2)
        self.gotoadd_btn = Button(self, text="Go to Add", command=self.onGoToAdd)
        self.gotoadd_btn.grid(row=5)

    def OnEntryClick(self, event):
        try:
            item = self.output_box.selection()[0]
        except IndexError:
            pass
        entry_title = self.output_box.item(item,"value")
        for item in self.entries_found:
            if str(entry_title) == str("('" + item.title.strip('\n') + "',)"):
                self.selected_box.delete(0.1, END)
                self.selected_box.insert(END, item.text + '\n')

    def onUpdateSearch(self, key):
    # Somehow calling self.onSearch() does not register last key
    # And we need to correct "special chars"
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)		
    # ...like, for instance, deleting last character
        if key.char == '\b':
            search_terms = str(self.input_box.get()[:-1])
        else: 
            search_terms = str(self.input_box.get() + key.char)
        self.entries_found = []
        self.entries_found = data.Search(search_terms,entries,entries_map)
        for item in range(len(self.entries_found)):
            aux = self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])

			
    def onSearch(self):
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)
        search_terms = str(self.input_box.get())
        for item in data.Search(search_terms,entries,entries_map):
            self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])
			
    def onGoToAdd(self):
        newroot = Tk()
        newcomm = CommAdd(newroot)
        newroot.geometry("800x600+0+0")
        newroot.mainloop()
Ejemplo n.º 36
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Append Data")
        self.pack(fill=BOTH, expand=True)
        labelfont20 = ('Roboto', 15, 'bold')
        labelfont10 = ('Roboto', 10, 'bold')
        labelfont8 = ('Roboto', 8, 'bold')

        frame0 = Frame(self)
        frame0.pack()

        lbl0 = Label(frame0, text="Hi Nakul")
        lbl0.config(font=labelfont20)
        lbl0.pack(padx=5, pady=5)
        lbl00 = Label(frame0, text="Fill the data here")
        lbl00.config(font=labelfont10)
        lbl00.pack(padx=5, pady=5)

        ####################################
        frame1 = Frame(self)
        frame1.pack()
        frame1.place(x=50, y=100)

        lbl1 = Label(frame1, text="Name", width=15)
        lbl1.pack(side=LEFT, padx=7, pady=5)

        self.entry1 = Entry(frame1, width=20)
        self.entry1.pack(padx=5, expand=True)

        ####################################
        frame2 = Frame(self)
        frame2.pack()
        frame2.place(x=50, y=130)

        lbl2 = Label(frame2, text="F Name", width=15)
        lbl2.pack(side=LEFT, padx=7, pady=5)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)

        ######################################
        frame3 = Frame(self)
        frame3.pack()
        frame3.place(x=50, y=160)

        lbl3 = Label(frame3, text="DOB(D/M/Y)", width=15)
        lbl3.pack(side=LEFT, padx=7, pady=5)

        self.entry3 = Entry(frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        #######################################
        frame4 = Frame(self)
        frame4.pack()
        frame4.place(x=50, y=190)

        lbl4 = Label(frame4, text="Medium(H/E)", width=15)
        lbl4.pack(side=LEFT, padx=7, pady=5)

        self.entry4 = Entry(frame4)
        self.entry4.pack(fill=X, padx=5, expand=True)

        ##########################################
        frame5 = Frame(self)
        frame5.pack()
        frame5.place(x=50, y=225)
        MODES = [
            ("M", "Male"),
            ("F", "Female"),
        ]
        lbl5 = Label(frame5, text="Gender", width=15)
        lbl5.pack(side=LEFT, padx=7, pady=5)

        global v
        v = StringVar()
        v.set("Male")  # initialize

        for text, mode in MODES:
            b = Radiobutton(frame5, text=text, variable=v, value=mode)
            b.pack(side=LEFT, padx=10)

        ############################################
        #####printing line
        lbl5a = Label(
            text="___________________________________________________")
        lbl5a.pack()
        lbl5a.place(x=45, y=255)

        ############################################
        frame6 = Frame(self)
        frame6.pack()
        frame6.place(x=50, y=290)

        lbl6 = Label(frame6, text="Phone No:", width=15)
        lbl6.pack(side=LEFT, padx=7, pady=5)

        self.entry6 = Entry(frame6)
        self.entry6.pack(fill=X, padx=5, expand=True)

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

        frame7 = Frame(self)
        frame7.pack()
        frame7.place(x=50, y=320)

        lbl7 = Label(frame7, text="Landline No:", width=15)
        lbl7.pack(side=LEFT, padx=7, pady=5)

        self.entry7 = Entry(frame7)
        self.entry7.pack(fill=X, padx=5, expand=True)

        ###############################################
        frame8 = Frame(self)
        frame8.pack()
        frame8.place(x=50, y=350)

        lbl8 = Label(frame8, text="Email:", width=15)
        lbl8.pack(side=LEFT, padx=7, pady=5)

        self.entry8 = Entry(frame8)
        self.entry8.pack(fill=X, padx=5, expand=True)

        #############################################
        frame9 = Frame(self)
        frame9.pack()
        frame9.place(x=50, y=380)

        lbl9 = Label(frame9, text="HomeTown:", width=15)
        lbl9.pack(side=LEFT, padx=7, pady=5)

        self.entry9 = Entry(frame9)
        self.entry9.pack(fill=X, padx=5, expand=True)

        ###############################################
        frame10 = Frame(self)
        frame10.pack()
        frame10.place(x=60, y=415)

        lbl10 = Label(frame10, text="Address:")
        lbl10.pack(padx=5, pady=5)

        self.entry10 = Text(frame10, height=5, width=28)
        self.entry10.pack(padx=5, expand=True)

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

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

        frame11 = Frame(self)
        frame11.pack()
        frame11.place(x=350, y=100)

        lbl11x = Label(frame11, text="_______Class 10th Data_______")
        lbl11x.pack(padx=0, pady=0)

        lbl11 = Label(text="%", width=15)
        lbl11.pack(side=LEFT, padx=0, pady=0)
        lbl11.place(x=350, y=130)

        self.entry11 = Entry(width=12)
        self.entry11.pack(padx=1, expand=True)
        self.entry11.place(x=420, y=130)

        lbl11a = Label(text="Passing Year", width=15)
        lbl11a.pack(padx=0, pady=2)
        lbl11a.place(x=350, y=160)

        self.entry11a = Entry(width=12)
        self.entry11a.pack(padx=1, expand=True)
        self.entry11a.place(x=420, y=160)

        lbl11b = Label(text="Board Name", width=15)
        lbl11b.pack(padx=0, pady=2)
        lbl11b.place(x=350, y=190)

        self.entry11b = Entry(width=12)
        self.entry11b.pack(padx=1, expand=True)
        self.entry11b.place(x=420, y=190)

        ####################################################
        frame12 = Frame(self)
        frame12.pack()
        frame12.place(x=510, y=100)

        lbl12x = Label(frame12, text="_______Class 12th Data_______")
        lbl12x.pack(padx=0, pady=0)

        lbl12 = Label(text="%", width=15)
        lbl12.pack(side=LEFT, padx=0, pady=0)
        lbl12.place(x=510, y=130)

        self.entry12 = Entry(width=12)
        self.entry12.pack(padx=1, expand=True)
        self.entry12.place(x=580, y=130)

        lbl12a = Label(text="Passing Year", width=15)
        lbl12a.pack(padx=0, pady=2)
        lbl12a.place(x=510, y=160)

        self.entry12a = Entry(width=12)
        self.entry12a.pack(padx=1, expand=True)
        self.entry12a.place(x=580, y=160)

        lbl12b = Label(text="Board Name", width=15)
        lbl12b.pack(padx=0, pady=2)
        lbl12b.place(x=510, y=190)

        self.entry12b = Entry(width=12)
        self.entry12b.pack(padx=1, expand=True)
        self.entry12b.place(x=580, y=190)

        #####################################################
        frame13 = Frame(self)
        frame13.pack()
        frame13.place(x=670, y=100)

        lbl13x = Label(frame13, text="________B.Tech Data_________")
        lbl13x.pack(padx=0, pady=0)

        lbl13 = Label(text="%", width=15)
        lbl13.pack(side=LEFT, padx=0, pady=0)
        lbl13.place(x=670, y=130)

        self.entry13 = Entry(width=12)
        self.entry13.pack(padx=1, expand=True)
        self.entry13.place(x=740, y=130)

        lbl13a = Label(text="Passing Year", width=15)
        lbl13a.pack(padx=0, pady=2)
        lbl13a.place(x=670, y=160)

        self.entry13a = Entry(width=12)
        self.entry13a.pack(padx=1, expand=True)
        self.entry13a.place(x=740, y=160)

        lbl13b = Label(text="College", width=15)
        lbl13b.pack(padx=0, pady=2)
        lbl13b.place(x=670, y=190)

        self.entry13b = Entry(width=12)
        self.entry13b.pack(padx=1, expand=True)
        self.entry13b.place(x=740, y=190)

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

        frame14 = Frame(self)
        frame14.pack()
        frame14.place(x=380, y=255)

        lbl14 = Label(frame14, text="Any Other Info:")
        lbl14.pack(padx=5, pady=5)

        self.entry14 = Text(frame14, height=5, width=28)
        self.entry14.pack(padx=5, expand=True)

        frame15 = Frame(self)
        frame15.pack()
        frame15.place(x=650, y=290)

        openButton = Button(frame15,
                            text="Attatch Resume",
                            width=15,
                            command=self.openResume)
        openButton.pack(padx=5, pady=5)
        self.entry15 = Entry(frame15)
        self.entry15.pack(fill=X, padx=4, expand=True)
        #############################################################
        frame16 = Frame(self)
        frame16.pack()
        frame16.place(x=450, y=500)

        closeButton = Button(frame16,
                             text="SUBMIT",
                             width=35,
                             command=self.getDatax)
        closeButton.pack(padx=5, pady=5)

        #######################################
        framexxx = Frame(self)
        framexxx.pack()
        framexxx.place(x=700, y=600)
        self.xxx = Label(framexxx, text="Recent Changes Will Appear Here")
        self.xxx.config(font=labelfont8)
        self.xxx.pack()

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

        frame000 = Frame(self)
        frame000.pack()
        frame000.place(x=50, y=600)

        self.lbl000 = Label(frame000,
                            text="Beta/Sample2.0 | (c) Nakul Rathore")
        self.lbl000.config(font=labelfont8)
        self.lbl000.pack(padx=5, pady=5)

    def openResume(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes, initialdir='C:/Users/')
        global x15
        fl = dlg.show()
        #file name
        x15 = fl
        temp1 = os.path.basename(fl)
        global temp2
        temp2 = os.path.splitext(temp1)[0]

        self.entry15.delete(0, 'end')
        self.entry15.insert(0, temp2)

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

    def getDatax(self):
        x1 = self.entry1.get()
        x2 = self.entry2.get()
        x3 = self.entry3.get()
        x4 = self.entry4.get()

        x5 = v.get()

        x6 = int(self.entry6.get())
        x7 = int(self.entry7.get())
        x8 = self.entry8.get()
        x9 = self.entry9.get()

        x10 = self.entry10.get('1.0', 'end')

        x11 = int(self.entry11.get())
        x11a = int(self.entry11a.get())
        x11b = self.entry11b.get()

        x12 = int(self.entry12.get())
        x12a = int(self.entry12a.get())
        x12b = self.entry12b.get()

        x13 = int(self.entry13.get())
        x13a = int(self.entry13a.get())
        x13b = self.entry13b.get()

        x14 = self.entry14.get('1.0', 'end')

        list1 = [
            x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x11a, x11b, x12,
            x12a, x12b, x13, x13a, x13b, x14,
            "=HYPERLINK(" + "\"" + x15 + "\"" + "," + "\"" + temp2 + "\"" + ")"
        ]

        wb = openpyxl.load_workbook('..\database\database.xlsx')
        ws = wb.active
        print(wb.get_sheet_names())
        max_row = ws.get_highest_row()
        #max_col = ws.get_highest_column()
        max_col = 21
        print max_row

        for i in xrange(1, max_col + 1):
            #print list1[i]
            ws.cell(row=max_row + 1, column=i).value = list1[i - 1]
        ws.cell(row=max_row + 1,
                column=max_col).font = Font(color="0000FF", underline='single')
        ws.cell(row=max_row + 1,
                column=max_col).alignment = Alignment(horizontal='center')
        wb.save('..\database\database.xlsx')

        self.entry1.delete(0, 'end')
        self.entry2.delete(0, 'end')
        self.entry3.delete(0, 'end')
        self.entry4.delete(0, 'end')

        self.entry6.delete(0, 'end')
        self.entry7.delete(0, 'end')
        self.entry8.delete(0, 'end')
        self.entry9.delete(0, 'end')
        self.entry10.delete('1.0', '2.0')
        self.entry11.delete(0, 'end')
        self.entry11a.delete(0, 'end')
        self.entry11b.delete(0, 'end')
        self.entry12.delete(0, 'end')
        self.entry12a.delete(0, 'end')
        self.entry12b.delete(0, 'end')
        self.entry13.delete(0, 'end')
        self.entry13a.delete(0, 'end')
        self.entry13b.delete(0, 'end')

        self.entry14.delete('1.0', '2.0')

        self.xxx.config(text="Recent Changes Made For : " + x1)
Ejemplo n.º 37
0
class Example(Frame):
#Initialise values

    start_time=time.time()
    para_toggle=0
    grass_toggle=1
    string_toggle=0
    divide_toggle=0
    ctrl_toggle=0
    ctrlpt1=[85,55]
    ctrlpt1x=ctrlpt1[0]
    ctrlpt2=[150,180]
    ctrlpt3=[105,255]
    div_num = 8

#initilise Frame then initialise this Example class using initUI() 
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        
        self.parent = parent
        self.initUI()
        

        
    def initUI(self):
      
        self.parent.title("Grass")
#Configure parent for column layout       
        Style().configure("TButton", padding=(0, 5, 0, 5), 
            font='serif 10')
        
        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)

#Buttons and stuff

        frame1 = Frame(self)
        frame1.grid(row=0,columnspan=4)
        self.lbl1 = Label(frame1, text="")
        self.lbl1.pack(side=LEFT, padx=5, pady=5)

        frame2 = Frame(self)
        frame2.grid(row=1,columnspan=4)
        lbl2 = Label(frame2, text="Divisions", width=6)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        self.entry1=Entry(frame2) 
        self.entry1.pack(fill=X, padx=5, expand=True)        
        
        frame3 = Frame(self)
        frame3.grid(row=2,columnspan=4)
        self.lbl3 = Label(frame3, text="Divisions =%r"%self.div_num)
        self.lbl3.pack(side=LEFT, expand=True)
    

        set_point = Button(self, text="Set divisions", command=self.get_div)
        set_point.grid(row=3, column=0)

        show_ctrl_points = Button(
                                  self, text="Control points",
                                  command=self.toggle_ctrl
                                  )
        show_ctrl_points.grid(row=3, column=2)
               
        div = Button(self, text="Divide", command=self.toggle_divide)
        div.grid(row = 5, column = 0,columnspan=2)

        strart = Button(self, text="Strings", command=self.toggle_string)
        strart.grid(row = 5, column = 2,columnspan=2)

        plotpar = Button(self, text="Parabola", command=self.toggle_para)
        plotpar.grid(row = 6, column = 0,columnspan=2)

        grass = Button(self, text="Grass", command=self.toggle_grass)
        grass.grid(row = 6, column = 2,columnspan=2)

        self.w = Canvas(self, width=200, height=900)
        self.w.grid(row=7, columnspan=4)
        self.after(70,self.draw)
        self.pack() 

#Draw initial control points for user


        

#Various toggles to show/remove parts of the model

    def toggle_ctrl(self):
        self.ctrl_toggle=(self.ctrl_toggle+1)%2
   
    def toggle_para(self):
        self.para_toggle=(self.para_toggle+1)%2

    def toggle_grass(self):
        self.grass_toggle=(self.grass_toggle+1)%2
    
    def toggle_string(self):
        self.string_toggle=(self.string_toggle+1)%2  
   
    def toggle_divide(self):
        self.divide_toggle=(self.divide_toggle+1)%2  

#Main function that draws the grass then reinitialises the after method on the Frame

    def draw(self):  
            newx=self.ctrlpt1x+50*math.sin(3.14*0.5*(self.start_time-time.time()))
            self.ctrlpt1=[newx,55]
            self.w.delete("all")
            if self.grass_toggle==1:       
                self.grass_polygon()
                self.w.create_polygon(0,235,400,235,400,400,0,400,fill='#A74A2A')
            if self.divide_toggle==1:
                self.draw_divide()           
            if self.string_toggle==1:
                self.string_art()
            if self.para_toggle==1:
                self.plot_para()
            if self.ctrl_toggle==1:
                self.w.create_oval(
                                   self.ctrlpt1[0] - 2, self.ctrlpt1[1] - 2, 
                                   self.ctrlpt1[0] + 2, self.ctrlpt1[1] + 2,
                                   fill="black"
                                  )
                self.w.create_oval(
                                   self.ctrlpt2[0] - 2, self.ctrlpt2[1] - 2, 
                                   self.ctrlpt2[0] + 2, self.ctrlpt2[1] + 2,
                                   fill="black"
                                  )
                self.w.create_oval(
                                   self.ctrlpt3[0] - 2, self.ctrlpt3[1] - 2, 
                                   self.ctrlpt3[0] + 2, self.ctrlpt3[1] + 2,
                                   fill="black"
                                  )
            self.after(70,self.draw)
  
#Gets the number of divisions from the label and then sets it          
    
    def get_div(self):
        try:
            self.div_num=int(self.entry1.get())
            self.lbl1.config(text="Division number set")
            self.lbl3.config(text="Divisions =%r"%self.div_num)
        except ValueError:
            self.lbl1.config(text="Incorrect entry type")

#Draws the positions of each division

    def draw_divide(self):
        list1=self.divide_line(self.ctrlpt1,self.ctrlpt2)
        for n in range(len(list1)):  
            self.w.create_oval(
                               list1[n][0] - 2, list1[n][1] - 2, 
                               list1[n][0] + 2,list1[n][1] + 2,fill="black"
                              )
        list2=self.divide_line(self.ctrlpt2,self.ctrlpt3)  
        for n in range(len(list2)):  
            self.w.create_oval(
                               list2[n][0] - 2, list2[n][1] - 2, 
                               list2[n][0] + 2,list2[n][1] + 2,fill="black"
                              )  
#Draws the polygons for each section of the grass (Clean up function)
 
    def grass_polygon(self):
        lst=self.intersect_list()
        pluslst2=[0]*(2*(len(lst)-1)-1)
        minuslst2=[0]*(2*(len(lst)-1)-1)
        pluslst2[0:1]=lst[0][1],lst[0][0]
        minuslst2[0:1]=lst[0]
        try:
            for n in range(1,len(lst)-1):
                width=2+10*(1-abs(1-2*(n+2)/float(len(lst))))
                m1 = self.slope(lst[n],lst[n+1]) 
                m = -1/m1
                dx = math.sqrt(width**2/(1+m**2))
                dy = math.sqrt(width**2/(1+1/m**2))
                minuslst2[2*n]=math.ceil(lst[n][0]-dx)
                minuslst2[2*n+1]=math.ceil(lst[n][1]-dy)
                pluslst2[2*n+1]=math.ceil(lst[n][0]+dx)
                pluslst2[2*n]=math.ceil(lst[n][1]+dy)
            pluslst2.reverse()    
            self.w.create_polygon(minuslst2,pluslst2,fill='green')
        except TypeError:
            self.lbl1.config(text="Slope error")
            

#Standard slope function (Convert to matrix form maybe? also fix the perp line case)   
    
    def slope(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        if abs(x2-x1) > 0.00001:
            m1=(y2+y1)/float(x2-x1)
            return m1
        else:
            return 'slope_error'
#Gets all the intersection points needed for the parabola

    def intersect_list(self):
        list1 = self.divide_line(self.ctrlpt1,self.ctrlpt2)
        list2 = self.divide_line(self.ctrlpt2,self.ctrlpt3)
        zplst = zip(list1[0:len(list1)-1],list2[1:len(list1)])
        para_list=[0]*(len(zplst)+1)
        para_list[0]=self.ctrlpt1
        para_list[len(zplst)]=self.ctrlpt3
        for n in range(len(zplst)-1):
            para_list[n+1]=self.intersection(
                                        zplst[n][0],zplst[n][1],
                                        zplst[n+1][0],zplst[n+1][1]
                                        )
        return para_list
  
#Draws the parabola points
          
    def plot_para(self):
        plotlist=self.intersect_list()
        for n in range(len(plotlist)):  
            self.w.create_oval(
                                plotlist[n][0]-2, plotlist[n][1]-2, 
                                plotlist[n][0]+2, plotlist[n][1]+2,fill="black"
                                  )

#Draws the strings
                    
    def string_art(self):
        list1 = self.divide_line(self.ctrlpt1,self.ctrlpt2)
        list2 = self.divide_line(self.ctrlpt2,self.ctrlpt3)
        zplst = zip(list1[0:len(list1)-1],list2[1:len(list1)])
        for n in range(len(zplst)):  
            self.w.create_line(
                                zplst[n][0][0], zplst[n][0][1], 
                                zplst[n][1][0], zplst[n][1][1],fill="black"
                                  )

#Given four points which define two lines it finds the intersection point of the two lines. (Use matrix form)

    def intersection(self,point1,point2,point3,point4):
        x1,y1 = point1
        x2,y2 = point2
        x3,y3 = point3
        x4,y4 = point4
        if abs(x2-x1) > 0.00001 and abs(x4-x3) > 0.00001:
            m1=(y2-y1)/float(x2-x1)
            c1=y1-float(m1)*x1
            m2=(y4-y3)/float(x4-x3)
            c2=y3-float(m2)*x3
            xint = (c2-c1)/float((m1-m2))
            yint = m1*((c2-c1)/float((m1-m2)))+c1
        else:
            if abs(x2-x1) < 0.00001:
                xint=x2
                yint=(y4-y3)*x2/float(x4-x3)+y3-float((y4-y3)/float(x4-x3))*x3
            else:
                xint=x3
            
        return [xint,yint]

#Finds the points which divide a line defined by two points in to div_num sections

    def divide_line(self,point1,point2):
        x1,y1 = point1
        x2,y2 = point2
        list = [0]*(self.div_num+1)
        for n in range(self.div_num+1):
            list[n]=[x1+(n)*(x2-x1)/float(self.div_num),y1+(n)*(y2-y1)/float(self.div_num)]
        return list     
#Clears the canvas       

    def clear_canvas(self):
        self.w.delete("all") 
Ejemplo n.º 38
0
class Application(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        # size
        self.width = 250
        self.height = 120

        # screen size
        self.sw = self.parent.winfo_screenwidth()
        self.sh = self.parent.winfo_screenheight()

        # create a Motor object
        self.motor = Motor()

        # init UI and centering in the screen
        self.initUI()
        self.centering()

    def initUI(self):
        self.parent.title("RPI Motors")

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        # configure grid
        self.columnconfigure(0, pad=5)
        self.columnconfigure(1, pad=5)
        self.columnconfigure(2, pad=5)

        self.rowconfigure(0, pad=5)
        self.rowconfigure(1, pad=5)
        self.rowconfigure(2, pad=5)

        # label
        self.port_lbl = Label(self, text="Port")
        self.port_lbl.grid(row=0, column=0, pady=4, padx=5, sticky=W + E)

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

        # control buttons
        self.cls = Button(self,
                          text="Turn Left",
                          command=self.motor.turn_left())
        self.cls.grid(row=1, column=0, sticky=E + W)
        self.bck = Button(self, text="Stop", command=self.motor.stop_mov())
        self.bck.grid(row=1, column=1, sticky=E + W)
        self.lbl = Button(self,
                          text="Turn Right",
                          command=self.motor.turn_right())
        self.lbl.grid(row=1, column=2, sticky=E + W)

        # exit button
        self.clo = Button(self, text="Exit", command=self.quit)
        self.clo.grid(row=2, columnspan=4, sticky=E + W)

        # draw
        self.pack()

    def centering(self):
        self.posX = (self.sw - self.width) / 2
        self.posY = (self.sh - self.height) / 2

        self.parent.geometry('%dx%d+%d+%d' %
                             (self.width, self.height, self.posX, self.posY))

    def set_new_port():
        self.motor.set_port(self.entry.get())
Ejemplo n.º 39
0
class topFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setUI()

    def setUI(self):
        self.parent.title("ServoGui")
        self.pack(fill=BOTH, expand=1)
        self.comPort = StringVar(self)
        self.laststrm = StringVar(self)

        settingFrame = Frame(self, borderwidth=1, relief=RAISED)
        settingFrame.pack(fill=Y, side=LEFT)

        Label(settingFrame, width=50, text="Port Settings", bg="green", fg="black").pack(fill=X)

        ports = self.getComPorts()
        w = apply(OptionMenu, (settingFrame, self.comPort) + tuple(ports))
        w.pack(fill=X)

        BaudFrame = Frame(settingFrame)
        BaudFrame.pack(fill=X)
        Label(BaudFrame, text="Baud:").pack(side=LEFT)
        self.baud_entry = Entry(BaudFrame,
                                width=15,
                                validate="focusout",
                                validatecommand=self.baudValidate)
        self.baud_entry.pack(side=LEFT, expand = True)
        self.baud_entry.insert(0,"115200")

        Button(settingFrame, text="Open Port", command=self.openPort). pack(fill=X)
        Button(settingFrame, text="Close Port", command=self.closePort). pack(fill=X)

        StreamFrame = Frame(settingFrame)
        StreamFrame.pack()
        self.btnStartStream = Button(StreamFrame,
                                text="Start Stream",
                                command=self.startStream,
                                state=DISABLED)
        self.btnStopStream = Button(StreamFrame,
                                text="Stop Stream",
                                command=self.stopStream,
                                state=DISABLED)
        self.btnGetConfig = Button(StreamFrame,
                                text="Get Config",
                                command=self.getConfig,
                                state=DISABLED)
        self.btnStartStream.pack(side=LEFT)
        self.btnStopStream.pack(side=LEFT)
        self.btnGetConfig.pack(side=LEFT)
        self.queue = Queue.Queue()
        self.writequeue = Queue.Queue()

        Label(settingFrame, width=50, text="Drive Settings", bg="green", fg="black").pack(fill=X)
        DriveSettingsFrame = Frame(settingFrame, relief=SUNKEN)
        DriveSettingsFrame.pack(fill=X)

        driveSettingsFrames = []
        self.driveSettingsEntries = []
        for drivesetting in drivesettings:
            driveSettingsFrames.append(Frame(DriveSettingsFrame))
            driveSettingsFrames[-1].pack(fill=X)
            Label(driveSettingsFrames[-1], text=drivesetting).pack(side=LEFT)
            self.driveSettingsEntries.append(Entry(driveSettingsFrames[-1]))
            self.driveSettingsEntries[-1].pack(side=RIGHT)
        Button(DriveSettingsFrame, text="Send to drive", command=self.sendConfig).pack(fill=X)
        Button(DriveSettingsFrame, text="Save config in drive", command=self.saveConfig).pack(fill=X)

        Label(settingFrame, width=50, textvariable=self.laststrm, bg="green", fg="black").pack(fill=X)

        #MatplotLib stuff

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(311)
        self.a.set_title("Requested and actual position")
        self.b = f.add_subplot(312)
        self.b.set_title("Error")
        self.c = f.add_subplot(313)
        self.c.set_title("Current meas ADC value")

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)

        toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.hall=[]
        self.encoder_count=[]
        self.pos_error=[]
        self.requested_position=[]
        self.requested_delta=[]
        self.adc_value=[]
        self.pid_output=[]
        self.a.set_autoscaley_on(True)


        self.encoder_line, = self.a.plot([],[])
        self.error_line, = self.b.plot([],[])
        self.reqpos_line, = self.a.plot([],[])
        self.ADC_line, = self.c.plot([],[])
        self.updateCanvas()


    def baudValidate(self):
        sVal = self.baud_entry.get()
        try:
            iVal = int(sVal)
        except ValueError:
            print "Illegal baud value"
            self.baud_entry.delete(0, END)
            self.baud_entry.insert(0, "115200")
            return False
        return True

    def openPort(self):
        try:
            self.ser = serial.Serial(self.comPort.get(), int(self.baud_entry.get()), timeout=0)
        except serial.SerialException:
            print "unable to open"
            return
        self.btnStartStream['state'] = NORMAL
        self.btnStopStream['state'] = NORMAL
        self.btnGetConfig['state'] = NORMAL

        self.thread = SerialThread(self.queue, self.writequeue, self.ser)
        self.thread.daemon = True
        self.thread.start()
        self.process_serial()

    def closePort(self):
        self.thread.stop()
        self.thread.join()
        self.ser.closePort()

        self.btnStartStream['state'] = DISABLED
        self.btnStopStream['state'] = DISABLED
        self.btnGetConfig['state'] = DISABLED

    def process_serial(self):
        while self.queue.qsize():
            try:
                line = self.queue.get()
                self.handleLine(line)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

    def startStream(self):
        self.writequeue.put(b"STREAM START \r")

    def stopStream(self):
        self.writequeue.put(b"STREAM DIE \r")
    def getConfig(self):
        self.writequeue.put(b"GET\r")
    def saveConfig(self):
        self.writequeue.put(b"SAVE \r")
    def sendConfig(self):
        for setting in drivesettings:
            dataToSend = b"SET "+setting+" "+self.driveSettingsEntries[drivesettings.index(setting)].get()+"\r"
            print dataToSend
            self.writequeue.put(dataToSend)
            time.sleep(0.2)


    def getComPorts(self):
        ports = serial.tools.list_ports.comports()
        portNames = []
        for port in ports:
            portNames.append(port[0])
        return portNames
    def handleLine(self,line):
        line = line.replace(" ", "")
        line = line.replace("/n", "")
        line = line.replace("/r", "")
        parts = line.split(":")
        if len(parts)>1:
            if parts[0] == "STR":
                self.handleStr(parts[1])
                return
            if parts[0] in drivesettings:
                self.driveSettingsEntries[drivesettings.index(parts[0])].delete(0, END)
                self.driveSettingsEntries[drivesettings.index(parts[0])].insert(0, parts[1])
    def handleStr(self,strm):
        #format of the stream line: STR:hall;count;requestedPosition;requestedDelta;error
        parts = strm.split(";")

        self.laststrm.set(strm)
        self.hall.append(int(parts[0]))
        if len(self.hall) > 5000:
            self.hall.pop(0)

        self.encoder_count.append(parts[1])
        if len(self.encoder_count) > 5000:
            self.encoder_count.pop(0)

        self.requested_position.append(parts[2])
        if len(self.requested_position) > 5000:
            self.requested_position.pop(0)

        self.requested_delta.append(parts[3])
        if len(self.requested_delta) > 5000:
            self.requested_delta.pop(0)

        self.pos_error.append(parts[4])
        if len(self.pos_error) > 5000:
            self.pos_error.pop(0)

        self.adc_value.append(parts[5])
        if len(self.adc_value) > 5000:
            self.adc_value.pop(0)

        self.pid_output.append(parts[5])
        if len(self.pid_output) > 5000:
            self.pid_output.pop(0)

    def updateCanvas(self):

        self.encoder_line.set_xdata(range(len(self.encoder_count)))
        self.encoder_line.set_ydata(self.encoder_count)
        self.error_line.set_xdata(range(len(self.pos_error)))
        self.error_line.set_ydata(self.pos_error)
        self.reqpos_line.set_xdata(range(len(self.requested_position)))
        self.reqpos_line.set_ydata(self.requested_position)
        self.ADC_line.set_xdata(range(len(self.adc_value)))
        self.ADC_line.set_ydata(self.adc_value)
        self.a.relim()
        self.a.autoscale_view()
        self.b.relim()
        self.b.autoscale_view()
        self.c.relim()
        self.c.autoscale_view()
        self.canvas.draw()
        self.after(100, self.updateCanvas)
Ejemplo n.º 40
0
class ChooseType(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        ChooseType.socket = None
        ChooseType.create_player = None
        
        self.plx_name = "PLAYER"
        ChooseType.plx_type = "SPECTATOR"
        ChooseType.start_game = None
        label_1 = Label(self, text="Create character", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label_2 = Label(self, text="Name: ")
        self.entry_1 = Entry(self)
        self.entry_1.insert(0, 'Player_')

        label_3 = Label(self, text="Join as: ")
        button1 = Button(self, text="FROG", command=self.callback_frog)
        button2 = Button(self, text="FLY", command=self.callback_fly)
        button3 = Button(self, text="SPECTATOR", command=self.callback_spec)
        ChooseType.button4 = Button(self, text="Back", command=lambda: controller.show_frame("StartPage"))

        label_1.pack(side="top", fill="x", pady=10)
        label_2.pack()       
        self.entry_1.pack()
        label_3.pack()
        button1.pack()
        button2.pack()
        button3.pack()
        ChooseType.button4.pack(pady=20)
    
    def check_name(self,s):
        temp = False
        try:
            s.decode('ascii')
        except UnicodeEncodeError:
            print "it was not a ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", "Invalid player name")
        except UnicodeDecodeError:
            print "it was not a ascii-encoded unicode string"
            tkMessageBox.showwarning("Error message", "Invalid player name")
        else:
            if len(s) < 10 and len(s) >= 1:
                temp = True
            else:
                tkMessageBox.showwarning("Error message", "String lenght must be 1-10 characters")
        return temp
    
    # this frame works on callbacks so each button is processed separately
    # 1. get name
    # 2. check if the name is valid
    # 3. set player type
    # 4. **create server localy if the user comes from create server frame
    # 5. add player to the game (parameters: name, type)
    def callback_frog(self):
        self.plx_name = self.entry_1.get()
        if self.check_name(self.plx_name):
            ChooseType.plx_type = "FROG"
            self.create_server(CreateServer.plx_name,CreateServer.game_dim)
            self.callback_add_player()

    def callback_fly(self):
        self.plx_name = self.entry_1.get()
        if self.check_name(self.plx_name):
            ChooseType.plx_type = "FLY"
            self.create_server(CreateServer.plx_name,CreateServer.game_dim)
            self.callback_add_player()

    def callback_spec(self):
        self.plx_name = self.entry_1.get()
        if self.check_name(self.plx_name):
            ChooseType.plx_type = "SPECTATOR"
            self.create_server(CreateServer.plx_name,CreateServer.game_dim)
            self.callback_add_player()
        
    
    # join the game
    def callback_add_player(self):
        set_shut_down_level(1)
        data = "JOIN;"+ChooseType.plx_type
        if global_state==1:
            # directly (locally) access the game engine
            ChooseType.create_player = CreateServer.local_world.add_player(self.plx_name)
            CLIENTS.append((ChooseType.create_player, 'Local Player'))
            CreateServer.local_world.set_player_attr(ChooseType.create_player, 1, 'character', data)
            ChooseType.start_game = True
        else:
            GameWindow.vSer.set(globvar[0]) 
            host,_ = globvar[1]
            try:
                ChooseType.socket = s = socket.socket(AF_INET,SOCK_STREAM)
                s.connect((host,QUAD_AXE))
                # ping-pong communication:  
                # 1. client: ADD_ME;Player1 -> server: ADDED -> client
                # 2. client: JOIN;FROG -> server
                data2 = 'ADD_ME;'+self.plx_name
                self.socket.send(data2.encode())
                buf = ChooseType.socket.recv(100)
                message = buf.decode('utf-8')
                if message == "ADDED":
                    print 'Added player!'
                    ChooseType.start_game = True
                    ChooseType.socket.send(data.encode())
            except Exception as e:
                print e
                ChooseType.start_game = False
                print 'Cannot connect to server!'
        self.controller.show_frame("GameWindow")
    
    # this is the function that initiates: engine, server and broadcast
    def create_server(self,s_name,field_xy):
        if global_state == 0 or shut_down_level != 0:
            return
        ChooseType.button4.config(state="disabled")
        # addition game field size check
        GameWindow.vSer.set(s_name)
        m_split=field_xy.split('X')
        try:
            x_size = int(m_split[0])
        except:
            x_size = 10  
        try:
            y_size = int(m_split[1])
        except:
            y_size = 10                    
        if (x_size < 2 or x_size > MAX_GF_SIZE):
            print 'The gamefield\'s dimensions size should be between 3 and '+str(MAX_GF_SIZE)+' !'
            x_size = 10             
        if (y_size < 2 or y_size > MAX_GF_SIZE):
            print 'The gamefield\'s dimensions size should be between 3 and '+str(MAX_GF_SIZE)+' !'
            y_size = 10
        # Start the world
        CreateServer.local_world = engine.World(x_size,y_size)
        et = engine.engine_thread(ENGINE_SLEEP, CreateServer.local_world)
        et.start()
        THREADS.append(et)       
        # Initialize the server
        server_sock = server.init_server()
        set_globvar(server_sock.getsockname())
        st = server.server_thread(s_name, server_sock, CreateServer.local_world)        
        st.start() # Start the server thread
        THREADS.append(st)     
        # Initialize the broadcaster
        bc_sock = server.init_broadcaster()
        # Start broadcasting thread
        bt = server.announce_bc_thread(bc_sock, BROADCASTING_PORT, s_name, CreateServer.local_world)
        bt.start()
        THREADS.append(bt)
Ejemplo n.º 41
0
class SelectPaths(MyFrame):
    def __init__(self, topframe=None):

        MyFrame.__init__(self, topframe=topframe)

        style = Style()
        style.theme_use('clam')

        self.patient_foler_path = ""
        self.patients = []
        self.set_title('Brain segmentation GUI')
        self.add_ui_components()

    def add_ui_components(self):

        # Creating the frames.
        self.sub_frame1 = Frame(self)
        self.sub_frame1.grid(column=0, row=0)

        sub_frame2 = Frame(self)
        sub_frame2.grid(column=0, row=1)

        sub_frame3 = Frame(self)
        sub_frame3.grid(column=0, row=2)

        sub_frame21 = Frame(sub_frame2)
        sub_frame21.grid(column=0, row=0)

        sub_frame22 = Frame(sub_frame2)
        sub_frame22.grid(padx=20, column=1, row=0)

        sub_frame221 = Frame(sub_frame22)
        sub_frame221.grid(row=1, column=0)

        # Creating the top-menu buttons.
        self.visualise_button = Button(self.sub_frame1,
                                       text="Visualise",
                                       command=self.start_visualisation)
        self.visualise_button.grid(row=0, column=1)

        self.help_button = Button(self.sub_frame1,
                                  text="Help",
                                  command=self.open_help)
        self.help_button.grid(row=0, column=2)

        # Creating the select modality path.
        self.modality_label = Label(sub_frame21,
                                    text="Path to patient folders",
                                    relief=FLAT)
        self.modality_label.grid(row=1, column=1)
        self.modality_path_entry = Entry(sub_frame21)
        self.modality_path_entry.grid(row=2, column=1)
        #self.modality_path_entry.set(self.patient_folder_path)

        self.modality_path_button = Button(
            sub_frame21,
            text="Choose",
            command=self.choose_directory_and_import)
        self.modality_path_button.grid(row=2, column=2)

        # Creating the patients listbox.
        self.label_patients = Label(sub_frame22, text="Patients")
        self.label_patients.grid(row=0, column=0)

        self.listbox_patients = Listbox(sub_frame221,
                                        selectmode='multiple',
                                        width=50,
                                        height=10)

        self.listbox_patients.pack(side=LEFT, fill=Y)
        #self.listbox_patients.grid(row=1, column=0)
        self.listbox_patients.bind("<Button-1>", self.listbox_changed)

        self.scrollbar = Scrollbar(sub_frame221)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        # attach listbox to scrollbar
        self.listbox_patients.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox_patients.yview)
        # Creating the status console.
        self.status_text = Text(sub_frame3, height=5)
        self.status_text.grid(column=0, row=0)
        self.status_text.tag_configure('title',
                                       justify='center',
                                       font="Arial 10 bold")
        self.status_text.tag_configure('entry', justify='left', font="Arial 9")
        self.status_text.insert(END, 'Status Console', 'title')
        self.status_text_entry_number = 1
        self.status_text.configure(state='disabled')

# ***** EVENTS - START********************************

    def start_visualisation(self):
        """ Launch visualisation module. 
        Linked to self.visualise_button (Button). """

        patient_path = os.path.join(self.patient_folder_path,
                                    'processed_' + self.patients[0])

        segmentation_path = os.path.join(
            patient_path, SEGM_PREFIX + '_' + self.patients[0] + '.nii.gz')

        supervoxel_path = os.path.join(
            patient_path,
            SUPERVOXEL_PREFIX + '_' + self.patients[0] + '.nii.gz')

        # check if the supervoxels and the segmentation exist
        if not os.path.exists(supervoxel_path):
            supervoxel_path = None
        if not os.path.exists(segmentation_path):
            segmentation_path = None

        mod_paths = []
        for mod in MODALITY_PREFIXES:
            mod_paths.append(\
                    os.path.join(patient_path,
                                 mod+'_'+self.patients[0]+'.nii.gz'))

        vis = vv.VisualVolumes(image_paths=mod_paths,
                               segm_path=segmentation_path,
                               supervoxel_id_path=supervoxel_path,
                               topframe=self.master)
        vis.tkraise()

    def listbox_changed(self, event):
        """ Add a patient upon selection in the listbox. 
        Linked to self.listbox_patients (Listbox). """

        indices = list(self.listbox_patients.curselection())
        selected_idx = self.listbox_patients.nearest(event.y)

        if selected_idx == -1:
            return

        # remove or add a patient index
        if selected_idx not in indices:
            indices.append(selected_idx)
        else:
            indices.remove(selected_idx)

        # set self.patients based on the new patient indices and enable visualisation if only one is selected.
        self.patients = []
        for idx in indices:
            self.patients.append(self.listbox_patients.get(idx).split(' ')[0])
        if len(self.patients) == 1:
            self.visualise_button['state'] = 'enabled'
        else:
            self.visualise_button['state'] = 'disabled'

    def choose_directory_and_import(self):
        """ Allow the user to select an import path. 
	    Linked to self.modality_path_button (Button), 
	    and sets self.modality_path_entry (Entry). """

        initialdir = DATA_PATH
        msg = 'Select directory containing patients'
        path = askdirectory(title=msg, initialdir=initialdir)
        # update the text box.
        self.modality_path_entry.delete(0, END)
        self.modality_path_entry.insert(0, str(path))

        # Adding the modality paths after the folder is selected.
        self.patient_folder_path = self.modality_path_entry.get()
        if os.path.exists(self.patient_folder_path):

            patients_validation = os.listdir(self.patient_folder_path)

            # Checking if the patient has the right modalities and importing the patient.
            for i, patient in enumerate(patients_validation):

                # Checking if the patient was already processed.
                if patient.startswith('processed_') or os.path.exists(
                        os.path.join(self.patient_folder_path,
                                     'processed_' + patient)):
                    print("The files of the patient " + patient +
                          " are already copied")
                    continue

                # If everything is fine, then it continues to makign folders and copying files
                # Copying the files into the new folder.
                valid = self._convert_and_copy_files(patient)
                if not valid:
                    patients_validation[i] = None

            # We make a list of patients with only ids for the listbox.
            valid_patients = [p for p in patients_validation if p is not None]
            self.list_existing_patients(valid_patients)

    def _convert_and_copy_files(self, patient):
        """ Check if all valid files exist for this patient and return
        True if so. """

        # Getting the list of modalities for every patient.
        patient_path = os.path.join(self.patient_folder_path, patient)
        modalities = os.listdir(patient_path)

        # Look for paths
        valid_paths = {}
        prefices = [SEGM_PREFIX, SUPERVOXEL_PREFIX] + MODALITY_PREFIXES
        for prefix in prefices:
            candidates = [modality \
                          for modality in modalities \
                          if modality.startswith(prefix+'.')]
            if len(candidates) != 1:
                err = '%s file not identified. Look for ambiguities in %s.' \
                        % (prefix, patient_path)
                print(err)
                return False
            modality = candidates[0]

            if not any([
                    modality.endswith(ext)
                    for ext in ['.mha', '.nii', '.nii.gz']
            ]):
                err = "Image format not recognized: %s. In %s" \
                            % (modality, patient_path)
                print(err)
                return False

            valid_paths[prefix] = modality

        # Creating a processed patient folder.
        os.mkdir(os.path.join(self.patient_folder_path,
                              'processed_' + patient))
        for prefix, basename in valid_paths.iteritems():
            shutil.copyfile(
                os.path.join(self.patient_folder_path, patient, basename),
                os.path.join(self.patient_folder_path, 'processed_' + patient,
                             prefix + '_' + patient + '.nii.gz'))
        return True

    def open_help(self):

        self.help_window = help_window.HelpWindow()
        self.help_window.tkraise()


# ***** EVENTS - END***************************

    def list_existing_patients(self, patients=None):
        print("Importing existing patients")
        # We make a list of patients with only ids for the listbox.

        if patients is None:
            patients = os.listdir(self.patient_folder_path)
        self.patients = []
        for patient in patients:
            if not patient.startswith('processed_'):
                self.patients.append(patient)
        self.patients.sort()
        self.populate_patient_listbox(self.patients)

        if self.listbox_patients.size() > 0:
            self.listbox_patients.selection_set(0)

        self.status_text.configure(state='normal')
        self.status_text.insert(
            END, '\n' + str(self.status_text_entry_number) +
            '- Patients are imported.', 'entry')
        self.status_text_entry_number += 1
        self.status_text.insert(
            END, '\n' + str(self.status_text_entry_number) +
            '- Please select a patient to proceed', 'entry')
        self.status_text_entry_number += 1
        self.status_text.configure(state='disabled')

    def populate_patient_listbox(self, patients):

        self.listbox_patients.delete(0, END)
        for patient in patients:
            patient_path = os.path.join(self.patient_folder_path,
                                        'processed_' + patient)

            #check if a given patient has a label
            if os.path.exists(
                    os.path.join(
                        patient_path, 'corrected_' + SEGM_PREFIX + '_' +
                        patient + '.nii.gz')):
                patient = patient + ' - segmentation corrected'
            self.listbox_patients.insert(END, patient)
Ejemplo n.º 42
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.date = (time.strftime("%m_%d_%Y"))
        self.initUI()


    def initUI(self):
        self.parent.title("Experiment")
        self.pack(fill=BOTH, expand=True)

        self.frame1 = Frame(self)
        self.frame1.pack(fill=X)

        self.lbl1 = Label(self.frame1, text="Participant", width=10)
        self.lbl1.pack(side=LEFT, padx=5, pady=5)

        self.entry1 = Entry(self.frame1)
        self.entry1.pack(fill=X, padx=5, expand=True)

        self.frame2 = Frame(self)
        self.frame2.pack(fill=X)

        self.lbl2 = Label(self.frame2, text="Date", width=10)
        self.lbl2.pack(side=LEFT, padx=5, pady=5)

        self.entry2 = Entry(self.frame2)
        self.entry2.insert(0, self.date)
        self.entry2.state()
        self.entry2.pack(fill=X, padx=5, expand=True)

        self.frame3 = Frame(self)
        self.frame3.pack(fill=X)

        self.lbl3 = Label(self.frame3, text="COM Port", width=10)
        self.lbl3.pack(side=LEFT, padx=5, pady=5)

        self.entry3 = Entry(self.frame3)
        self.entry3.pack(fill=X, padx=5, expand=True)

        self.frame4 = Frame(self)
        self.frame4.pack(fill=X)

        self.accept = Button(self.frame4, text="Ok", command=self.makeVariables)
        self.accept.pack(fill=X, padx=5)


    def makeVariables(self):
        self.participant = self.entry1.get()
        self.port = self.entry3.get()
        self.verify()
        Frame.quit(self)


    def verify(self):
        mbox.showwarning('Check', 'Have you set the markers on Emotiv Toolbox?')


    def getName(self):
        return self.participant


    def getDate(self):
        return self.date

    def get_port(self):
        return self.port
Ejemplo n.º 43
0
class GripperDemo(Frame):
    def __init__(self, parent1):
        Frame.__init__(self, parent1)
        self.parent = parent1
        self.initUI()

    def initUI(self):
        self.parent.title("Gripper Demo")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        #scale1 - Gripper Pos
        ScaleGripperPos = Scale(self,
                                from_=0,
                                to=100,
                                orient=HORIZONTAL,
                                length=300,
                                resolution=1,
                                command=self.onScaleGripperPos)
        ScaleGripperPos.grid(row=1, column=2)

        self.label = Label(self, text="Gripper Pos ")
        self.label.grid(row=1, column=1)

        self.GripperPos = IntVar()
        self.labelScaleGripperPos = Label(self,
                                          text=0,
                                          textvariable=self.GripperPos)
        self.labelScaleGripperPos.grid(row=1, column=3)

        #scale2 - X ROTATION
        scaleRotX = Scale(self,
                          from_=0,
                          to=650,
                          orient=HORIZONTAL,
                          length=300,
                          resolution=1,
                          command=self.onScaleXAxisRot)
        scaleRotX.grid(row=2, column=2)
        scaleRotX.set(450)

        self.label = Label(self, text="X Axis Rotation ")
        self.label.grid(row=2, column=1)

        self.labelRotX = Label(self)
        self.labelRotX.grid(row=2, column=3)

        #Entry1 - Force
        self.entryForce = Entry(self)
        self.entryForce.grid(row=3, column=2)
        self.entryForce.insert(0, "50")  #35=700

        #self.forceString = StringVar()
        #self.forceString.set(1023);
        self.labelForce = Label(self)
        self.labelForce.grid(row=3, column=3)
        #self.entryForce.insert(1023,self.force.get())
        #self.entry1.delete(0,END) #delete entry text
        #entry.bind("<Return>", callback) #calls callback function after hit "enter"

        self.label = Label(self, text="Current (A)")
        self.label.grid(row=6, column=1)
        self.labelCurrent = Label(self)
        self.labelCurrent.grid(row=6, column=3)

        #Entry2 - Speed
        self.entrySpeed = Entry(self)
        self.entrySpeed.grid(row=4, column=2)
        self.entrySpeed.insert(0, "4000")
        self.labelSpeed = Label(self)
        self.labelSpeed.grid(row=4, column=3)

        #Entry2 - Active Distance
        self.entryDistance = Entry(self)
        self.entryDistance.grid(row=5, column=2)

        #Entry3 - Send Command
        self.entrySendCommand = Entry(self)
        self.entrySendCommand.grid(row=8, column=2)

        self.activeDistance = IntVar()
        self.activeDistance.set(15)
        self.labelActiveDistance = Label(self)
        self.labelActiveDistance.grid(row=5, column=3)
        self.entryDistance.insert(0, self.activeDistance.get())

        #Button1 - close
        self.button1 = Button(self, text="close", command=self.gripperClose)
        self.button1.grid(row=7, column=1)
        #Button2 - open
        self.button2 = Button(self, text="open", command=self.gripperOpen)
        self.button2.grid(row=7, column=2)
        #Button3 - home
        self.button3 = Button(self,
                              text="home",
                              command=self.gripperHomeRoutine)
        self.button3.grid(row=7, column=3)
        #Button4 - send command
        self.button4 = Button(self, text="send", command=self.sendCommand)
        self.button4.grid(row=8, column=3)
        #Button3
        self.buttonForce = Button(self,
                                  text="forceSetPoint (mg)",
                                  command=self.gripperSetForce)
        self.buttonForce.grid(row=3, column=1)
        #Button4
        self.buttonSpeed = Button(self,
                                  text="speedSetPoint (mseg/close)",
                                  command=self.gripperSetSpeed)
        #80degree each finger = to move 40 degree to close
        self.buttonSpeed.grid(row=4, column=1)
        #Button5
        self.buttonDistance = Button(self,
                                     text="distanceSetPoint (Cm)",
                                     command=self.gripperSetDistance)
        self.buttonDistance.grid(row=5, column=1)

    def gripperOpen(self):
        message = "open"
        rospy.loginfo(message)
        pub.publish(message)

    def gripperClose(self):
        message = "close_101"  #101 is the auto close command
        rospy.loginfo(message)
        pub.publish(message)

    def gripperHomeRoutine(self):
        message = "home"
        rospy.loginfo(message)
        pub.publish(message)

    def sendCommand(self):
        message = self.entrySendCommand.get()
        rospy.loginfo(message)
        pub.publish(message)

    def gripperSetForce(self):
        aux = map(int(self.entryForce.get()), 0, 1200, 0, 1023)
        message = "setForce_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def gripperSetSpeed(self):
        #0.174seg 80graus (6.0V sem carga)
        #4s 80 graus na velocidade minima 50ms
        aux = map(int(self.entrySpeed.get()), 4000, 174, 50, 0)
        if aux < 0:
            aux = 0
        message = "setSpeed_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def gripperSetDistance(self):
        aux = self.entryDistance.get()
        message = "setDistance_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def onScaleGripperPos(self, x):
        aux = int(float(x))
        self.GripperPos.set(aux)
        message = "close_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def onScaleXAxisRot(self, x):
        aux = int(float(x))
        message = "rotate_" + str(aux)
        rospy.loginfo(message)
        pub.publish(message)

    def updateLabels(self):
        aux = map(gripperForce.data, 0, 1023, 0, 1200)
        self.labelForce.config(text=str(aux))
        aux = int(self.entrySpeed.get())
        if aux < 174:
            aux = 174
        self.labelSpeed.config(text=str(aux))
        self.labelActiveDistance.config(text=str(gripperDistance.data))
        self.labelRotX.config(text=str(gripperRotationX.data))
        self.labelCurrent.config(text=str((gripperCurrent.data - 511) * 0.024))
Ejemplo n.º 44
0
class Ex(Frame):
    def __init__(self,parent):
        Frame.__init__(self,parent)
        self.parent = parent
        self.x_before = 400
        self.x_current = 400
        self.y_before = 400
        self.y_current = 400
        self.FirstRun = True
        self.AddVal = ADDVAL
        self.AddVal_X = ADDVAL_X
        self.initUI()
        self.runRandWalk(STEPS)
        self.FirstRun = False
        self.Steps = STEPS
        self.newSteps = STEPS
        self.XStep = XSTEP

    def initUI(self):
        self.parent.title("Random Walk Lines 1")
        self.pack(fill=BOTH,expand=1)
        
        self.style = Style()
        self.style.theme_use("default")
        frame = Frame(self,relief=RAISED,borderwidth=2)
        frame.pack(fill=BOTH,expand=True)

        self.canvas = Canvas(frame)
        self.canvas.create_line(10,400,790,400,dash=(4,2), width=2)
        self.canvas.create_line(400,10,400,790,dash=(4,2), width=2)
        self.canvas.pack(fill=BOTH,expand=1)
        
        self.newWalkButton = Button(self,text="New Walk",
                                   command=self.newWalk)
        self.closeButton   = Button(self,text="Close",
                                    command=self.closeAll)
        self.stepsButton   = Button(self,text="Send Steps",
                                    command=self.sendSteps)
        self.xSizeButton   = Button(self,text="Set X Step",
                                    command=self.xSize)
        self.ySizeButton   = Button(self,text="Set Y Step",
                                    command=self.ySize)
        self.xSizeBox      = Entry(self,width=10)
        self.ySizeBox      = Entry(self,width=10)
        self.stepsBox      = Entry(self,width=10)
        

        # pack the buttons here
        self.closeButton.pack(side=RIGHT,padx=5,pady=5)
        self.newWalkButton.pack(side=RIGHT)
        self.stepsButton.pack(side=RIGHT)
        self.stepsBox.pack(side=RIGHT)
        self.xSizeButton.pack(side=RIGHT)
        self.xSizeBox.pack(side=RIGHT)
        self.ySizeButton.pack(side=RIGHT)
        self.ySizeBox.pack(side=RIGHT)
        
    def ySize(self):
        self.AddVal = int(self.ySizeBox.get())

    def xSize(self):
        self.AddVal_X = int(self.xSizeBox.get())

    def sendSteps(self):
        self.newSteps = int(self.stepsBox.get())
        
    def newWalk(self):
        for x in range(0,self.Steps):
            getTag = "step"+str(x)
            self.canvas.coords(getTag,(0,0,0,0))

        self.Steps = self.newSteps
        self.x_current = 400
        self.x_before  = 400
        self.y_current = 400
        self.y_before  = 400
        self.runRandWalk(self.Steps)
        
    def closeAll(self):
        Frame.quit(self)

    def RandWalk(self,whichStep):
        r = random.randint(0,1)
        rx = random.randint(0,1)
        addval = 0;
        addval_x = 0;
        toTag = "step"+str(whichStep)
        if r == 0:
            addval = (self.AddVal)
        else:
            addval = -(self.AddVal)

        if rx==0:
            addval_x = (self.AddVal_X)
        else:
            addval_x = -(self.AddVal_X)
            
        self.y_current = self.y_before + addval
        self.x_current = self.x_before + addval_x
                
        if self.y_current < 200:
            if self.y_before == 200:
                if self.FirstRun == True:
                    self.canvas.create_line(self.x_before,self.y_before,
                                            self.x_current,self.y_current,
                                            fill = "green", width = 5,
                                            tags=toTag)
                else:
                    self.canvas.coords(toTag,(self.x_before,self.y_before,
                                              self.x_current,self.y_current),)
                    self.canvas.itemconfig(toTag,fill="green")
            else:
                if self.FirstRun == True:
                    self.canvas.create_line(self.x_before,self.y_before,
                                            self.x_current,self.y_current,
                                            fill = "green", width = 5,
                                            tags=toTag)
                else:                    
                    self.canvas.coords(toTag,(self.x_before,self.y_before,
                                             self.x_current,self.y_current))
                    self.canvas.itemconfig(toTag,fill="green")
        else:
            if self.y_before<200:
                if self.FirstRun==True:
                    self.canvas.create_line(self.x_before,self.y_before,
                                            self.x_current,self.y_current,
                                            fill = "green", width = 5,
                                            tags=toTag)
                else:
                    self.canvas.coords(toTag,(self.x_before,self.y_before,
                                             self.x_current,self.y_current))
                    self.canvas.itemconfig(toTag,fill="green")
            else:
                if self.FirstRun==True:
                    self.canvas.create_line(self.x_before,self.y_before,
                                            self.x_current,self.y_current,
                                            fill = "red", width = 5,
                                            tags=toTag)
                else:
                    self.canvas.coords(toTag,(self.x_before,self.y_before,
                                             self.x_current,self.y_current))
                    self.canvas.itemconfig(toTag,fill="red")

                
        self.canvas.pack(fill=BOTH,expand=1)
        self.x_before = self.x_current
        self.y_before = self.y_current
                    

    def runRandWalk(self,steps):
        for x in range(0,steps):
            self.RandWalk(x)
Ejemplo n.º 45
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg = None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)


        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W+N, pady=4, padx=5)


        check_box = {"work": IntVar(),
                     "boost": IntVar()}

        check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self, text="boost games", variable=check_box["boost"])
        check2.grid(row=7, column=1)


        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand= self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

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

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)


        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
Ejemplo n.º 46
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'用户登录')
        self.root.resizable(False, False)
        self.root.geometry('+500+500')
        self.lb_user = Label(self.root, text=u'用户名:', padx=5)
        self.lb_passwd = Label(self.root, text=u'密码:', padx=5)

        self.lb_stime = Label(self.root, text=u'日期: ', padx=5)
        self.lb_sexmp = Label(self.root, text=u'      (输入格式01,02,03)', padx=5)
        self.lb_mytext = Label(self.root, text=u'原因: ', padx=5)
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd.grid(row=1, column=0, sticky=W)
        self.lb_stime.grid(row=2, column=0, sticky=W)
        self.lb_sexmp.grid(row=3, column=0, sticky=W)
        self.lb_mytext.grid(row=4, column=0, sticky=W)

        self.en_user = Entry(self.root, width=20)
        self.en_passwd = Entry(self.root, width=20)
        self.en_stime = Entry(self.root, width=20)
        self.en_reson = Entry(self.root, width=20)
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=1, column=1, columnspan=1)
        self.en_stime.grid(row=2, column=1, columnspan=1)
        self.en_reson.grid(row=4, column=1, columnspan=1, rowspan=3)

        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码',
                               underline=0,
                               variable=self.var)
        self.ckb.grid(row=9, column=0)
        self.bt_print = Button(self.root, text=u'确定', width=20)
        self.bt_print.grid(row=9, column=1, sticky=E, pady=5)
        self.bt_print.config(command=self.print_info)
        self.checkconf()
        self.root.mainloop()

        def validate_func(self, en):
            return False if eval(en).get().strip() != '' else True

    def print_info(self):
        en1_value = self.en_user.get().strip()
        en2_value = self.en_passwd.get().strip()
        en3_value = self.en_stime.get().strip()
        nowtime = time.strftime('%Y-%m-', time.localtime(time.time()))
        real_en3_value = nowtime + en3_value + " 18:00"
        real_en4_value = nowtime + en3_value + " 20:00"
        en4_value = self.en_stime.get().strip()
        en5_value = self.en_reson.get().strip()
        #print(real_en3_value,real_en4_value)
        isok = job.test_search_in_python_org(en1_value, en2_value,
                                             real_en3_value, real_en4_value,
                                             en5_value)
        #print(isok)

    def checkconf(self):
        if os.path.exists("local.conf") and os.path.getsize("local.conf") != 0:
            list = []
            with open('local.conf', 'r') as f:
                for line in f.readlines():
                    list.append(line.strip())
                    print(line.strip())
            self.en_user.insert(0, list[0])
            self.en_passwd.insert(0, list[1])
            self.en_stime.insert(0, u'01')
            self.en_reson.insert(0, list[2])
        else:
            self.en_user.insert(0, u'input you name')
            self.en_passwd.insert(0, u'input you password')
            self.en_stime.insert(0, u'01')
            self.en_reson.insert(0, u'值班')
class MainWindow(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title(mainWindowTitle)
        self.resizable(width=0, height=0)
        self.__setStyles()
        self.__initializeComponents()
        self.__dataController = DataController();
        self.mainloop()
            
    def __initializeComponents(self):
        self.imageCanvas = Canvas(master=self, width=imageCanvasWidth,
                                  height=windowElementsHeight, bg="white")
        self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0),
                              pady=windowPadding, fill=BOTH)
        
        self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth,
                                  height=windowElementsHeight)
        self.buttonsFrame.propagate(0)
        self.loadFileButton = Button(master=self.buttonsFrame,
                                     text=loadFileButtonText, command=self.loadFileButtonClick)
        self.loadFileButton.pack(fill=X, pady=buttonsPadding);
        
        self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText)
        self.colorByLabel.pack(fill=X)
        self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED,
                                        values=colorByComboboxValues)
        self.colorByCombobox.set(colorByComboboxValues[0])
        self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange)
        self.colorByCombobox.pack(fill=X, pady=buttonsPadding)
        self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText)
        self.rejectedValuesPercentLabel.pack(fill=X)
        self.rejectedValuesPercentEntry = Entry(self.buttonsFrame)
        self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent)
        self.rejectedValuesPercentEntry.config(state=DISABLED)
        self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding)        
        
        self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText)
        self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText)
        self.colorsTableLengthLabel.pack(fill=X)
        self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableLengthEntry.insert(0, defaultColorsTableLength)
        self.colorsTableLengthEntry.config(state=DISABLED)
        self.colorsTableLengthEntry.pack(fill=X)
        self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText)
        self.scaleTypeLabel.pack(fill=X)
        self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED,
                                          values=scaleTypesComboboxValues)
        self.scaleTypeCombobox.set(scaleTypesComboboxValues[0])
        self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange)
        self.scaleTypeCombobox.pack(fill=X)
        self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText)
        self.colorsTableMinLabel.pack(fill=X)
        self.colorsTableMinEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMinEntry.insert(0, defaultColorsTableMin)
        self.colorsTableMinEntry.config(state=DISABLED)
        self.colorsTableMinEntry.pack(fill=X)
        self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText)
        self.colorsTableMaxLabel.pack(fill=X)
        self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMaxEntry.insert(0, defaultColorsTableMax)
        self.colorsTableMaxEntry.config(state=DISABLED)
        self.colorsTableMaxEntry.pack(fill=X)
        self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding)
        
        self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText,
                                   state=DISABLED, command=self.__redrawButtonClick)
        self.redrawButton.pack(fill=X, pady=buttonsPadding)
        self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH)
        
    def __setStyles(self):
        Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont)
    
    def loadFileButtonClick(self):
        fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')])
        if (fileName):
            if (not self.__getInputParams()):
                self.__showInvalidInputMessage()
                return
            
            self.lastFileName = fileName;
            self.title(mainWindowTitle + " " + fileName)
            self.__draw(fileName)
            tkMessageBox.showinfo(measureDialogTitle, 
                                  measureDialogText + str(self.__dataController.getMeasure(fileName)))
            
            self.redrawButton.config(state=NORMAL)
            self.colorByCombobox.config(state="readonly")
            self.colorsTableLengthEntry.config(state=NORMAL)
            self.scaleTypeCombobox.config(state="readonly")
            
    def __redrawButtonClick(self):
        if (not self.__getInputParams()):
            self.__showInvalidInputMessage()
            return
        
        self.__draw(self.lastFileName)

    def __scaleTypeComboboxChange(self, event):
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            self.colorsTableMinEntry.config(state=DISABLED)
            self.colorsTableMaxEntry.config(state=DISABLED)
        else:
            self.colorsTableMinEntry.config(state=NORMAL)
            self.colorsTableMaxEntry.config(state=NORMAL)
        
    def __colorByComboboxChange(self, event):
        if (self.colorByCombobox.get() == colorByNoneOption):
            self.rejectedValuesPercentEntry.config(state=DISABLED)
        else:
            self.rejectedValuesPercentEntry.config(state=NORMAL)
        
    def __draw(self, fileName):
        self.imageCanvas.delete(ALL)

        dataForDrawing = self.__dataController.getDataForDrawing(
            fileName, self.colorByCombobox.get(), self.colorsTableLength,
            self.scaleTypeCombobox.get(), self.colorsTableMinValue,
            self.colorsTableMaxValue, self.rejectedValuesPercent)
        
        for package in dataForDrawing:
            x = package[0];
            y = package[1];
            color = package[2];
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color)
            
    def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv):   
        allSpeeds = self.__getAllSpeeds(dataPackages)
        minSpeed = min(allSpeeds)
        maxSpeed = max(allSpeeds)
        
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            colorsTableMinValue = minSpeed
            colorsTableMaxValue = maxSpeed
        else:
            colorsTableMinValue = self.colorsTableMinValue
            colorsTableMaxValue = self.colorsTableMaxValue
        
        i = 0
        for package in dataPackages:
            x = (package[dataXNumber] - minX) * ratio
            y = (package[dataYNumber] - minY) * ratio
            
            color = hsv.getColorByValue(colorsTableMinValue,
                                        colorsTableMaxValue,
                                        allSpeeds[i])
                
            tk_rgb = "#%02x%02x%02x" % color
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb)
            i += 1
            
    def __showInvalidInputMessage(self):
        tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText)
    
    def __getInputParams(self):
        try:
            self.colorsTableLength = int(self.colorsTableLengthEntry.get())
            self.colorsTableMinValue = float(self.colorsTableMinEntry.get())
            self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get())
            self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get())
        
            if (self.colorsTableLength < 1 or
                self.colorsTableMinValue >= self.colorsTableMaxValue or
                self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100):
                raise
            return True
        except:
            return False
Ejemplo n.º 48
0
class Window(Frame):
	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.parent = parent
		self.initUI()

	def initUI(self):
		self.style = Style()
		self.style.theme_use("clam")
		self.pack(fill=BOTH,expand=5)
		self.parent.title("Document Similarity Checker")
		self.dir = "Choose a directory"
		self.setupInputs()
		self.setButton()
	
	def setupInputs(self):
		self.chooseDir = Button(self, text="Choose",command=self.getDir)
		self.chooseDir.place(x=10, y=10)
		self.selpath = Label(self, text=self.dir, font=("Helvetica", 12))
		self.selpath.place(x=150, y=10)

		self.aLabel = Label(self, text="Alpha", font=("Helvetica", 12))
		self.aLabel.place(x=10, y=50)
		self.aEntry = Entry()
		self.aEntry.place(x=200,y=50,width=400,height=30)

		self.bLabel = Label(self, text="Beta", font=("Helvetica", 12))
		self.bLabel.place(x=10, y=100)
		self.bEntry = Entry()
		self.bEntry.place(x=200,y=100,width=400,height=30)

	def setButton(self):
		self.quitButton = Button(self, text="Close",command=self.quit)
		self.quitButton.place(x=520, y=250)

		self.browserButton = Button(self, text="Open Browser",command=self.browser)
		self.browserButton.place(x=400, y=250)
		self.browserButton.config(state=DISABLED)

		self.generate = Button(self, text="Generate Data",command=self.genData)
		self.generate.place(x=10, y=250)

	def browser(self):
		import webbrowser
		webbrowser.get('firefox').open('data/index.html')
		self.browserButton.config(state=DISABLED)

	def getDir(self):
		globals.dir = tkFileDialog.askdirectory(parent=self.parent,initialdir="/",title='Select a directory')
		self.selpath['text'] = globals.dir
		#print globals.dir

	#validate and process data
	def genData(self):
		valid = True
		try:
			globals.alpha = float(self.aEntry.get())
		except ValueError:
			globals.alpha = 0.0
			valid = False
		try:
			globals.beta = float(self.bEntry.get())
		except ValueError:
			globals.beta = 0.0
			valid = False

		if not os.path.isdir(globals.dir) or globals.alpha>=1.0 or globals.beta>=1.0:
			valid = False

		if valid:
			self.generate.config(state=DISABLED)
			from compute import main as computeMain
			computeMain()
			from jsonutil import main as jsonMain
			jsonMain()
			self.browserButton.config(state=NORMAL)
			self.generate.config(state=NORMAL)
Ejemplo n.º 49
0
 def initUI(self):
     self.parent.title("One Time Pad Generator")
     self.style = Style()
     self.style.theme_use("default")
     self.grid()
     
     #string
     text_to_encrypt = Entry(self)
     text_to_encrypt.grid(row=0, column=0)
     text_to_encrypt.delete(0, Tkinter.END)
     text_to_encrypt.insert(0, "text you want to encrypt or decrypt")
     
     #pad
     encrypt_pad = Entry(self)
     encrypt_pad.grid(row=0, column=1)
     encrypt_pad.delete(0, Tkinter.END)
     encrypt_pad.insert(0, "padOutput")
     
     #start
     start_encrypt = Entry(self)
     start_encrypt.grid(row=0, column=2)
     start_encrypt.delete(0, Tkinter.END)
     start_encrypt.insert(0, 0)
     
     
     
     
     #encrypt button
     encodeButton = Button(self, text="Encrypt",
         command=lambda: self.encrypt(text_to_encrypt.get(), encrypt_pad.get(), start_encrypt.get()))
     encodeButton.grid(row=1, column=0)
     #decrypt button
     encodeButton = Button(self, text="Decrypt",
         command=lambda: self.decrypt(str(text_to_encrypt.get()), encrypt_pad.get(), start_encrypt.get()))
     encodeButton.grid(row=1, column=2)
     
   
     #generate pad
     padgen = Entry(self)
     padgen.grid(row=2, column=0)
     padgen.delete(0, Tkinter.END)
     padgen.insert(0, 0)
     
     #gen key button
     genkey = Button(self, text="Generate Key",
                     command=lambda: Cryptography.outputPad(Cryptography.GenerateKey(int(padgen.get())), encrypt_pad.get()))
     genkey.grid(row=2, column=1)
     
     #encrypted text
    
     self.T = Tkinter.Text(self)
     S = Scrollbar(self.T)
     S.grid(column=2);
     S.config(command=self.T.yview)
     self.T.config(yscrollcommand=S.set)
     self.T.insert(Tkinter.END,self.encrypted[0])
     self.T.grid(row=5, column=0, sticky="nsew", rowspan = 10, columnspan = 3)
     
    
     #input email
     e = Entry(self)
     e.grid(row = 3, column = 0)
     e.delete(0, Tkinter.END)
     e.insert(0, "Send encrypted message via email")
     #send email
     email = Button(self, text="Send Email",command=lambda:self.sendmail(e.get()))
     email.grid(row=3, column=1)
class Test_GPS3G(tk.Frame):
	_title = "GPS + 3G Demo"
	def __init__(self, parent, controller):
		tk.Frame.__init__(self, parent)
		self.controller = controller

		label = tk.Label(self, text=self._title, font=TITLE_FONT)
		label.pack(side="top", fill="x", pady=10)

		frame_apn = tk.Frame(self)
		frame_apn.pack(fill=tk.X)
		lbl_apn = tk.Label(frame_apn, text="apn", width=8)
		lbl_apn.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_apn = Entry(frame_apn)
		self.entry_apn.insert(tk.END, 'internet')
		self.entry_apn.pack(fill=tk.X, padx=5, expand=True)

		frame_username = tk.Frame(self)
		frame_username.pack(fill=tk.X)
		lbl_username = tk.Label(frame_username, text="username", width=8)
		lbl_username.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_username = Entry(frame_username)
		self.entry_username.pack(fill=tk.X, padx=5, expand=True)

		frame_password = tk.Frame(self)
		frame_password.pack(fill=tk.X)
		lbl_password = tk.Label(frame_password, text="password", width=8)
		lbl_password.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_password = Entry(frame_password)
		self.entry_password.pack(fill=tk.X, padx=5, expand=True)

		frame_dial_number = tk.Frame(self)
		frame_dial_number.pack(fill=tk.X)
		lbl_dial_number = tk.Label(frame_dial_number, text="dial_number", width=8)
		lbl_dial_number.pack(side=tk.LEFT, padx=5, pady=5)
		self.entry_dial_number = Entry(frame_dial_number)
		self.entry_dial_number.insert(tk.END, '*99#')
		self.entry_dial_number.pack(fill=tk.X, padx=5, expand=True)

		btn_exit = tk.Button(self, text="Back",
						   command=self.OnClose)
		btn_exit.pack(side=tk.RIGHT, padx=5, pady=5)

		self.btn_test = tk.Button(self, text="Run",
						   command=self.GPS3GTest)
		self.btn_test.pack(side=tk.RIGHT, padx=5, pady=5)

	def OnClose(self):
		self.btn_test.config(state=tk.NORMAL)
		self.controller.show_frame("StartPage")

	def GPS3GTest(self):
		if self.entry_apn.get() == "":
			mbox.showerror("Error", "apn should not be blank")
			return

		App_Argument = ""
		if ENABLE_ARGUMENT == True:
			App_Argument += " -a " + self.entry_apn.get() + \
						" -d " + self.entry_dial_number.get()
			if len(self.entry_username.get()) > 0:
				App_Argument += " -u " + self.entry_username.get()
			if len(self.entry_password.get()) > 0:
				App_Argument += " -p " + self.entry_password.get()
		else:
			App_Argument = LED_GPS3G
		print RUN_SCRIPT + GPS_3G_TEST_APP + App_Argument

		# Force eth0 down, in order to connect 3g correctly
		if ssh_session.CreateSshSession(RUN_SCRIPT + WIFI_DOWN, WIFI_DOWN) != 0:
			return self.OnClose()

		# Wait for eth0 has been down
		time.sleep(2)

		if ssh_session.CreateSshSession(RUN_SCRIPT + GPS_3G_TEST_APP + App_Argument, GPS_3G_TEST_APP) != 0:
			return self.OnClose()

		self.btn_test.config(state=tk.DISABLED)
Ejemplo n.º 51
0
class Open(Frame):

    def __init__(self, parent, **kw):
        Frame.__init__(self, **kw)
        self.parent = parent
        self.initUI()
        return

    def initUI(self):
        config = ConfigParser.ConfigParser()
        config.read('settings.ini')
        default_sheet = config.get('USER', 'default_spreadsheet')
        self.pack(fill=BOTH, expand=True)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)

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

        self.lblTsv = Label(self, text="Enter TSV Export:")
        self.lblTsv.grid(sticky=W, pady=4, padx=5)

        self.txtTsv = Text(self)
        self.txtTsv.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+N+S)

        self.btnSubmit = Button(self, text="Submit", command=self.submit_text)
        self.btnSubmit.grid(row=6, column=4, padx=5)

        self.btnUpload = Button(self, text="Upload to GS", command = self.upload_db)
        self.btnUpload.grid(row=6, column=3, padx=5)

        self.btnCancel = Button(self, command=sys.exit, text="Quit")
        self.btnCancel.grid(row=6, column=2, padx=5)

        self.lblSheet = Label(self, text="Enter google sheets URL:")
        self.lblSheet.grid(row=5, sticky=W, pady=4, padx=4)

        self.sheetUrl = Entry(self)
        self.sheetUrl.grid(row=6, columnspan=2, sticky=W+E, padx=5, pady=5)
        self.sheetUrl.insert(0, default_sheet)
        return


    def submit_text(self):
        text = self.txtTsv.get("1.0", END)
        reader = RCLCReader()
        session = Session()
        try:
            db_objects, failed_lines = reader.read_tsv_text(text, session)
            session.commit()
            if len(failed_lines) > 0:
                errormsg = "{0} lines raised an error when reading data:\n".format(len(failed_lines))
                for line in failed_lines:
                    errormsg += line
                tkMessageBox.showerror("Error", errormsg)
            else:
                tkMessageBox.showinfo("Data Submission Complete", "All data has been submitted to DB successfully.")
        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
            tkMessageBox.showerror("Error", "An error occured in reading the data: {0} {1}.\nTraceback: {2}.".format(e.message, str(e), traceback.format_tb(tb)))
        return


    def upload_db(self):
        session = Session()
        id_regex = "/spreadsheets/d/([a-zA-Z0-9-_]+)"
        id = re.search(id_regex, self.sheetUrl.get())
        if len(id.groups()) == 0:
            tkMessageBox.showerror("Error", "A valid google sheet ID could not be determined.")
        else:
            config = ConfigParser.ConfigParser()
            config.read('settings.ini')
            config.set('USER', 'default_spreadsheet', self.sheetUrl.get())
            fp = open('settings.ini', 'w+')
            config.write(fp)
            fp.close()
            try:
                writer = GSheetsWriter(spreadsheet_id=id.group(1))
                writer.update_loot_spreadsheet(session)
            except Exception as e:
                fp = open("delete_error.txt", "w+")
                ex_type, ex, tb = sys.exc_info()
                fp.write(str(ex_type))
                traceback.print_tb(tb, file=fp)
                fp.write(str(e.args) + "\n")
                fp.write(str(e) + "\n")
                fp.write(e.message + "\n")
                fp.flush()
                fp.close()
                tkMessageBox.showerror("Error", "An error occurred in uploading to google sheets: {0}".format(e.message))
            tkMessageBox.showinfo("", "Loot data has been uploaded to google spreadsheet.")
        return
Ejemplo n.º 52
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        
    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background = "#000000")
        self.style.configure("TCheckbutton", background = "#000000")
        self.style.configure("TButton", background = "#000000") 
        self.pack(fill=BOTH, expand=1)
        
        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight = 1)
        self.rowconfigure(6, weight = 1)
        
        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky = W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height = 20)
        area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=3, sticky = N+S+E+W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self, text="IP Address",variable=self.ip, width=10)
        ip_add_button.grid(row = 1, column = 3, sticky = N)
        ip_add_button.config(anchor = W, activebackground = "red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self, text="Ports", variable=self.port, width=10)
        port_button.grid(row = 1, column = 3)
        port_button.config(anchor = W, activebackground = "orange")
        
        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self, text="Host Name",variable=self.host, width=10)
        host_name_button.grid(row = 1, column = 3, sticky = S)
        host_name_button.config(anchor = W, activebackground = "yellow")
        
        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self, text="Gateway", variable=self.gateway, width=10)
        gateway_btn.grid(row = 2, column = 3, sticky = N)
        gateway_btn.config(anchor = W, activebackground = "green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self, text="Services", variable = self.service, width=10)
        service_btn.grid(row = 2, column = 3)
        service_btn.config(anchor = W, activebackground = "blue")

        # Starting IP label
        ip_label = Label(self, text = "Starting IP:  ")
        ip_label.grid(row = 5, column = 0, pady = 1, padx = 3, sticky = W)
        self.ip_from = Entry(self, width = 15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row = 5 , column = 0, pady = 1, padx = 3, sticky = E)

        # Ending IP label
        ip_label_two = Label(self, text = "Ending IP:  ")
        ip_label_two.grid(row = 5, column = 1, pady = 1, padx = 5, sticky = W)
        self.ip_to = Entry(self, width = 15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = E)
        
        # Starting Port Label
        port_label = Label(self, text = "Starting Port:  ")
        port_label.grid(row = 5, column = 0, pady = 3, padx = 5, sticky = S+W)
        self.port_from = Entry(self, width = 15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row = 5 , column = 0, pady = 1, padx = 5, sticky = S+E)

        # Ending Port Label
        port_label_two = Label(self, text = "Ending Port:  ")
        port_label_two.grid(row = 5, column = 1, pady = 3, padx = 5, sticky = S+W)
        self.port_to = Entry(self, width = 15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = S+E)

        # Scan Me 
        self_scan_button = Button(self, text="Scan Me", command = lambda : self.onClick(1), width = 33)
        self_scan_button.grid(row = 6, column = 1, sticky = N)

        # Scan near me Button
        scan_other_button = Button(self, text="Scan Near Me", width = 33, command = lambda : self.onClick(2))
        scan_other_button.grid(row = 6, column = 0, pady=1, sticky = N)
        
        # Clear button
        clear_button = Button(self, text="Clear text", command = self.clear_text, width = 12)
        clear_button.grid(row = 6, column = 3, pady=1, sticky = N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient = HORIZONTAL, length = 175)
        self.label_scanning.grid(row = 6, column = 0, columnspan = 4, padx = 7, pady = 7, sticky = E+S+W)
        self.label_scanning.config(mode = "determinate")

     
    # Clear what is in the text box.   
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []
        
    # On click methods for scan me and scan others.
    def onClick(self, button_id):
        
        if button_id == 1:
            
            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground = "blue")    
                
            # Check to see if ports button is marked   
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()                
                        message, total = scan_my_ports(int(starting_port), int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")
                    
                    time = "The TCP port scan completed in: " + str(total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")
                
            # Check to see if IP button is marked     
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)
            
            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0. new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        # If Scan other button is clicked. 
        elif button_id == 2:
            
            # Check other IP's 
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()
                        
                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address, ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(i,"is UP\n")
                                self.area.insert(0.0, new_message)
                        
                        total_time =  "Range scanned: " + str(starting_ipv4_address) +" to " + str(ending_ipv4_address) + "\n" + "The IP scan completed in:  " + str(time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground = "red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")
                
                
            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        
                        
                        message, time = scan_ports_other(int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i +"\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"
                    
                    total_time = "TCP Port scan completed in: " + str(time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                    
                else:
                    self.area.insert(0.0, "No Port range specified.")
            
            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected 
                if message:
                    for i in message:
                        new_message = "Host name: "+ str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)
                    
                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)
                    
                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)
                    
                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        else:
            pass
Ejemplo n.º 53
0
class AdderApp(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Adder App")
        #self.master.geometry("200x150")

        self.instructions = Label(self, text="Enter the value to add to:")
        self.instructions.pack(pady=5)

        self.number = Entry(self)
        self.number.focus_set()
        self.number.pack(pady=5)

        self.total = Tkinter.StringVar()
        self.time = Tkinter.StringVar()

        self.total_frame = Frame(self)
        self.total_frame.pack(pady=0)
        Label(self.total_frame, text="Total:").pack(side=Tkinter.LEFT, padx=5)
        Label(self.total_frame, textvariable=self.total).pack(side=Tkinter.LEFT)
        self.time_frame = Frame(self)
        self.time_frame.pack(pady=0)
        Label(self.time_frame, text="Time:").pack(side=Tkinter.LEFT)
        Label(self.time_frame, textvariable=self.time).pack(side=Tkinter.LEFT)
        self.complete_msg = Tkinter.StringVar()
        Label(self, textvariable=self.complete_msg).pack(pady=2)

        self.buttons = Frame(self)
        self.buttons.pack(side=Tkinter.BOTTOM, pady=2)
        self.quit_btn = Button(self.buttons, text="Quit", command=self.quit)
        self.quit_btn.pack(side=Tkinter.LEFT)
        self.quit_btn.bind("<Return>", (lambda e, b=self.quit_btn: b.invoke()))
        self.run_btn = Button(self.buttons, text="Run", command=self.run, default=Tkinter.ACTIVE)
        self.run_btn.pack(side=Tkinter.LEFT)

        self.pack(fill=Tkinter.X)
        self.master.bind("<Return>", (lambda e, b=self.run_btn: b.invoke()))

    def run_btn_invoke(self, e):
        print("starting run with button enter")
        self.run_btn.invoke()

    def run(self):
        self.complete_msg.set("")

        self.add_run = adder.Adder()
        self.t = threading.Thread(target=self.add_run.run_to, args=(int(self.number.get()),))
        self.t.start()

        self.update_status()

    def update_status(self):
        self.total.set(self.add_run.total)
        try:
            self.time.set(self.add_run.elapsed_seconds())
        except Exception:
            pass

        if self.add_run.complete:
            self.add_run.complete = False
            self.complete_msg.set("Run Complete")
            self.quit_btn.focus_set()

        self.after(50, self.update_status)
Ejemplo n.º 54
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background="#000000")
        self.style.configure("TCheckbutton", background="#000000")
        self.style.configure("TButton", background="#000000")
        self.pack(fill=BOTH, expand=1)

        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, weight=1)

        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky=W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height=20)
        area.grid(row=1,
                  column=0,
                  columnspan=3,
                  rowspan=4,
                  padx=3,
                  sticky=N + S + E + W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self,
                                    text="IP Address",
                                    variable=self.ip,
                                    width=10)
        ip_add_button.grid(row=1, column=3, sticky=N)
        ip_add_button.config(anchor=W, activebackground="red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self,
                                  text="Ports",
                                  variable=self.port,
                                  width=10)
        port_button.grid(row=1, column=3)
        port_button.config(anchor=W, activebackground="orange")

        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self,
                                       text="Host Name",
                                       variable=self.host,
                                       width=10)
        host_name_button.grid(row=1, column=3, sticky=S)
        host_name_button.config(anchor=W, activebackground="yellow")

        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self,
                                  text="Gateway",
                                  variable=self.gateway,
                                  width=10)
        gateway_btn.grid(row=2, column=3, sticky=N)
        gateway_btn.config(anchor=W, activebackground="green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self,
                                  text="Services",
                                  variable=self.service,
                                  width=10)
        service_btn.grid(row=2, column=3)
        service_btn.config(anchor=W, activebackground="blue")

        # Starting IP label
        ip_label = Label(self, text="Starting IP:  ")
        ip_label.grid(row=5, column=0, pady=1, padx=3, sticky=W)
        self.ip_from = Entry(self, width=15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row=5, column=0, pady=1, padx=3, sticky=E)

        # Ending IP label
        ip_label_two = Label(self, text="Ending IP:  ")
        ip_label_two.grid(row=5, column=1, pady=1, padx=5, sticky=W)
        self.ip_to = Entry(self, width=15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row=5, column=1, pady=1, padx=5, sticky=E)

        # Starting Port Label
        port_label = Label(self, text="Starting Port:  ")
        port_label.grid(row=5, column=0, pady=3, padx=5, sticky=S + W)
        self.port_from = Entry(self, width=15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row=5, column=0, pady=1, padx=5, sticky=S + E)

        # Ending Port Label
        port_label_two = Label(self, text="Ending Port:  ")
        port_label_two.grid(row=5, column=1, pady=3, padx=5, sticky=S + W)
        self.port_to = Entry(self, width=15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row=5, column=1, pady=1, padx=5, sticky=S + E)

        # Scan Me
        self_scan_button = Button(self,
                                  text="Scan Me",
                                  command=lambda: self.onClick(1),
                                  width=33)
        self_scan_button.grid(row=6, column=1, sticky=N)

        # Scan near me Button
        scan_other_button = Button(self,
                                   text="Scan Near Me",
                                   width=33,
                                   command=lambda: self.onClick(2))
        scan_other_button.grid(row=6, column=0, pady=1, sticky=N)

        # Clear button
        clear_button = Button(self,
                              text="Clear text",
                              command=self.clear_text,
                              width=12)
        clear_button.grid(row=6, column=3, pady=1, sticky=N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient=HORIZONTAL, length=175)
        self.label_scanning.grid(row=6,
                                 column=0,
                                 columnspan=4,
                                 padx=7,
                                 pady=7,
                                 sticky=E + S + W)
        self.label_scanning.config(mode="determinate")

    # Clear what is in the text box.
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []

    # On click methods for scan me and scan others.
    def onClick(self, button_id):

        if button_id == 1:

            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground="blue")

            # Check to see if ports button is marked
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        message, total = scan_my_ports(int(starting_port),
                                                       int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")

                    time = "The TCP port scan completed in: " + str(
                        total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")

            # Check to see if IP button is marked
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)

            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0.new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        # If Scan other button is clicked.
        elif button_id == 2:

            # Check other IP's
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()

                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address,
                                                      ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(
                                    i, "is UP\n")
                                self.area.insert(0.0, new_message)

                        total_time = "Range scanned: " + str(
                            starting_ipv4_address) + " to " + str(
                                ending_ipv4_address
                            ) + "\n" + "The IP scan completed in:  " + str(
                                time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")

            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()

                        message, time = scan_ports_other(
                            int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i + "\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"

                    total_time = "TCP Port scan completed in: " + str(
                        time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Port range specified.")

            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected
                if message:
                    for i in message:
                        new_message = "Host name: " + str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)

                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground="red")

            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)

                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        else:
            pass
Ejemplo n.º 55
0
class Login(object):
    def __init__(self):
        self.root = Tk()
        self.root.title(u'登录')
        self.root.resizable(False, False)
        self.root.geometry('+450+250')
        # self.sysfont = font(self.root, size=15)
        self.lb_user = Label(self.root,
                             text=u'用户名:',
                             width=20,
                             height=10,
                             font=("黑体", 15, "bold"))
        self.lb_passwd1 = Label(self.root, text=u'')
        self.lb_passwd = Label(self.root,
                               text=u'密码:',
                               width=20,
                               height=5,
                               font=("黑体", 15, "bold"))
        self.lb_user.grid(row=0, column=0, sticky=W)
        self.lb_passwd1.grid(row=1, column=0, sticky=W)
        self.lb_passwd.grid(row=2, column=0, sticky=W)

        self.en_user = Entry(self.root, width=24)
        self.en_passwd = Entry(self.root, width=24)
        self.en_user.grid(row=0, column=1, columnspan=1)
        self.en_passwd.grid(row=2, column=1, columnspan=1)
        self.en_user.insert(0, u'请输入用户名')
        self.en_passwd.insert(0, u'请输入密码')
        self.en_user.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_user'),
            invalidcommand=lambda: self.invalid_func('self.en_user'))
        self.en_passwd.config(
            validate='focusin',
            validatecommand=lambda: self.validate_func('self.en_passwd'),
            invalidcommand=lambda: self.invalid_func('self.en_passwd'))

        self.var = IntVar()
        self.ckb = Checkbutton(self.root,
                               text=u'记住用户名和密码',
                               underline=0,
                               variable=self.var,
                               font=(15))
        self.ckb.grid(row=3, column=0)
        self.bt_print = Button(self.root, text=u'登陆')
        self.bt_print.grid(row=3, column=1, sticky=E, pady=50, padx=10)
        self.bt_print.config(command=self.print_info)

        self.bt_register = Button(self.root, text=u'注册')
        self.bt_register.grid(row=3, column=2, sticky=E, pady=50, padx=50)
        # self.bt_register.config(command=self.register_info)
        # self.root.bind('<Return>', self.enter_print)
        self.root.mainloop()

    def validate_func(self, en):
        return False if eval(en).get().strip() != '' else True

    def invalid_func(self, en):
        value = eval(en).get().strip()
        if value == u'输入用户名' or value == u'输入密码':
            eval(en).delete(0, END)
        if en == 'self.en_passwd':
            eval(en).config(show='*')

    def print_info(self):
        en1_value = self.en_user.get().strip()
        en2_value = self.en_passwd.get().strip()
        txt = u'''用户名: %s \n密码  : %s ''' % (self.en_user.get(),
                                            self.en_passwd.get())
        if en1_value == '' or en1_value == u'输入用户名':
            print(u'无用户名', u'请输入用户名')
        elif en2_value == '' or en2_value == u'输入密码':
            print(u'无密码', u'请输入密码')
        else:
            a = 0
            # 打开数据库连接
            db = pymysql.connect("62.234.41.135", "root", "root", "book")
            # 使用cursor()方法获取操作游标
            cursor = db.cursor()
            # SQL 查询语句
            sql = "select * from user"
            try:
                # 执行SQL语句
                cursor.execute(sql)
                # 获取所有记录列表
                results = cursor.fetchall()
                for row in results:
                    id = row[0]
                    name = row[1]
                    pwd = row[2]
                    if name == en1_value and pwd == en2_value:
                        a = 1
                        print("数据库连接及验证成功!!!")
                        print('登陆成功!!!', txt)
                    # # 打印结果
                    # print "id=%d,name=%s,pwd=%s" % \
                    #       (id, name, pwd)
            except:
                print("Error: unable b_while fecth data")

            # 关闭数据库连接
            db.close()
            if (a == 0):
                print('用户名或密码错误!!!', txt)

    def register_info(self):
        self.rootR = Tk()
        loginPage(self.rootR)
        self.root.withdraw()

    def enter_print(self, event):
        self.print_info()
Ejemplo n.º 56
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.initUI()
        self.UIwithGrid()

    def initUI(self):  # creating gui
        self.frame1 = Frame(self)
        self.frame2 = Frame(self)
        self.frame3 = Frame(self)
        self.frame4 = Frame(self)
        self.frame5 = Frame(self)

        # created multiple frames

        self.label1 = Label(self.frame1,
                            text="COURSE PROGRAM ESTIMATOR",
                            font='Helvetica 25 bold',
                            background="SpringGreen3",
                            foreground="black")
        self.label2 = Label(self.frame1,
                            text="     Training Data: ",
                            font="Times 14")
        self.entry = Entry(self.frame1, width=65)
        self.entry.insert(
            0,
            'https://www.sehir.edu.tr/tr/duyurular/2017-2018-Akademik-Yili-Ders-Programi'
        )
        self.color = Label(
            self.frame1,
            text="                   ",
            background="red",
        )
        self.button = Button(self.frame1,
                             text="Fetch and Train",
                             command=self.fetch)
        self.label3 = Label(self.frame2,
                            text="Individual Courses:",
                            font='Helvetica 10 bold')
        self.label4 = Label(self.frame3,
                            text="     Top 3 Estimates:",
                            font='Helvetica 10 bold')
        self.coursesListbox = Listbox(self.frame2, width=30)
        self.label5 = Label(self.frame4,
                            text=" Accuracy Analysis \nBased on Programs: ",
                            font='Helvetica 10 bold')
        self.programsListbox = Listbox(self.frame4, width=30)
        self.estimatesListbox = Text(self.frame5, width=30, height=10)

        self.scrollbar1 = Scrollbar(self.frame2, orient=VERTICAL)
        self.scrollbar2 = Scrollbar(self.frame4, orient=VERTICAL)
        self.scrollbar3 = Scrollbar(self.frame5, orient=VERTICAL)
        self.scrollbar1.config(command=self.coursesListbox.yview)
        self.scrollbar2.config(comman=self.programsListbox.yview)
        self.scrollbar3.config(command=self.estimatesListbox.yview)
        self.coursesListbox.config(yscrollcommand=self.scrollbar1.set)
        self.programsListbox.config(yscrollcommand=self.scrollbar2.set)
        self.estimatesListbox.config(yscrollcommand=self.scrollbar3.set)

    def UIwithGrid(self):
        self.frame1.grid(row=1, column=2, sticky=N + S + E + W)
        self.frame2.grid(row=2, column=1, columnspan=2, sticky=W)
        self.frame3.grid(row=2, column=2, sticky=N + E)
        self.frame4.grid(row=3, column=1, columnspan=2, sticky=W, pady=5)
        self.frame5.grid(row=3, column=2, columnspan=2, sticky=E, pady=5)
        self.label1.grid(row=1, column=2, sticky=E + W)
        self.label2.grid(row=2, column=1, columnspan=2, pady=25, sticky=W)
        self.entry.grid(row=2, column=2, columnspan=2, sticky=E)
        self.color.grid(row=3, column=2, columnspan=2)
        self.button.grid(row=3, column=2, sticky=E, padx=90)
        self.label3.grid(row=1, column=1)
        self.coursesListbox.grid(row=2, column=1)
        self.label4.pack(in_=self.frame3, side='left')
        self.label5.grid(row=1, column=1)
        self.programsListbox.grid(row=2, column=1)
        self.estimatesListbox.grid(row=2, column=3, sticky=E)
        self.scrollbar1.grid(row=2, column=1, sticky=N + S + E)
        self.scrollbar2.grid(row=2, column=1, sticky=N + E + S)
        self.scrollbar3.grid(row=2, column=2, columnspan=2, sticky=N + S + E)
        self.pack()

    def fetch(self):  # fetching phase
        self.color.config(background='yellow')
        self.course_list = []
        self.update()
        url = self.entry.get()
        self.dataobj = Data()  # creating data obj
        self.dataobj.init_data(url)
        self.courses = self.dataobj.courselist.keys()  # getting keys
        self.courses.sort()  # sorting keys
        self.obj_list = []
        for i in self.courses:
            self.obj_list.append(self.dataobj.courselist[i])
        self.classifier_obj = docclass.naivebayes(docclass.getwords)
        for i in self.obj_list:  # TRANING PHASE
            self.classifier_obj.train(i.split_name.lower(), i.first_code)
        r1 = re.compile("(.*?)\s*\(")
        for i in self.courses:  # adding courses to listbox
            course_name = self.dataobj.courselist[i].name
            name = r1.match(course_name)
            if name != None:
                name1 = i + '' + '(' + name.group(1) + ')'
            else:
                name1 = i + ' ' + '(' + course_name + ')'
            self.coursesListbox.insert(END, name1)
        for z in self.courses:  # adding course category to other listbox
            if self.dataobj.courselist[z].first_code not in self.course_list:
                self.course_list.append(self.dataobj.courselist[z].first_code)

            code = self.dataobj.courselist[z].first_code
            if code not in self.programsListbox.get(0, END):
                self.programsListbox.insert(END, code)
        self.color.config(background='green')
        self.update()
        self.coursesListbox.bind('<<ListboxSelect>>', self.estimate)
        self.programsListbox.bind('<<ListboxSelect>>', self.analyze)

    def estimate(self, event):  # estimating phase
        try:
            for wid in self.frame3.winfo_children():
                wid.destroy()
            self.label4 = Label(self.frame3,
                                text="     Top 3 Estimates:",
                                font='Helvetica 10 bold')
            self.label4.pack(in_=self.frame3)
        except:
            print 'ERROR !!!!'
        widget = event.widget
        selection = widget.curselection()
        picked = widget.get(selection[0])
        x = picked.split('(')
        dict_ = {}
        for cat in self.course_list:  # getting estimating scores
            dict_[cat] = self.classifier_obj.prob(x[1], cat) * 10

        scores = dict_
        sorted_scores = sorted(scores.items(),
                               key=operator.itemgetter(1),
                               reverse=True)  # sorting dictionary
        top_3 = sorted_scores[0:3]  # getting top 3 scores
        print top_3
        dict_temp = {x[0].split(' ')[0]: top_3}
        m = 1
        for key, value in dict_temp.items():  # adding items as labels
            for i in value:
                department, score = i
                if department != key:  # checking if it is true estimation or not
                    color = 'red'
                else:
                    color = 'green'
                self.first_element = Label(self.frame3,
                                           text=department + ':' + str(score),
                                           font='Helvetica 15 bold',
                                           background=color,
                                           width=20)
                if m == 1:
                    self.first_element.pack(in_=self.frame3)
                elif m == 2:
                    self.first_element.pack(in_=self.frame3)
                elif m == 3:
                    self.first_element.pack(in_=self.frame3)
                m = m + 1

    def analyze(self, event):
        try:
            self.estimatesListbox.delete('1.0', END)
        except:
            print 'ERROR'
        widget = event.widget
        selection = widget.curselection()
        picked = widget.get(selection[0])
        cat_ = picked
        course_names = {}
        for i in self.obj_list:  # creating a dict. keys name of courses, values code of
            if i.first_code == cat_:  # filtering
                print i.first_code, cat_
                name = i.name.split('(')[0]
                course_names[name] = i.code
            else:
                continue
        info = {}
        for course in course_names.keys():  # finds best match for each course
            score_dict = {}
            for cat in self.course_list:
                score_dict[cat] = self.classifier_obj.prob(course, cat)
            sorted_scores = sorted(score_dict.items(),
                                   key=operator.itemgetter(1),
                                   reverse=True)
            info[course] = sorted_scores[0][0]
        all_info = {
            'Total Number Of Courses: ': str(len(info))
        }  # creating initial analyzing data
        q = 0
        for item in info.values():  # amount of accurate data
            if item != cat_:
                q = q + 1
        all_info['Inaccurate Classification: '] = str(q)
        all_info['Accurately Classified: '] = len(info) - q
        all_info['Accuracy: '] = '%' + str(
            (float(all_info['Accurately Classified: ']) / float(len(info))) *
            100)
        _ = all_info.keys()
        _.sort()
        for infos in _:
            self.estimatesListbox.insert(END,
                                         infos + str(all_info[infos]) + '\n ')

        for course_ in info:
            self.estimatesListbox.insert(
                END,
                '\t' + course_names[course_] + '-->' + info[course_] + '\n')
Ejemplo n.º 57
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.inigen = IniGen()
        self.initUIGlobals()

    def initUIGlobals(self):
        """
      This is the first part of the window to be rendered. After these have been
       set by the user and 'Emit Globals' has been clicked, the given algorithm
       can then specify how to generate the second part of the window. All fields
       are disabled for user input after globals have been emitted.

      Information in Global Parameters:
        Algorithm
          - name of the algorithm to use
        File Name
          - name of the output file to be generated
        Min Time
          - Minimum Time for distillers to run
        Max Time
          - Maximum Time for distillers to run
        Set Enabled:
          - checkbox to specify if the distiller should be enabled True or False
    """
        self.parent.title("Ini Generator")

        Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')

        # initialize row counter. This is incremented after each element added to grid
        row = 0
        # initialize column counter. This is incremented after a column has been filled
        self.column = 0

        # Globals: entries for info common to all runs
        label_globals = Label(self, text="Globals")
        label_globals.grid(row=row, column=self.column)
        row += 1

        label_alg = Label(self, text="Algorithm")
        label_alg.grid(row=row, column=self.column, sticky=E + W)
        row += 1
        self.cbox_alg = Combobox(self,
                                 values=algorithms.keys(),
                                 state='readonly')
        self.cbox_alg.current(0)
        self.cbox_alg.grid(row=row, column=self.column, sticky=E + W + S + N)
        row += 1

        label_filename = Label(self, text="Output File Name")
        label_filename.grid(row=row, column=self.column, sticky=E + W)
        row += 1
        self.entry_filename = Entry(self)
        self.entry_filename.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        label_mintime = Label(self, text="Min Time")
        label_mintime.grid(row=row, column=self.column, sticky=E + W)
        row += 1
        self.entry_mintime = Entry(self)
        self.entry_mintime.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        label_maxtime = Label(self, text="Max Time")
        label_maxtime.grid(row=row, column=self.column, sticky=W + E)
        row += 1
        self.entry_maxtime = Entry(self)
        self.entry_maxtime.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        self.enabled = IntVar()
        self.check_enabled = Checkbutton(self,
                                         text="set enabled",
                                         variable=self.enabled)
        self.check_enabled.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        # Control: buttons used to emmiting text and generating file
        self.button_emit_globals = Button(self,
                                          text="Emit Globals",
                                          command=self.emit_globals)
        self.button_emit_globals.grid(row=row,
                                      column=self.column,
                                      sticky=W + E)
        row += 1

        button_addrun = Button(self, text="Add Run", command=self.emit_run)
        button_addrun.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        button_generate = Button(self,
                                 text="Generate File",
                                 command=self.generate_file)
        button_generate.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        self.column += 1

        self.pack()

    def initUIRuns(self):
        """
      Second part of gui to be rendered. This contains all the fields needed to emit
       a single run within a distiller file. Multiple runs can be added by clicking
       'Add Run' multiple times.

      Information in Run Parameters:
        Run Name
          - header name for run
        Dependencies
          - description and uuid fields for each dependency in the algorithm
        Params
          - parameter fields for each parameter in the algorithm
    """

        self.entry_run_name = None
        self.entries_dep_description = []
        self.entries_dep_uuid = []
        self.entries_param = []

        row = 0

        label_runs = Label(self, text="Runs")
        label_runs.grid(row=row, column=self.column)
        row += 1

        label_run_name = Label(self, text="Run Name")
        label_run_name.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        self.entry_run_name = Entry(self)
        self.entry_run_name.grid(row=row, column=self.column, sticky=W + E)
        row += 1

        algorithm = self.cbox_alg.get()
        settings = algorithms[algorithm]

        for dep in settings['deps']:

            if row >= 21:
                self.column += 1
                row = 1

            label_dep_description = Label(self,
                                          text="{0} (description)".format(dep))
            label_dep_description.grid(row=row,
                                       column=self.column,
                                       sticky=W + E)
            row += 1

            entry_dep_description = Entry(self)
            entry_dep_description.grid(row=row,
                                       column=self.column,
                                       sticky=W + E)
            row += 1

            label_dep_uuid = Label(self, text="{0} (uuid)".format(dep))
            label_dep_uuid.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            entry_dep_uuid = Entry(self)
            entry_dep_uuid.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            self.entries_dep_description.append(entry_dep_description)
            self.entries_dep_uuid.append(entry_dep_uuid)

        for param in settings['params']:

            if row >= 21:
                self.column += 1
                row = 1

            label_param = Label(self, text=param)
            label_param.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            entry_param = Entry(self)
            entry_param.grid(row=row, column=self.column, sticky=W + E)
            row += 1

            self.entries_param.append(entry_param)

        row = 0
        self.column += 1

        self.text_file = Text(self)
        self.text_file.grid(row=row,
                            column=self.column,
                            rowspan=31,
                            sticky=W + E + N + S,
                            padx=5,
                            pady=5)
        self.column += 1
        scrollbar = Scrollbar(self, command=self.text_file.yview)
        self.text_file.config(yscrollcommand=scrollbar.set)
        scrollbar.grid(row=row, column=self.column, rowspan=31, sticky=N + S)

        self.pack()

    def emit_globals(self):
        self.algorithm = algorithms[self.cbox_alg.get()]
        path = self.algorithm['path']
        if self.enabled.get():
            enabled = 'True'
        else:
            enabled = 'False'

        lines = self.inigen.emit_global(path, enabled)

        self.mintime = self.entry_mintime.get()
        self.maxtime = self.entry_maxtime.get()

        self.cbox_alg.configure(state='disabled')
        self.entry_filename.configure(state='disabled')
        self.entry_mintime.configure(state='disabled')
        self.entry_maxtime.configure(state='disabled')
        self.check_enabled.configure(state='disabled')
        self.button_emit_globals.configure(state='disabled')

        self.initUIRuns()
        self.update_text(lines)

    def emit_run(self):
        label = self.entry_run_name.get()
        chunking = 'parallel'  #hardcoded for now
        mintime = self.mintime
        maxtime = self.maxtime
        lines = self.inigen.emit_run_header(label, chunking, mintime, maxtime)
        self.update_text(lines)

        deps = []
        for i in range(len(self.entries_dep_description)):
            deps.append([
                self.entries_dep_description[i].get(),
                self.algorithm['deps'][i], self.entries_dep_uuid[i].get()
            ])
        params = []
        for i in range(len(self.entries_param)):
            params.append(
                [self.algorithm['params'][i], self.entries_param[i].get()])
        outputs = self.algorithm['outputs']
        lines = self.inigen.emit_run_body(deps, params, outputs)
        self.update_text(lines)

    def generate_file(self):
        self.inigen.generate_file(self.entry_filename.get())
        self.quit()

    def update_text(self, lines):
        self.text_file.configure(state='normal')
        string = "\n".join(lines)
        self.text_file.insert(END, string)
        self.text_file.configure(state='disabled')
Ejemplo n.º 58
0
    def initUI(self):
        self.master.title("Telegram UnlimitMe")
        self.master.minsize(width=500, height=300)
        self.pack(fill=BOTH, expand=True)

        frame1 = Frame(self)
        frame1.pack(fill=X)

        tknlbl = Label(frame1, text="Token", width=7, font=("Helvetica", 10))
        tknlbl.pack(side=LEFT, padx=5, pady=5)

        tkntxt = Entry(frame1, font=("Helvetica", 10))
        tkntxt.pack(fill=X, padx=5, expand=True)
        tkntxt.insert(0, self.loadtoken())

        frame2 = Frame(self)
        frame2.pack(fill=X)

        cidlbl = Label(frame2, text="Chat ID", width=7, font=("Helvetica", 10))
        cidlbl.pack(side=LEFT, padx=5, pady=5)

        cidtxt = Entry(frame2, font=("Helvetica", 10))
        cidtxt.pack(fill=X, padx=5, expand=True)
        cidtxt.insert(0, self.loadcid())

        frame3 = Frame(self)
        frame3.pack(fill=X)

        msglbl = Label(frame3, text="Message", width=8, font=("Helvetica", 10))
        msglbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        msgtxt = Entry(frame3, width=30, font=("Helvetica", 10))
        msgtxt.insert(
            0,
            "UnlimitMe script by (Gooogle)[https://github.com/GooogIe/UnlimitMe]"
        )
        msgtxt.pack(fill=BOTH, padx=5, pady=2)

        frame8 = Frame(self)
        frame8.pack(fill=X)

        tmslbl = Label(frame8,
                       text="Spam times",
                       width=10,
                       font=("Helvetica", 10))
        tmslbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        tmstxt = Entry(frame8, width=30, font=("Helvetica", 10))
        tmstxt.insert(0, "5")
        tmstxt.pack(fill=BOTH, padx=5, pady=2)

        frame7 = Frame(self)
        frame7.pack(fill=X)

        imglbl = Label(frame7,
                       text="Image Source",
                       width=15,
                       font=("Helvetica", 10))
        imglbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        imgtxt = Entry(self, width=30, font=("Helvetica", 10))
        imgtxt.insert(0, "http://www.photo.it/ok.png")
        imgtxt.pack(fill=BOTH, padx=5, pady=2)

        frame4 = Frame(self)
        frame4.pack(fill=X)

        x = StringVar()
        x.set("Chat IDS found: \n" + str(chatids(tkntxt.get())))
        cidslbl = Label(frame4,
                        textvariable=x,
                        width=40,
                        font=("Helvetica", 10))
        cidslbl.pack(side=LEFT, anchor=N, padx=5, pady=5)

        listbox = Listbox(frame4, width=30, font=("Helvetica", 10))
        listbox.pack(side=RIGHT, padx=5, pady=5)

        frame5 = Frame(self)
        frame5.pack(fill=X)

        spambtn = Button(frame5,
                         relief=FLAT,
                         bg="#1EFE7B",
                         text="Spam",
                         font=("Helvetica", 10),
                         fg="#ffffff",
                         width=15,
                         command=lambda: self.flood(tmstxt.get(), msgtxt.get(
                         ), tkntxt.get(), cidtxt.get()))
        spambtn.pack(side=RIGHT, padx=5, pady=5)

        sendbtn = Button(
            frame5,
            relief=FLAT,
            bg="#2ECC71",
            text="Send",
            font=("Helvetica", 10),
            fg="#ffffff",
            width=15,
            command=lambda: self.sendMessage(msgtxt.get(), tkntxt.get(
            ), cidtxt.get()) & listbox.insert(END, "You: " + msgtxt.get()))
        sendbtn.pack(side=RIGHT, padx=5, pady=5)

        imgbtn = Button(frame5,
                        relief=FLAT,
                        bg="#1ABC9C",
                        text="Send a Photo",
                        font=("Helvetica", 10),
                        fg="#ffffff",
                        width=15,
                        command=lambda: self.sendImage(imgtxt.get(
                        ), tkntxt.get(), cidtxt.get()))
        imgbtn.pack(side=LEFT, padx=5, pady=5)

        savebtn = Button(
            frame5,
            relief=FLAT,
            bg="#E74C3C",
            text="Save CID & Token",
            font=("Helvetica", 10),
            fg="#ffffff",
            width=15,
            command=lambda: self.saveall(tkntxt.get(), cidtxt.get()))
        savebtn.pack(side=LEFT, padx=5, pady=5)

        getcidsbtn = Button(frame5,
                            relief=FLAT,
                            bg="#3498DB",
                            text="Reload Chat IDS",
                            font=("Helvetica", 10),
                            fg="#ffffff",
                            width=15,
                            command=lambda: x.set("Chat IDS found: \n" +
                                                  chatids(tkntxt.get())))
        getcidsbtn.pack(side=LEFT, padx=5, pady=5)

        frame6 = Frame(self)
        frame6.pack(fill=X, expand=True)

        abtlbl = Label(
            frame6,
            font=("Helvetica", 10),
            text="Created by Habb0n - (c) 2016 - Using Python & Tkinter",
            width=50)
        abtlbl.pack(side=BOTTOM, anchor=N, padx=1, pady=1)
Ejemplo n.º 59
0
class ElementalCodingGUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.elemental_coding = ElementalCoding()
        self.huffman_coding = HuffmanCoding()
        self.dictionary_coding = DictionaryCoding()
        self.init_ui()
        self.current_encoding = 5

    def init_ui(self):
        self.parent.title("Information Theory")
        Style().configure("TButton", padding=(0, 5, 0, 5), font='Verdana 10')

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        self.columnconfigure(4, pad=3)

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)

        string_to_search_label = Label(self, text="Search a string: ")
        string_to_search_label.grid(row=0, column=0, rowspan=2)
        self.string_to_search_textfield = Entry(self)
        self.string_to_search_textfield.grid(row=0, column=1, rowspan=2, columnspan=2, sticky=W)
        self.string_to_search_textfield.bind('<Return>', self.get_string_from_textfield)
        self.compression_ratio_text = StringVar()
        self.compression_ratio_text.set('Compression Ratio: ')
        compression_ratio_label = Label(self, textvariable=self.compression_ratio_text).grid(row=0, column=2,
                                                                                             columnspan=4)

        Separator(self, orient=HORIZONTAL).grid(row=1)
        string_to_encode_label = Label(self, text="Encode a string: ")
        string_to_encode_label.grid(row=2, column=0, rowspan=2)
        self.string_to_encode_textfield = Entry(self)
        self.string_to_encode_textfield.grid(row=2, column=1, rowspan=2, columnspan=2, sticky=W)
        self.string_to_encode_textfield.bind('<Return>', self.get_string_from_textfield_to_encode)

        Separator(self, orient=HORIZONTAL).grid(row=3)
        self.area = Text(self)
        self.area.grid(row=4, column=0, columnspan=3, rowspan=1, padx=5, sticky=E + W)
        self.area.config(width=10, height=15)
        self.possible_options_text = StringVar()
        self.possible_options_text.set("Possible Options: ")
        self.possible_options_label = Label(self, textvariable=self.possible_options_text).grid(row=4, column=3,
                                                                                                sticky=N)

        huffman_coding_button = Button(self, text="Huffman",
                                       command=self.huffman_coding_callback).grid(row=5, column=0)
        arithmetic_coding_button = Button(self, text="Arithmetic Coding",
                                          command=self.arithmetic_coding_callback).grid(row=5, column=1)
        dictionary_coding_button = Button(self, text="Dictionary",
                                          command=self.dictionary_coding_callback).grid(row=5, column=2)
        elias_coding_button = Button(self, text="Elias",
                                     command=self.elias_coding_callback).grid(row=5, column=3)
        our_coding_button = Button(self, text="Elemental Coding",
                                   command=self.elemental_coding_callback).grid(row=5, column=4)
        self.pack()
        self.elemental_coding_callback()

    def get_string_from_textfield_to_encode(self, event):
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = 'a'
        if self.current_encoding == 1:
            self.huffman_coding.encode(text_to_encode)
            self.set_text_in_text_area(output)
            compression_ratio = self.huffman_coding.compression_ratio
            self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        if self.current_encoding == 2:
            pass
        if self.current_encoding == 3:
            pass
        if self.current_encoding == 4:
            pass
        if self.current_encoding == 5:
            self.elemental_coding.getElementList()
            self.elemental_coding.codeElemental(text_to_encode)
            self.elemental_coding.encodeText()
            output = self.elemental_coding.printCodedText()
            compression_ratio = self.elemental_coding.get_compression_ratio()
            self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
            #self.set_text_in_text_area(output)

    def get_string_from_textfield(self, event):
        text_to_encode = self.string_to_sitemearch_textfield.get()
        possible_options = self.elemental_coding.lookForString(text_to_encode)
        self.possible_options_text.set('Possible Options: ' + possible_options)
        self.string_to_search_textfield.delete(END)

    def huffman_coding_callback(self):
        self.current_encoding = 1
        output = self.huffman_coding.encode_default_file()
        self.set_text_in_text_area(output)
        compression_ratio = self.huffman_coding.compression_ratio
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        print "HUFMAAN!"

    def arithmetic_coding_callback(self):
        self.current_encoding = 2
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = ' '
        for char in text_to_encode:
            if char not in arithmetic_intervals:
                can_encode = False
            else:
                can_encode = True
        if can_encode:
            codificacion = interval_coding(text_to_encode, arithmetic_intervals)
            self.compression_ratio_text.set(str(codificacion[2]))
        else:
            self.compression_ratio_text.set("Error: no en intervalos\n"
                                            "Si desea comprobar este metodo,"
                                            "introduce un string en el cuadro\n"
                                            "\"Encode text\"")

        print "Arithmetic!"

    def dictionary_coding_callback(self):
        self.current_encoding = 3
        contents = get_file_contents(os.getcwd() + '/pagina.txt')
        compress_text = self.dictionary_coding.compress(contents)
        compression_ratio = len(compress_text) / float(len(contents))
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio) )
        compress_text = [str(item) for item in compress_text]
        self.set_text_in_text_area(''.join(compress_text))
        print "Dictionary!"

    def elias_coding_callback(self):
        self.current_encoding = 4
        text_to_encode = self.string_to_encode_textfield.get()
        if text_to_encode == '':
            text_to_encode = ' '
        for char in text_to_encode:
            if char not in elias_intervals:
                can_encode = False
            else:
                can_encode = True
        if can_encode:
            codificacion = interval_coding(text_to_encode, elias_intervals)
            self.compression_ratio_text.set(str(codificacion[2]) + "%")
        else:
            self.compression_ratio_text.set("Error: no en intervalos\n"
                                            "Si desea comprobar este metodo,"
                                            "introduce un string en el cuadro\n"
                                            "\"Encode text\"")


    def set_text_in_text_area(self, output):
        self.area.config(state=NORMAL)
        self.area.delete("1.0", END)
        self.area.insert(INSERT, output)
        self.area.config(state=DISABLED)

    def elemental_coding_callback(self):
        self.current_encoding = 5
        self.elemental_coding.getElementList()
        self.elemental_coding.processFile('pagina.txt')
        self.elemental_coding.encodeText()
        output = self.elemental_coding.printCodedText()
        self.set_text_in_text_area(output)
        compression_ratio = self.elemental_coding.get_compression_ratio()
        self.compression_ratio_text.set('Compression Ratio: ' + str(compression_ratio))
        print "Our Coding!"