コード例 #1
0
class CheckBox:
    def __init__(self, root, text: str, x: int, y: int):
        self.varChecked = BooleanVar()
        self.text = text
        self.checkbox = Checkbutton(root,
                                    text=self.text,
                                    variable=self.varChecked,
                                    onvalue=True,
                                    offvalue=False)
        self.x = x
        self.y = y

        self.checkbox.pack()
        self.checkbox.place(x=self.x, y=self.y)

    @property
    def command(self):
        return self.command

    @command.setter
    def command(self, command):
        self.checkbox['command'] = command

    def isChecked(self):
        return True if self.varChecked.get() else False

    def check(self):
        self.checkbox.select()

    def uncheck(self):
        self.checkbox.deselect()
コード例 #2
0
class ProgressCheckButton(Frame, Observable):
    def __init__(self, parent, model, index, status_model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self.model = model
        self.index = index
        self.status_model = status_model
        self.var = IntVar()
        self.var.set(model.get_checked())
        self.progress_var = IntVar()
        self.progress_status = ProgressStatus.undefined
        self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self.model.add_listener(self._model_changed)

    def _model_changed(self, new_status):
        model_state = self.model.get_checked()
        gui_state = self.var.get()
        if model_state is not gui_state:
            self.model.set_checked(gui_state)

    def refresh_check(self):
        if self.status_model.is_checked_force_reload():
            self.check_button.select()
        else:
            self.check_button.deselect()

    def is_checked(self):
        return self.var.get()

    def _progress_status_changed(self, new_status):
        self._refresh_progress()

    def _refresh_progress(self):
        status = self.status_model.get_status()
        if not status == self.progress_status:
            if status == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _check_changed(self):
        new_checked = self.var.get()
        if new_checked is not self.model.get_checked():
            self.model.set_checked(new_checked)
        if new_checked is not self.status_model.is_checked():
            self._notify(self.index, new_checked)
コード例 #3
0
class ProgressListBoxItem(Frame, Observable):
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

        # Create variables and initialise to zero
        self._checked_var = IntVar()
        self._progress_var = IntVar()
        self._checked_var.set(0)
        self._progress_var.set(0)
        self._current_gui_checked_state = CheckStatus.undefined
        self._current_gui_progress_state = ProgressStatus.undefined

        self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self._update()
        self._model.add_listener(self._model_changed)

    def _model_changed(self):
        self.update()

    def _update(self):
        # Update check status
        model_check_state = self._model.get_check_status()
        if model_check_state is not self._current_gui_checked_state:
            self._current_gui_checked_state = model_check_state
            # if self.status_model.is_checked_force_reload():
            if model_check_state:
                self.check_button.select()
            else:
                self.check_button.deselect()

        # Update progress status
        model_progress_state = self._model.get_progress_status
        if not model_progress_state == self._current_gui_progress_state:
            self._current_gui_progress_state = model_progress_state
            if model_progress_state == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _user_check_changed(self):
        new_checked = self._checked_var.get()
        if new_checked is not self._model.get_check_status():
            self._model.manual_set_checked(new_checked)
コード例 #4
0
ファイル: round.py プロジェクト: MalteBiermann/PGA
class FensterRound(Frame):
    def __init__(self, master, controller):
        super().__init__(master)
        self.controller = controller

        self.int_round = StringVar(value=self.controller.int_round)
        self.int_round.trace_add('write', self.callback_int)
        if self.controller.bool_roundActive:
            self.bool_roundActive = BooleanVar(value=1)
        else:
            self.bool_roundActive = BooleanVar(value=0)

        self.grid()
        self.chkb = Checkbutton(master, text="Runden", var=self.bool_roundActive, command=self.callback_chkb)
        self.chkb.grid(row=0, column=0, padx=3, pady=3, sticky="w")
        Label(master, text="Anzahl Nachkommastellen").grid(row=1, column=0, padx=3, pady=3, sticky="w")
        self.entry_round = Entry(master,textvariable=self.int_round, validate="all", validatecommand=self.callback_int, width=5)
        self.entry_round.grid(row=1, column=1, padx=3, pady=3, sticky="e")
        self.init_chkb()
        self.callback_chkb()

    def callback_chkb(self):
        if self.bool_roundActive.get() == 1:
            self.entry_round.config(state="normal")
            self.controller.bool_roundActive = True
        else:
            self.entry_round.config(state="disabled")
            self.controller.bool_roundActive = False

    def callback_int(self, *args):
        if self.int_round.get() != "":
            self.controller.int_round = int(self.int_round.get())

    def init_chkb(self):
        if self.controller.bool_roundActive:
            self.chkb.select()
        else:
            self.chkb.deselect()
コード例 #5
0
from tkinter import DISABLED
from tkinter import SUNKEN
from tkinter import HORIZONTAL
from tkinter import W
from tkinter import E
from PIL import ImageTk
from PIL import Image

root = Tk()
root.title("Checkboxes")
root.geometry("500x500")

var = StringVar()


def show():
    Label(root, text=var.get()).pack(pady=5)


checkbox = Checkbutton(root,
                       text="Check this box",
                       variable=var,
                       onvalue="On",
                       offvalue="Off")
checkbox.deselect()
checkbox.pack()

Button(root, text="Show Selection", command=show).pack()

root.mainloop()
コード例 #6
0
class GUI:
    currentCaptureState = False
    index = 0
    time = None
    config = None

    def __init__(self, config):
        GUI.config = config
        self.newWindow = None
        self.AlertShownDOS = 0
        self.AlertShownDDOS = 0
        self.AlertShownFTP = 0
        self.main_window = Tk()
        self.main_window.geometry('+{}+{}'.format(
            int(self.main_window.winfo_screenwidth() / 3 -
                self.main_window.winfo_reqwidth() / 2),
            int(self.main_window.winfo_screenheight() / 3 -
                self.main_window.winfo_reqheight() / 2)))
        self.main_window.geometry('750x300')
        self.main_window.title('Intrusion Detection System')
        style = ttk.Style()
        style.map("Treeview")
        self.loadTreeView()
        self.btnStartCapture = Button(self.main_window,
                                      text="Capture Packet",
                                      width=13,
                                      relief=RAISED,
                                      disabledforeground="black",
                                      bg='#856ff8',
                                      fg='white',
                                      font=('helvetica', 9, 'bold'),
                                      state=NORMAL,
                                      command=self.startCapture)
        self.btnStopCapture = Button(self.main_window,
                                     text="Stop Capture",
                                     width=13,
                                     relief=RAISED,
                                     disabledforeground="black",
                                     bg='#856ff8',
                                     fg='white',
                                     font=('helvetica', 9, 'bold'),
                                     state=DISABLED,
                                     command=self.stopCapture)
        self.btnConfig = Button(self.main_window,
                                text="Configuration",
                                relief=RAISED,
                                width=13,
                                disabledforeground="black",
                                bg='#856ff8',
                                fg='white',
                                font=('helvetica', 9, 'bold'),
                                state=NORMAL,
                                command=self.configWindow)
        self.btnStartCapture.pack(pady=10)
        self.btnStopCapture.pack(pady=10)
        self.btnConfig.pack(pady=10)
        self.btnStartCapture.place(x=270, y=240)
        self.btnStopCapture.place(x=400, y=240)
        self.btnConfig.place(x=530, y=240)
        self.labelText = StringVar()
        self.label = Label(self.main_window,
                           anchor=CENTER,
                           textvariable=self.labelText,
                           font=('Helvetica', 9, 'bold'),
                           relief=GROOVE,
                           fg="blue")
        self.labelText.set(" Number of Packets Captured: {}  ".format(
            GUI.index))
        self.label.place(x=25, y=243)
        self.main_window.protocol('WM_DELETE_WINDOW', self.onClosing)
        self.main_window.resizable(FALSE, FALSE)
        self.main_window.mainloop()

    def loadTreeView(self):
        self.frame = Frame(self.main_window)
        self.frame.pack(pady=20)
        self.tree_view = ttk.Treeview(self.frame,
                                      columns=('id', 'time', 'src_ip',
                                               'dst_ip', 'proto', 'info'),
                                      show='headings',
                                      height=8,
                                      selectmode="browse")
        self.tree_view.pack(side=LEFT)
        # Treeview Column Config
        self.tree_view.column('id', anchor=CENTER, width=50)
        self.tree_view.column('time', anchor=CENTER, width=80)
        # self.tree_view.column('src_mac', anchor=CENTER, width= 140)
        # self.tree_view.column('dst_mac', anchor=CENTER, width = 140)
        self.tree_view.column('src_ip', anchor=CENTER, width=140)
        self.tree_view.column('dst_ip', anchor=CENTER, width=140)
        self.tree_view.column('proto', anchor=CENTER, width=70)
        self.tree_view.column('info', anchor=CENTER)
        # Heading
        self.tree_view.heading('id', text='ID')
        self.tree_view.heading('time', text='Time')
        self.tree_view.heading('src_ip', text='Source IP')
        self.tree_view.heading('dst_ip', text='Destination IP')
        self.tree_view.heading('proto', text='Protocol')
        self.tree_view.heading('info', text='Info')
        # Scrollbar
        self.scroll_bar = Scrollbar(self.frame,
                                    orient=VERTICAL,
                                    command=self.tree_view.yview)
        self.scroll_bar.pack(side=RIGHT, fill=Y)
        # Attaching Scrollbar
        self.tree_view.config(yscrollcommand=self.scroll_bar.set)
        # Color for Attack Detection
        self.tree_view.tag_configure('attack', background='red')
        # More Details
        self.tree_view.bind("<Double-1>", self.OnDoubleClick)

    def capturing(self):
        while GUI.currentCaptureState and not self.thread.stopped():
            raw_packet, IPaddr = self.s.recvfrom(65536)
            ps_object = Sniffer(raw_packet, GUI.config, "WIN")
            capture = ps_object.capturePacket()
            if not bool(capture) and capture != None:
                row = ps_object.appendRowToGUI()
                self.appendData(GUI.index, GUI.index + 1, row)
                GUI.index = GUI.index + 1
            elif bool(capture):
                row = ps_object.appendRowToGUI()
                self.appendData(GUI.index, GUI.index + 1, row, ('attack', ))
                if capture[0] == "Distributed Denial of Service":
                    self.alertAttackDDOS(capture)
                if capture[0] == "Denial of Service":
                    self.alertAttackDOS(capture)
                if capture[0] == "FTP Brute Force Attack":
                    self.alertAttackFTP(capture)
                GUI.index = GUI.index + 1
            if GUI.config["logEnabled"] and not bool(
                    capture) and capture != None:
                ps_object.logPacketToFile(GUI.index + 1, self.filename)
            elif GUI.config["logEnabled"] and bool(capture):
                ps_object.logPacketToFile(GUI.index + 1, self.filename,
                                          "AttackPacket")
            try:
                self.labelText.set(" Number of Packets Captured: {}  ".format(
                    GUI.index))
            except:
                pass

    def startCapture(self):
        self.btnStartCapture.config(state=DISABLED)
        self.btnConfig.config(state=DISABLED)
        self.btnStopCapture.config(state=NORMAL)
        GUI.currentCaptureState = True
        # HOST = socket.gethostbyname(socket.gethostname())
        # HOST = socket.gethostbyname(socket.gethostname())
        HOST = socket.gethostbyname_ex(socket.gethostname())[2][0]
        # HOST = "192.168.1.23"
        print("Interface IP: %s" % HOST)
        # Create a raw socket and bind it to the public interface
        self.s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                               socket.IPPROTO_IP)
        self.s.bind((HOST, 0))
        # Include IP headers
        self.s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
        # Promiscuous mode - Enabled
        self.s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
        if GUI.config["logEnabled"] == True:
            format = "%d_%m_%Y_%H_%M_%S"
            self.filename = datetime.now().strftime(format) + ".txt"
            with open('./' + str(self.filename), 'w'):
                pass
        else:
            self.filename = "None.txt"
        if GUI.time == None:
            GUI.time = time.time()
        self.thread = StoppableThread(target=self.capturing, daemon=True)
        self.thread.start()

    def stopCapture(self):
        self.btnStartCapture.config(state=NORMAL)
        self.btnConfig.config(state=NORMAL)
        self.btnStopCapture.config(state=DISABLED)
        GUI.currentCaptureState = False
        self.s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
        self.thread.stop()

    def disableAll(self, mainAttack):
        if mainAttack == "DOS":
            self.dospingcheckbox.config(state=DISABLED)
            self.dossyncheckbox.config(state=DISABLED)
            self.dosudpcheckbox.config(state=DISABLED)
            self.dping_threshold.config(state=DISABLED)
            self.dping_timeinterval.config(state=DISABLED)
            self.dsyn_threshold.config(state=DISABLED)
            self.dsyn_timeinterval.config(state=DISABLED)
            self.dudp_threshold.config(state=DISABLED)
            self.dudp_timeinterval.config(state=DISABLED)
        elif mainAttack == "DDOS":
            self.ddospingcheckbox.config(state=DISABLED)
            self.ddossyncheckbox.config(state=DISABLED)
            self.ddosudpcheckbox.config(state=DISABLED)
            self.ddping_threshold.config(state=DISABLED)
            self.ddping_timeinterval.config(state=DISABLED)
            self.ddsyn_threshold.config(state=DISABLED)
            self.ddsyn_timeinterval.config(state=DISABLED)
            self.ddudp_threshold.config(state=DISABLED)
            self.ddudp_timeinterval.config(state=DISABLED)

    def enableAll(self, mainAttack):
        if mainAttack == "DOS":
            self.dospingcheckbox.config(state=NORMAL)
            self.dossyncheckbox.config(state=NORMAL)
            self.dosudpcheckbox.config(state=NORMAL)
            self.dping_threshold.config(state=NORMAL)
            self.dping_timeinterval.config(state=NORMAL)
            self.dsyn_threshold.config(state=NORMAL)
            self.dsyn_timeinterval.config(state=NORMAL)
            self.dudp_threshold.config(state=NORMAL)
            self.dudp_timeinterval.config(state=NORMAL)
        elif mainAttack == "DDOS":
            self.ddospingcheckbox.config(state=NORMAL)
            self.ddossyncheckbox.config(state=NORMAL)
            self.ddosudpcheckbox.config(state=NORMAL)
            self.ddping_threshold.config(state=NORMAL)
            self.ddping_timeinterval.config(state=NORMAL)
            self.ddsyn_threshold.config(state=NORMAL)
            self.ddsyn_timeinterval.config(state=NORMAL)
            self.ddudp_threshold.config(state=NORMAL)
            self.ddudp_timeinterval.config(state=NORMAL)

    def configWindow(self):
        if self.newWindow == None:
            self.main_window.withdraw()
            self.newWindow = Toplevel(self.main_window)
            self.newWindow.focus_force()
            self.newWindow.geometry('300x350')
            self.newWindow.geometry('+{}+{}'.format(
                int(self.newWindow.winfo_screenwidth() / 2 -
                    self.newWindow.winfo_reqwidth() / 2),
                int(self.newWindow.winfo_screenheight() / 3 -
                    self.newWindow.winfo_reqheight() / 2)))
            self.newWindow.title("Edit Configuration")
            self.newWindow.resizable(FALSE, FALSE)
            Label(self.newWindow,
                  text="Threshold",
                  font=('helvetica', 9, 'underline')).place(x=135, y=12)
            Label(self.newWindow,
                  text="Time Interval",
                  font=('helvetica', 9, 'underline')).place(x=210, y=12)
            self.newWindow.protocol('WM_DELETE_WINDOW', self.configClosed)
            # DOS checkbox
            self.var_dos = IntVar(self.newWindow)
            self.doscheckbox = Checkbutton(
                self.newWindow,
                font=('helvetica', 9, 'bold'),
                text='Denial of Service',
                variable=self.var_dos,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DOS"))
            self.doscheckbox.pack(pady=10)
            self.doscheckbox.place(x=10, y=10)
            # DOS Ping Checkbox & Fields
            self.var_dos_ping = IntVar(self.newWindow)
            self.dospingcheckbox = Checkbutton(
                self.newWindow,
                text='Ping Flood',
                variable=self.var_dos_ping,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DOS", "ping"))
            self.dospingcheckbox.pack(pady=10)
            self.dospingcheckbox.place(x=40, y=40)
            self.dping_threshold = Entry(self.newWindow,
                                         width=8,
                                         relief=GROOVE)
            self.dping_threshold.place(x=140, y=44)
            self.dping_timeinterval = Entry(self.newWindow,
                                            width=8,
                                            relief=GROOVE)
            self.dping_timeinterval.place(x=220, y=44)
            # DOS SYN Checkbox & Fields
            self.var_dos_syn = IntVar(self.newWindow)
            self.dossyncheckbox = Checkbutton(
                self.newWindow,
                text='SYN Flood',
                variable=self.var_dos_syn,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DOS", "syn"))
            self.dossyncheckbox.pack(pady=10)
            self.dossyncheckbox.place(x=40, y=70)
            self.dsyn_threshold = Entry(self.newWindow, width=8, relief=GROOVE)
            self.dsyn_threshold.place(x=140, y=74)
            self.dsyn_timeinterval = Entry(self.newWindow,
                                           width=8,
                                           relief=GROOVE)
            self.dsyn_timeinterval.place(x=220, y=74)
            # DOS UDP Checkbox & Fields
            self.var_dos_udp = IntVar(self.newWindow)
            self.dosudpcheckbox = Checkbutton(
                self.newWindow,
                text='UDP Flood',
                variable=self.var_dos_udp,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DOS", "udp"))
            self.dosudpcheckbox.pack(pady=10)
            self.dosudpcheckbox.place(x=40, y=100)
            self.dudp_threshold = Entry(self.newWindow, width=8, relief=GROOVE)
            self.dudp_threshold.place(x=140, y=104)
            self.dudp_timeinterval = Entry(self.newWindow,
                                           width=8,
                                           relief=GROOVE)
            self.dudp_timeinterval.place(x=220, y=104)
            self.dping_threshold.insert(END,
                                        GUI.config["DOS"]["ping"]["threshold"])
            self.dping_timeinterval.insert(
                END, GUI.config["DOS"]["ping"]["timeinterval"])
            self.dsyn_threshold.insert(END,
                                       GUI.config["DOS"]["syn"]["threshold"])
            self.dsyn_timeinterval.insert(
                END, GUI.config["DOS"]["syn"]["timeinterval"])
            self.dudp_threshold.insert(END,
                                       GUI.config["DOS"]["udp"]["threshold"])
            self.dudp_timeinterval.insert(
                END, GUI.config["DOS"]["udp"]["timeinterval"])
            if GUI.config["DOS"]["status"] == True:
                self.doscheckbox.select()
                if GUI.config["DOS"]["ping"]["status"] == True:
                    self.dospingcheckbox.select()
                    self.dping_threshold.config(state=NORMAL)
                    self.dping_timeinterval.config(state=NORMAL)
                else:
                    self.dping_threshold.config(state=DISABLED)
                    self.dping_timeinterval.config(state=DISABLED)
                if GUI.config["DOS"]["syn"]["status"] == True:
                    self.dossyncheckbox.select()
                    self.dsyn_threshold.config(state=NORMAL)
                    self.dsyn_timeinterval.config(state=NORMAL)
                else:
                    self.dsyn_threshold.config(state=DISABLED)
                    self.dsyn_timeinterval.config(state=DISABLED)
                if GUI.config["DOS"]["udp"]["status"] == True:
                    self.dosudpcheckbox.select()
                    self.dudp_threshold.config(state=NORMAL)
                    self.dudp_timeinterval.config(state=NORMAL)
                else:
                    self.dudp_threshold.config(state=DISABLED)
                    self.dudp_timeinterval.config(state=DISABLED)
            else:
                self.disableAll("DOS")
            # DDOS checkbox
            self.var_ddos = IntVar(self.newWindow)
            self.ddoscheckbox = Checkbutton(
                self.newWindow,
                font=('helvetica', 9, 'bold'),
                text='Distributed Denial of Service',
                variable=self.var_ddos,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DDOS"))
            self.ddoscheckbox.pack(pady=10)
            self.ddoscheckbox.place(x=10, y=130)
            # DDOS Ping Checkbox & Fields
            self.var_ddos_ping = IntVar(self.newWindow)
            self.ddospingcheckbox = Checkbutton(
                self.newWindow,
                text='Ping Flood',
                variable=self.var_ddos_ping,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DDOS", "ping"))
            self.ddospingcheckbox.pack(pady=10)
            self.ddospingcheckbox.place(x=40, y=160)
            self.ddping_threshold = Entry(self.newWindow,
                                          width=8,
                                          relief=GROOVE)
            self.ddping_threshold.place(x=140, y=164)
            self.ddping_timeinterval = Entry(self.newWindow,
                                             width=8,
                                             relief=GROOVE)
            self.ddping_timeinterval.place(x=220, y=164)
            # DDOS SYN Checkbox & Fields
            self.var_ddos_syn = IntVar(self.newWindow)
            self.ddossyncheckbox = Checkbutton(
                self.newWindow,
                text='SYN Flood',
                variable=self.var_ddos_syn,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DDOS", "syn"))
            self.ddossyncheckbox.pack(pady=10)
            self.ddossyncheckbox.place(x=40, y=190)
            self.ddsyn_threshold = Entry(self.newWindow,
                                         width=8,
                                         relief=GROOVE)
            self.ddsyn_threshold.place(x=140, y=194)
            self.ddsyn_timeinterval = Entry(self.newWindow,
                                            width=8,
                                            relief=GROOVE)
            self.ddsyn_timeinterval.place(x=220, y=194)
            # DDOS UDP Checkbox & Fields
            self.var_ddos_udp = IntVar(self.newWindow)
            self.ddosudpcheckbox = Checkbutton(
                self.newWindow,
                text='UDP Flood',
                variable=self.var_ddos_udp,
                onvalue=1,
                offvalue=0,
                command=lambda: self.configAttack("DDOS", "udp"))
            self.ddosudpcheckbox.pack(pady=10)
            self.ddosudpcheckbox.place(x=40, y=220)
            self.ddudp_threshold = Entry(self.newWindow,
                                         width=8,
                                         relief=GROOVE)
            self.ddudp_threshold.place(x=140, y=224)
            self.ddudp_timeinterval = Entry(self.newWindow,
                                            width=8,
                                            relief=GROOVE)
            self.ddudp_timeinterval.place(x=220, y=224)
            self.ddping_threshold.insert(
                END, GUI.config["DDOS"]["ping"]["threshold"])
            self.ddping_timeinterval.insert(
                END, GUI.config["DDOS"]["ping"]["timeinterval"])
            self.ddsyn_threshold.insert(END,
                                        GUI.config["DDOS"]["syn"]["threshold"])
            self.ddsyn_timeinterval.insert(
                END, GUI.config["DDOS"]["syn"]["timeinterval"])
            self.ddudp_threshold.insert(END,
                                        GUI.config["DDOS"]["udp"]["threshold"])
            self.ddudp_timeinterval.insert(
                END, GUI.config["DDOS"]["udp"]["timeinterval"])
            if GUI.config["DDOS"]["status"] == True:
                self.ddoscheckbox.select()
                if GUI.config["DDOS"]["ping"]["status"] == True:
                    self.ddospingcheckbox.select()
                    self.ddping_threshold.config(state=NORMAL)
                    self.ddping_timeinterval.config(state=NORMAL)
                else:
                    self.ddping_threshold.config(state=DISABLED)
                    self.ddping_timeinterval.config(state=DISABLED)
                if GUI.config["DDOS"]["syn"]["status"] == True:
                    self.ddossyncheckbox.select()
                    self.ddsyn_threshold.config(state=NORMAL)
                    self.ddsyn_timeinterval.config(state=NORMAL)
                else:
                    self.ddsyn_threshold.config(state=DISABLED)
                    self.ddsyn_timeinterval.config(state=DISABLED)
                if GUI.config["DDOS"]["udp"]["status"] == True:
                    self.ddosudpcheckbox.select()
                    self.ddudp_threshold.config(state=NORMAL)
                    self.ddudp_timeinterval.config(state=NORMAL)
                else:
                    self.ddudp_threshold.config(state=DISABLED)
                    self.ddudp_timeinterval.config(state=DISABLED)
            else:
                self.disableAll("DDOS")
            # FTP Brute Force
            self.var_ftp = IntVar(self.newWindow)
            self.ftpcheckbox = Checkbutton(self.newWindow,
                                           font=('helvetica', 9, 'bold'),
                                           text='FTP Brute Force',
                                           variable=self.var_ftp,
                                           onvalue=1,
                                           offvalue=0,
                                           command=self.configFTPAttack)
            self.ftpcheckbox.pack(pady=10)
            self.ftpcheckbox.place(x=10, y=250)
            self.ftp_threshold = Entry(self.newWindow, width=8, relief=GROOVE)
            self.ftp_threshold.place(x=140, y=254)
            self.ftp_timeinterval = Entry(self.newWindow,
                                          width=8,
                                          relief=GROOVE)
            self.ftp_timeinterval.place(x=220, y=254)
            self.ftp_threshold.insert(END, GUI.config["FTP"]["threshold"])
            self.ftp_timeinterval.insert(END,
                                         GUI.config["FTP"]["timeinterval"])
            if GUI.config["FTP"]["status"] == True:
                self.ftpcheckbox.select()
                self.ftp_threshold.config(state=NORMAL)
                self.ftp_timeinterval.config(state=NORMAL)
            else:
                self.ftpcheckbox.deselect()
                self.ftp_threshold.config(state=DISABLED)
                self.ftp_timeinterval.config(state=DISABLED)
            # Packet Log
            self.dumy_var = IntVar(self.newWindow)
            self.checkbox = Checkbutton(self.newWindow,
                                        font=('helvetica', 9, 'bold'),
                                        text='Log Packets',
                                        variable=self.dumy_var,
                                        onvalue=1,
                                        offvalue=0,
                                        command=self.updateLogState)
            self.checkbox.pack(pady=10)
            self.checkbox.place(x=10, y=280)
            if GUI.config["logEnabled"] == True:
                self.checkbox.select()
            self.newWindow.mainloop()

    def configAttack(self, mainAttack, type=None):
        if mainAttack == "DOS" and type == None:
            if self.var_dos.get() == 1:
                GUI.config[mainAttack]["ping"]["status"] = True
                GUI.config[mainAttack]["syn"]["status"] = True
                GUI.config[mainAttack]["udp"]["status"] = True
                self.dospingcheckbox.select()
                self.dossyncheckbox.select()
                self.dosudpcheckbox.select()
                GUI.config[mainAttack]["status"] = True
                self.enableAll("DOS")
            else:
                GUI.config[mainAttack]["ping"]["status"] = False
                GUI.config[mainAttack]["syn"]["status"] = False
                GUI.config[mainAttack]["udp"]["status"] = False
                self.dospingcheckbox.deselect()
                self.dossyncheckbox.deselect()
                self.dosudpcheckbox.deselect()
                GUI.config[mainAttack]["status"] = False
                self.disableAll("DOS")
        elif mainAttack == "DOS" and type == "ping":
            if self.var_dos_ping.get() == 1:
                GUI.config[mainAttack][type]["status"] = True
                self.dping_threshold.config(state=NORMAL)
                self.dping_timeinterval.config(state=NORMAL)
            else:
                GUI.config[mainAttack][type]["status"] = False
                self.dping_threshold.config(state=DISABLED)
                self.dping_timeinterval.config(state=DISABLED)
        elif mainAttack == "DOS" and type == "syn":
            if self.var_dos_syn.get() == 1:
                GUI.config[mainAttack][type]["status"] = True
                self.dsyn_threshold.config(state=NORMAL)
                self.dsyn_timeinterval.config(state=NORMAL)
            else:
                GUI.config[mainAttack][type]["status"] = False
                self.dsyn_threshold.config(state=DISABLED)
                self.dsyn_timeinterval.config(state=DISABLED)
        elif mainAttack == "DOS" and type == "udp":
            if self.var_dos_udp.get() == 1:
                GUI.config[mainAttack][type]["status"] = True
                self.dudp_threshold.config(state=NORMAL)
                self.dudp_timeinterval.config(state=NORMAL)
            else:
                GUI.config[mainAttack][type]["status"] = False
                self.dudp_threshold.config(state=DISABLED)
                self.dudp_timeinterval.config(state=DISABLED)
        elif mainAttack == "DDOS" and type == None:
            if self.var_ddos.get() == 1:
                GUI.config[mainAttack]["ping"]["status"] = True
                GUI.config[mainAttack]["syn"]["status"] = True
                GUI.config[mainAttack]["udp"]["status"] = True
                self.ddospingcheckbox.select()
                self.ddossyncheckbox.select()
                self.ddosudpcheckbox.select()
                GUI.config[mainAttack]["status"] = True
                self.enableAll("DDOS")
            else:
                GUI.config[mainAttack]["ping"]["status"] = False
                GUI.config[mainAttack]["syn"]["status"] = False
                GUI.config[mainAttack]["udp"]["status"] = False
                self.ddospingcheckbox.deselect()
                self.ddossyncheckbox.deselect()
                self.ddosudpcheckbox.deselect()
                GUI.config[mainAttack]["status"] = False
                self.disableAll("DDOS")
        elif mainAttack == "DDOS" and type == "ping":
            if self.var_ddos_ping.get() == 1:
                GUI.config[mainAttack][type]["status"] = True
                self.ddping_threshold.config(state=NORMAL)
                self.ddping_timeinterval.config(state=NORMAL)
            else:
                GUI.config[mainAttack][type]["status"] = False
                self.ddping_threshold.config(state=DISABLED)
                self.ddping_timeinterval.config(state=DISABLED)
        elif mainAttack == "DDOS" and type == "syn":
            if self.var_ddos_syn.get() == 1:
                GUI.config[mainAttack][type]["status"] = True
                self.ddsyn_threshold.config(state=NORMAL)
                self.ddsyn_timeinterval.config(state=NORMAL)
            else:
                GUI.config[mainAttack][type]["status"] = False
                self.ddsyn_threshold.config(state=DISABLED)
                self.ddsyn_timeinterval.config(state=DISABLED)
        elif mainAttack == "DDOS" and type == "udp":
            if self.var_ddos_udp.get() == 1:
                GUI.config[mainAttack][type]["status"] = True
                self.ddudp_threshold.config(state=NORMAL)
                self.ddudp_timeinterval.config(state=NORMAL)
            else:
                GUI.config[mainAttack][type]["status"] = False
                self.ddudp_threshold.config(state=DISABLED)
                self.ddudp_timeinterval.config(state=DISABLED)

    def configFTPAttack(self):
        if self.var_ftp.get() == 1:
            GUI.config["FTP"]["status"] = True
            self.ftpcheckbox.select()
            self.ftp_threshold.config(state=NORMAL)
            self.ftp_timeinterval.config(state=NORMAL)
        else:
            GUI.config["FTP"]["status"] = False
            self.ftpcheckbox.deselect()
            self.ftp_threshold.config(state=DISABLED)
            self.ftp_timeinterval.config(state=DISABLED)

    def configClosed(self):
        try:
            temp = GUI.config
            temp["DOS"]["ping"]["threshold"] = int(self.dping_threshold.get())
            temp["DOS"]["ping"]["timeinterval"] = int(
                self.dping_timeinterval.get())
            temp["DOS"]["syn"]["threshold"] = int(self.dsyn_threshold.get())
            temp["DOS"]["syn"]["timeinterval"] = int(
                self.dsyn_timeinterval.get())
            temp["DOS"]["udp"]["threshold"] = int(self.dudp_threshold.get())
            temp["DOS"]["udp"]["timeinterval"] = int(
                self.dudp_timeinterval.get())
            temp["DDOS"]["ping"]["threshold"] = int(
                self.ddping_threshold.get())
            temp["DDOS"]["ping"]["timeinterval"] = int(
                self.ddping_timeinterval.get())
            temp["DDOS"]["syn"]["threshold"] = int(self.ddsyn_threshold.get())
            temp["DDOS"]["syn"]["timeinterval"] = int(
                self.ddsyn_timeinterval.get())
            temp["DDOS"]["udp"]["threshold"] = int(self.ddudp_threshold.get())
            temp["DDOS"]["udp"]["timeinterval"] = int(
                self.ddudp_timeinterval.get())
            temp["FTP"]["threshold"] = int(self.ftp_threshold.get())
            temp["FTP"]["timeinterval"] = int(self.ftp_timeinterval.get())
            GUI.config = temp
        except:
            pass
        with open('./Config.json', 'w') as file:
            json.dump(GUI.config, file)
        self.newWindow.destroy()
        self.main_window.deiconify()
        self.newWindow = None

    def alertAttackDOS(self, display):
        if self.AlertShownDOS == 0:
            mailer = Mailer(GUI.config["Mail"])
            mailer.send(
                "Alert! Denial of Service detected from \nIP ~ {}\nType ~ {} Flood!"
                .format(display[1], display[2].upper()))
            self.alertdos = Tk()
            self.alertdos.title(display[0])
            self.alertdos.geometry("350x50")
            self.alertdos.geometry('+{}+{}'.format(
                int(self.alertdos.winfo_screenwidth() / 2.3 -
                    self.alertdos.winfo_reqwidth() / 2),
                int(self.alertdos.winfo_screenheight() / 2 -
                    self.alertdos.winfo_reqheight() / 2)))
            self.alertdos.winfo_toplevel()
            self.alertdos.focus_force()
            Label(
                self.alertdos,
                anchor=CENTER,
                text=
                "Alert! Denial of Service detected from IP: {}\nType: {} Flood!"
                .format(display[1], display[2].upper()),
                font=('helvetica', 9)).pack()
            self.alertdos.protocol('WM_DELETE_WINDOW', self.alertdosClosed)
            self.alertdos.mainloop()

    def alertdosClosed(self):
        self.alertdos.destroy()
        self.AlertShownDOS = 1

    def alertAttackDDOS(self, display):
        if self.AlertShownDDOS == 0:
            mailer = Mailer(GUI.config["Mail"])
            mailer.send(
                "Alert! Distributed Denial of Service detected from \nIP's ~ {}\nType ~ {} Flood!"
                .format(', '.join(list(display[1])), display[2].upper()))
            self.alertddos = Tk()
            self.alertddos.title(display[0])
            self.alertddos.geometry("400x50")
            self.alertddos.geometry('+{}+{}'.format(
                int(self.alertddos.winfo_screenwidth() / 2.3 -
                    self.alertddos.winfo_reqwidth() / 2),
                int(self.alertddos.winfo_screenheight() / 2 -
                    self.alertddos.winfo_reqheight() / 2)))
            self.alertddos.winfo_toplevel()
            self.alertddos.focus_force()
            Label(
                self.alertddos,
                anchor=CENTER,
                text=
                "Alert! Distributed Denial of Service detected from \nIP's: {}\nType: {} Flood!"
                .format(', '.join(list(display[1])), display[2].upper()),
                font=('helvetica', 9)).pack()
            self.alertddos.protocol('WM_DELETE_WINDOW', self.alertddosClosed)
            self.alertddos.mainloop()

    def alertddosClosed(self):
        self.alertddos.destroy()
        self.AlertShownDDOS = 1

    def alertAttackFTP(self, display):
        if self.AlertShownFTP == 0:
            mailer = Mailer(GUI.config["Mail"])
            mailer.send(
                "Alert! FTP Login-Brute Force Attack detected from \nIP ~ {}".
                format(display[1]))
            self.alertftp = Tk()
            self.alertftp.title(display[0])
            self.alertftp.geometry("350x50")
            self.alertftp.geometry('+{}+{}'.format(
                int(self.alertftp.winfo_screenwidth() / 2.3 -
                    self.alertftp.winfo_reqwidth() / 2),
                int(self.alertftp.winfo_screenheight() / 2 -
                    self.alertftp.winfo_reqheight() / 2)))
            self.alertftp.winfo_toplevel()
            self.alertftp.focus_force()
            Label(
                self.alertftp,
                anchor=CENTER,
                text=
                "Alert! FTP Login-Brute Force Attack detected from \nIP: {}!".
                format(display[1]),
                font=('helvetica', 9)).pack()
            self.alertftp.protocol('WM_DELETE_WINDOW', self.alertftpClosed)
            self.alertftp.mainloop()

    def alertftpClosed(self):
        self.alertftp.destroy()
        self.AlertShownFTP = 1

    def appendData(self, currentIndex, currentID, value_list, tags=()):
        try:
            value_list.insert(1, "{:.4f}".format(time.time() - GUI.time))
            self.tree_view.insert(parent='',
                                  index=currentIndex,
                                  iid=currentID,
                                  values=value_list,
                                  tags=tags)
        except:
            pass

    def OnDoubleClick(self, event):
        item_selected = self.tree_view.identify('item', event.x, event.y)
        selectedID = int(self.tree_view.item(item_selected, "values")[0])
        with open("./PacketLog.json", 'r') as file:
            storedData = json.load(file)
        selectedPacket = [
            x for x in storedData["Packets"] if x["pacID"] == selectedID
        ][0]
        if selectedPacket["protocol"] == 1:
            TYPE_STR = {8: "Request", 0: "Reply", 3: "Error"}
            message = """Packet ID: {}
Version: {}
Header Length: {} bytes
Time to Live: {} seconds
Protocol: {}
Source IP Address: {}
Destination IP Address: {}
Type: {} - {}
Code: {}
Sequence Number: {}""".format(
                selectedPacket["pacID"], selectedPacket['version'],
                selectedPacket['header_length'],
                selectedPacket['time_to_live'], selectedPacket['protocol'],
                selectedPacket['src_ip_addr'], selectedPacket['dest_ip_addr'],
                selectedPacket['type_icmp'],
                TYPE_STR[selectedPacket['type_icmp']], selectedPacket['code'],
                selectedPacket['sequence_number'])
        elif selectedPacket["protocol"] == 6:
            message = """Packet ID: {}
Version: {}
Header Length: {} bytes
Time to Live: {} seconds
Protocol: {}
Source IP Address: {}
Destination IP Address: {}
Source Port: {}
Destination Port: {}
Sequence Number: {}
Acknowlegdement Number: {}
Header Length:{} Bytes
URG Flag: {}
ACK Flag: {}
PSH Flag: {}
RST Flag: {}
SYN Flag: {}
FIN Flag: {}""".format(
                selectedPacket["pacID"], selectedPacket['version'],
                selectedPacket['header_length'],
                selectedPacket['time_to_live'], selectedPacket['protocol'],
                selectedPacket['src_ip_addr'], selectedPacket['dest_ip_addr'],
                selectedPacket['src_port'], selectedPacket['dest_port'],
                selectedPacket['seq_number'], selectedPacket['ack_number'],
                selectedPacket['header_length_tcp'],
                selectedPacket['URG_Flag'], selectedPacket['ACK_Flag'],
                selectedPacket['PSH_Flag'], selectedPacket['RST_Flag'],
                selectedPacket['SYN_Flag'], selectedPacket['FIN_Flag'])
        elif selectedPacket["protocol"] == 17:
            message = """Packet ID: {}
Version: {}
Header Length: {} bytes
Time to Live: {} seconds
Protocol: {}
Source IP Address: {}
Destination IP Address: {}
Source Port: {}
Destination Port: {}
Data Length:{} Bits""".format(
                selectedPacket["pacID"], selectedPacket['version'],
                selectedPacket['header_length'],
                selectedPacket['time_to_live'], selectedPacket['protocol'],
                selectedPacket['src_ip_addr'], selectedPacket['dest_ip_addr'],
                selectedPacket['src_port'], selectedPacket['dest_port'],
                selectedPacket['UDP_len'])
        else:
            message = "None"
        messagebox.showinfo("Selected Packet", message)

    def updateLogState(self):
        if self.dumy_var.get() == 1:
            GUI.config["logEnabled"] = True
        else:
            GUI.config["logEnabled"] = False

    def onClosing(self):
        self.main_window.withdraw()
        sys.exit(0)
コード例 #7
0
class UI:
    box_colors = {'fill': 'red', 'outline': 'red'}
    line_color = 'red'
    corner_radius = 2

    def __init__(self, root):
        # toolbar stuff
        # https://www.youtube.com/watch?v=AYOs78NjYfc

        # set up window
        self.root = root
        self.root.geometry('650x400')
        # self.root.resizable(width=False, height=False)
        self.root.title('BrilliantImagery')
        self.root.iconbitmap(resource_path() / 'brilliantimagery_ui' /
                             'logo.ico')

        self.sequence = None

        self.canvas = None
        self.image = None
        self.point1 = ()
        self.point2 = ()
        self.last_points = ((), ())
        self.files_last_parsed = None

        self._make_menu_bar()

        # set up tabs
        self.tab_control = ttk.Notebook(self.root)
        self._make_ramp_stabilize_tab()
        self._make_renderer_tab()

    def _make_menu_bar(self):
        def quite_app():
            self.root.quit()

        self.menu = Menu(self.root)

        # ------ File Menu ------
        file_menu = Menu(self.menu, tearoff=0)
        file_menu.add_command(label='Open Project',
                              accelerator='Ctrl+O',
                              command=self._open_project)
        file_menu.add_command(label='Save Project',
                              accelerator='Ctrl+S',
                              command=self._save_project)
        file_menu.add_separator()
        file_menu.add_command(label='Exit', command=quite_app)
        self.menu.add_cascade(label='File', menu=file_menu)

        # --------- Help Menu --------
        help_menu = Menu(self.menu, tearoff=0)
        help_menu.add_command(label='About',
                              command=lambda: messagebox.showinfo(
                                  'About', f"BrilliantImagery UI\n\n"
                                  f"Version: "
                                  f"{brilliantimagery.__version__}"
                                  f"\nGo to brilliantimagery.org "
                                  f"for more info."))
        self.menu.add_cascade(label='Help', menu=help_menu)

        self.root.config(menu=self.menu)

    def _make_renderer_tab(self):
        tab_renderer = ttk.Frame(self.tab_control)
        self.tab_control.add(tab_renderer, text='Renderer')
        self.tab_control.pack(expand=1, fill='both')

        interface_frame = Frame(tab_renderer)
        interface_frame.pack(side=TOP, anchor=W)
        Label(interface_frame, text='Image Path:').grid(row=0,
                                                        column=0,
                                                        padx=10,
                                                        pady=10)
        file_entry = Entry(interface_frame, width=70)
        file_entry.grid(row=0, column=1)
        folder_button = Button(interface_frame,
                               text='File',
                               command=lambda: self._open_image(file_entry))
        folder_button.grid(row=0, column=2, padx=10)

        image_frame = Frame(tab_renderer)
        image_frame.pack(expand=1, fill='both')
        self.renderer_canvas = Canvas(image_frame,
                                      width=500,
                                      height=350,
                                      scrollregion=(0, 0, 500, 350))
        horizontal_scroll_bar = Scrollbar(image_frame, orient=HORIZONTAL)
        vertical_scroll_bar = Scrollbar(image_frame, orient=VERTICAL)
        horizontal_scroll_bar.pack(side=BOTTOM, fill=X)
        vertical_scroll_bar.pack(side=RIGHT, fill=Y)
        horizontal_scroll_bar.config(command=self.renderer_canvas.xview)
        vertical_scroll_bar.config(command=self.renderer_canvas.yview)

        self.renderer_canvas.pack(side=LEFT, expand=True, fill=BOTH)
        self.renderer_canvas.config(xscrollcommand=horizontal_scroll_bar.set,
                                    yscrollcommand=vertical_scroll_bar.set)

    def _make_ramp_stabilize_tab(self):
        # set up tab
        tab_ramp_stabilize = ttk.Frame(self.tab_control)
        self.tab_control.add(tab_ramp_stabilize, text='Ramp & Stabilize')
        self.tab_control.pack(expand=1, fill='both')
        # self.tab_control.grid(row=0, column=0)

        # make image canvas
        self.canvas = Canvas(tab_ramp_stabilize, width=255, height=255)
        self.canvas.grid(row=0, column=0, columnspan=2, rowspan=4)
        self.canvas.bind('<Button-1>', self._process_canvas_click)

        # make function checkboxes
        procedures_frame = LabelFrame(tab_ramp_stabilize,
                                      text='Operations To Perform')
        procedures_frame.grid(row=0, column=2, padx=5, pady=5, sticky=NW)

        self.ramp = IntVar()
        self.ramp_checkbutton = Checkbutton(procedures_frame,
                                            text="Ramp Linear Properties",
                                            variable=self.ramp)
        self.ramp_checkbutton.grid(row=0, column=0, sticky=W)

        self.exposure = IntVar()
        self.exposure_checkbutton = Checkbutton(procedures_frame,
                                                text="Ramp Exposure",
                                                variable=self.exposure)
        self.exposure_checkbutton.grid(row=1, column=0, sticky=W)

        self.stabilize = IntVar()
        self.stabilize_checkbutton = Checkbutton(procedures_frame,
                                                 text="Stabilize",
                                                 variable=self.stabilize)
        self.stabilize_checkbutton.grid(row=2, column=0, sticky=W)

        # Reload and reuse
        reuse_frame = LabelFrame(tab_ramp_stabilize, text='Data Reuse')
        reuse_frame.grid(row=1, column=2, padx=5, pady=5, sticky=NW)
        self.reuse_misalignment = IntVar()
        self.reuse_mis_checkbutton = Checkbutton(
            reuse_frame,
            text='Use Previously Calculated Misalignments',
            variable=self.reuse_misalignment)
        self.reuse_mis_checkbutton.grid(row=0, column=0, sticky=NW)
        self.reuse_brightness = IntVar()
        self.reuse_bright_checkbutton = Checkbutton(
            reuse_frame,
            text='Use Previously Calculated Brightnesses',
            variable=self.reuse_brightness)
        self.reuse_bright_checkbutton.grid(row=1, column=0, sticky=NW)

        Button(reuse_frame,
               text='Reload Image',
               command=lambda:
               (self._load_sequence(self.folder_entry.get()))).grid(row=2,
                                                                    column=0,
                                                                    sticky=NW,
                                                                    padx=5,
                                                                    pady=5)

        # set up folder selector
        folder_selector_row = 4
        folder_selector_column = 0
        Label(tab_ramp_stabilize,
              text='Sequence Folder:').grid(row=folder_selector_row,
                                            column=folder_selector_column,
                                            padx=10)
        self.folder_entry = Entry(tab_ramp_stabilize, width=70)
        self.folder_entry.grid(row=folder_selector_row,
                               column=folder_selector_column + 1,
                               columnspan=2)
        self.folder_entry.bind(
            '<FocusOut>',
            lambda e: self._load_sequence(self.folder_entry.get()))
        folder_button = Button(tab_ramp_stabilize,
                               text='Folder',
                               command=self._open_sequence)
        folder_button.grid(row=folder_selector_row,
                           column=folder_selector_column + 3,
                           sticky=W,
                           padx=10)

        process_button = Button(
            tab_ramp_stabilize,
            text='Process',
            command=lambda: self._process_sequence(message_finished.get()))
        process_button.grid(row=folder_selector_row + 1,
                            column=0,
                            sticky=W,
                            padx=10,
                            pady=10)

        message_finished = IntVar()
        Checkbutton(tab_ramp_stabilize,
                    text="Show MessageBox when done.",
                    variable=message_finished).grid(row=folder_selector_row +
                                                    1,
                                                    column=1,
                                                    sticky=W)

    def _process_sequence(self, show_finished):
        if not self._validate_selections():
            return

        self._maybe_reset_misalignment_brightness()

        rectangle = (min(self.point1[0],
                         self.point2[0]), min(self.point1[1], self.point2[1]),
                     max(self.point1[0],
                         self.point2[0]), max(self.point1[1], self.point2[1]))
        rectangle = [
            rectangle[0] / self.image.width(),
            rectangle[1] / self.image.height(),
            rectangle[2] / self.image.width(),
            rectangle[3] / self.image.height()
        ]

        last_modified = files_last_updated(self.sequence.path)
        if last_modified > self.files_last_parsed:
            self.sequence.parse_sequence()
            self.files_last_parsed = time.time()

        if self.ramp.get(
        ) and not self.exposure.get() and not self.stabilize.get():
            self.sequence.ramp_minus_exmpsure()
        elif not self.ramp.get() and self.exposure.get(
        ) and not self.stabilize.get():
            self.sequence.ramp_exposure(rectangle)
        elif not self.ramp.get() and not self.exposure.get(
        ) and self.stabilize.get():
            self.sequence.stabilize(rectangle)
        elif self.ramp.get() and self.exposure.get(
        ) and not self.stabilize.get():
            self.sequence.ramp(rectangle)
        elif not self.ramp.get() and self.exposure.get(
        ) and self.stabilize.get():
            self.sequence.ramp_exposure_and_stabilize(rectangle)
        elif self.ramp.get(
        ) and not self.exposure.get() and self.stabilize.get():
            self.sequence.ramp_minus_exposure_and_stabilize(rectangle)
        elif self.ramp.get() and self.exposure.get() and self.stabilize.get():
            self.sequence.ramp_and_stabilize(rectangle)

        self.sequence.save()

        if self.exposure.get():
            self.reuse_bright_checkbutton.select()
        if self.stabilize.get():
            self.reuse_mis_checkbutton.select()

        self.last_points = (self.point1, self.point2)

        if show_finished:
            messagebox.showinfo('Done', 'All done!')

        print('Done Processing!')

    def _maybe_reset_misalignment_brightness(self):
        folder = Path(self.folder_entry.get())
        files = [
            f.name for f in folder.iterdir()
            if (folder / f).is_file() and f.suffix.lower() == '.dng'
        ]

        if (self.point1, self.point2) != self.last_points:
            self.sequence.set_misalignments({f: None for f in files})
            self.sequence.set_brightnesses({f: None for f in files})
        else:
            if not self.reuse_misalignment.get():
                self.sequence.set_misalignments({f: None for f in files})
            if not self.reuse_brightness.get():
                self.sequence.set_brightnesses({f: None for f in files})

    def _open_sequence(self):
        folder = self._open_folder(self.folder_entry)
        if folder:
            self._load_sequence(folder)

    def _load_sequence(self, folder):
        if not Path(folder).is_dir():
            return
        if not self.sequence or folder != self.sequence.path:
            self.sequence = Sequence(folder)
            self.files_last_parsed = time.time()

        image = self.sequence.get_reference_image(index_order='yxc')

        image = PIL.Image.fromarray(image.astype('uint8'), mode='RGB')
        size = (255, int(255 * image.width / image.height))
        image.thumbnail(size, Image.ANTIALIAS)

        self.image = PhotoImage(image)

        self._draw_image()

    def _open_folder(self, entry):
        folder = filedialog.askdirectory(title='Select A Sequence Folder')
        if not folder:
            return

        self._set_text(entry, folder)
        return folder

    def _open_image(self, entry):
        file = self._open_file(entry)

        if not file:
            return
        dng = DNG(file)
        image_array = dng.get_image() * 255

        shape = image_array.shape
        image_array = np.reshape(image_array, image_array.size, 'C')
        image_array = np.reshape(image_array, (shape[2], shape[1], shape[0]),
                                 'F')

        image = PIL.Image.fromarray(image_array.astype('uint8'), mode='RGB')

        self.image_rendered = PhotoImage(image)
        self.renderer_canvas.create_image(self.image_rendered.width(),
                                          self.image_rendered.height(),
                                          image=self.image_rendered,
                                          anchor=SE)
        self.renderer_canvas.config(scrollregion=(0, 0, image.width,
                                                  image.height))

    def _open_file(self, entry):
        file = filedialog.askopenfilename(title='Select an Image to Render',
                                          filetypes=(('dng files', '*.dng'),
                                                     ('all files', '*.*')))
        if not file:
            return

        self._set_text(entry, file)
        return file

    def _set_text(self, entry, text):
        entry.delete(0, END)
        entry.insert(0, text)
        return

    def _process_canvas_click(self, click=None):
        if not self.image:
            return
        self._get_point(click)
        self._draw_image()
        if not self.point2:
            self.reuse_mis_checkbutton.deselect()
            self.reuse_bright_checkbutton.deselect()

    def _draw_image(self):
        if not self.image:
            return

        self.canvas.create_image(self.image.width(),
                                 self.image.height(),
                                 image=self.image,
                                 anchor=SE)

        if self.point1:
            self._draw_corner(self.point1)
        if self.point2:
            self._draw_corner(self.point2)
            self.canvas.create_rectangle(*self.point1,
                                         *self.point2,
                                         outline=UI.line_color)

    def _get_point(self, click):
        if not click:
            return
        if not self.point1:
            self.point1 = (click.x, click.y)
        elif not self.point2:
            self.point2 = (click.x, click.y)
        else:
            self.point1 = ()
            self.point2 = ()

    def _draw_corner(self, point):
        _point1 = (max(0, point[0] - UI.corner_radius),
                   max(0, point[1] - UI.corner_radius))
        _point2 = (min(self.image.width(), point[0] + UI.corner_radius),
                   min(self.image.height(), point[1] + UI.corner_radius))

        self.canvas.create_rectangle(*_point1, *_point2, **UI.box_colors)

    def _save_project(self):
        if self.sequence:
            misalignments = self.sequence.get_misalignments()
            brightnesses = self.sequence.get_brightnesses()
        else:
            misalignments = None
            brightnesses = None
        params = {
            'point1': self.point1,
            'point2': self.point2,
            'ramp': self.ramp.get(),
            'exposure': self.exposure.get(),
            'stabilize': self.stabilize.get(),
            'folder': self.folder_entry.get(),
            'misalignments': misalignments,
            'brightnesses': brightnesses,
        }
        params = json.dumps(params)

        file = filedialog.asksaveasfile(title='Save Project',
                                        mode='w',
                                        defaultextension='.bi',
                                        filetypes=[('BrilliantImagery Project',
                                                    '.bi'),
                                                   ("All Files", ".*")])
        if not file:
            return

        file.write(params)
        file.close()

    def _open_project(self):
        file = filedialog.askopenfile(title='Open Project',
                                      mode='r',
                                      defaultextension='.bi',
                                      filetypes=[('BrilliantImagery Project',
                                                  '.bi'), ("All Files", ".*")])
        if not file:
            return
        params = file.read()
        file.close()
        params = json.loads(params)

        self.point1 = params.get('point1')
        self.point2 = params.get('point2')
        self.last_points = (self.point1, self.point2)

        if params.get('ramp'):
            self.ramp_checkbutton.select()
        else:
            self.ramp_checkbutton.deselect()
        if params.get('exposure'):
            self.exposure_checkbutton.select()
        else:
            self.exposure_checkbutton.deselect()
        if params.get('stabilize'):
            self.stabilize_checkbutton.select()
        else:
            self.stabilize_checkbutton.deselect()

        folder = params.get('folder')
        self._set_text(self.folder_entry, folder)
        self._load_sequence(folder)

        misalignments = params.get('misalignments')
        brightnesses = params.get('brightnesses')

        if misalignments:
            self.sequence.set_misalignments(misalignments)
            if list(misalignments.values())[0] != None:
                self.reuse_mis_checkbutton.select()
        if brightnesses:
            self.sequence.set_brightnesses(brightnesses)
            if list(brightnesses.values())[0] != None:
                self.reuse_bright_checkbutton.select()

    def _validate_selections(self):
        if self.point1 and self.point2:
            rectangle = True
        else:
            rectangle = False

        if not self.folder_entry.get():
            messagebox.showerror('Oops!',
                                 'You need to specify a Sequence Folder.')
            return False

        if rectangle and (self.exposure.get() or self.stabilize.get()):
            return True
        elif self.reuse_brightness.get() and self.exposure.get():
            return True
        elif self.reuse_misalignment.get() and self.stabilize.get():
            return True
        elif self.ramp.get() and not (self.exposure.get()
                                      or self.stabilize.get()):
            return True

        messagebox.showerror(
            'Oops!',
            "You need to specify what to do (in the Operations to Perform box) "
            "and what information to use (either highlight a rectangle or select "
            "what info to reuse)")

        return False
コード例 #8
0
class entries(main, verify):
    def __init__(self, root):
        super().__init__(root)
        verify.__init__(self, root)

        self.name1 = Label(root,
                           text='First Name:',
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=80)
        self.name2 = Label(root,
                           text="Second Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=110)
        self.name3 = Label(root,
                           text="Third Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=140)
        self.name4 = Label(root,
                           text="Fourth Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=170)
        self.year = Label(root,
                          text='Year:',
                          bg='#2B2B2B',
                          fg='#B0B9D9',
                          font='bold 10').place(x=10, y=220)
        self.topic = Label(root,
                           text="Topic(s):",
                           bg='#2B2B2B',
                           fg='#F8D8C0',
                           font='bold 10').place(x=10, y=250)
        self.book = Label(root,
                          text="Book(s):",
                          bg='#2B2B2B',
                          fg='#F8D8C0',
                          font='bold 10').place(x=10, y=330)
        self.volume = Label(root,
                            text="Volume(s):",
                            bg='#2B2B2B',
                            fg='#B0D9D9',
                            font='bold 10').place(x=10, y=430)
        self.issue = Label(root,
                           text="Issue(s):",
                           bg='#2B2B2B',
                           fg='#B0D9D9',
                           font='bold 10').place(x=10, y=460)
        self.page = Label(root,
                          text="Page(s)",
                          bg='#2B2B2B',
                          fg='#B0D9D9',
                          font='bold 10').place(x=10, y=490)

        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=85, y=80)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=100, y=110)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=85, y=140)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=95, y=170)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=70, y=250)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=70, y=330)

        vname1 = root.register(self.name1_entry)
        vname2 = root.register(self.name2_entry)
        vname3 = root.register(self.name3_entry)
        vname4 = root.register(self.name4_entry)
        vyear = root.register(self.year_entry)
        vtopic = root.register(self.topic_entry)
        vbook = root.register(self.book_entry)
        vvolume = root.register(self.volume_entry)
        vissue = root.register(self.issue_entry)
        vpage = root.register(self.page_entry)

        self.iname1 = Entry(root,
                            validate="key",
                            validatecommand=(vname1, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname1.place(x=110, y=80)
        self.iname2 = Entry(root,
                            validate="key",
                            validatecommand=(vname2, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname2.place(x=110, y=110)
        self.iname3 = Entry(root,
                            validate="key",
                            validatecommand=(vname3, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname3.place(x=110, y=140)
        self.iname4 = Entry(root,
                            validate="key",
                            validatecommand=(vname4, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname4.place(x=110, y=170)
        self.year = Entry(root,
                          validate="key",
                          validatecommand=(vyear, '%P'),
                          width=20,
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(x=90, y=220)
        self.topic = Entry(root,
                           validate="key",
                           validatecommand=(vtopic, '%P'),
                           bg='#3C3F41',
                           fg='yellow',
                           relief=FLAT,
                           highlightbackground='#2B2B2B',
                           highlightthickness=0.5,
                           highlightcolor='black').place(width=304,
                                                         height=70,
                                                         x=90,
                                                         y=250)
        self.book = Entry(root,
                          validate="key",
                          validatecommand=(vbook, '%P'),
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(width=304,
                                                        height=70,
                                                        x=90,
                                                        y=330)
        self.volume = Entry(root,
                            validate="key",
                            validatecommand=(vvolume, '%P'),
                            width=20,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black').place(x=90, y=430)
        self.issue = Entry(root,
                           validate="key",
                           validatecommand=(vissue, '%P'),
                           width=20,
                           bg='#3C3F41',
                           fg='yellow',
                           relief=FLAT,
                           highlightbackground='#2B2B2B',
                           highlightthickness=0.5,
                           highlightcolor='black').place(x=90, y=460)
        self.page = Entry(root,
                          validate="key",
                          validatecommand=(vpage, '%P'),
                          width=20,
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(x=90, y=490)

        self.verify_name1.config(text='☐')
        self.verify_name2.config(text='☐')
        self.verify_name3.config(text='☐')
        self.verify_name4.config(text='☐')
        self.verify_year.config(text='☐')
        self.verify_volume.config(text='☐')
        self.verify_issue.config(text='☐')
        self.verify_page.config(text='☐')

        self.correctname1 = self.correctname2 = self.correctname3 = self.correctname4 = self.correcttopic = self.correctbook = self.correctyear = self.correctyear = self.correctissue = self.correctpage = ' '

    def name1_entry(self, name1):
        try:
            if name1 != None:
                self.name1 = name1
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname1 = APA.nameAPA(name1, self.name2, self.name3,
                                                self.name4)

                if self.name1 == '':
                    self.verify_name1.config(text='☐', state=DISABLED)

                else:
                    self.verify_name1.config(text='☑', state=NORMAL)

                if self.correctname1 != ' ':
                    if (self.correcttopic != ' ' or self.correctbook != ' '):
                        main.name_value = self.correctname1
                        self.submitbtn.config(state=NORMAL, relief=RAISED)

                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                print(self.correctname1)
                main.name_value = self.correctname1

                return True
            else:
                return False
        except IndexError:
            self.name1 = None
            return True

    def name2_entry(self, name2):
        try:
            if name2 != None:
                self.name2 = name2
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname2 = APA.nameAPA(self.name1, name2, self.name3,
                                                self.name4)
                if self.name2 == '':
                    self.verify_name2.config(text='☐', state=DISABLED)

                else:
                    self.verify_name2.config(text='☑', state=NORMAL)

                if self.correctname2 != ' ':
                    if (self.correcttopic != ' ' or self.correctbook != ' '):
                        main.name_value = self.correctname2
                        self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.name_value = self.correctname2
                print(self.correctname2)

                return True
            else:
                return False
        except IndexError:
            self.name2 = None
            return True

    def name3_entry(self, name3):
        try:
            if name3 != None:
                self.name3 = name3
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname3 = APA.nameAPA(self.name1, self.name2, name3,
                                                self.name4)
                if self.name3 == '':
                    self.verify_name3.config(text='☐', state=DISABLED)

                else:
                    self.verify_name3.config(text='☑', state=NORMAL)

                if (self.correcttopic != ' ' and self.correctbook != ' '):
                    main.name_value = self.correctname3
                    self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.name_value = self.correctname3
                print(self.correctname3)
                return True
            else:
                return False
        except IndexError:
            self.name3 = None
            return True

    def name4_entry(self, name4):
        try:
            if name4 != None:
                self.name4 = name4
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname4 = APA.nameAPA(self.name1, self.name2,
                                                self.name3, name4)
                if self.name4 == '':
                    self.verify_name4.config(text='☐', state=DISABLED)

                else:
                    self.verify_name4.config(text='☑', state=NORMAL)

                if (self.correcttopic != ' ' and self.correctbook != ' '):
                    main.name_value = self.correctname4
                    self.submitbtn.config(state=NORMAL, relief=RAISED)

                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.name_value = self.correctname4
                print(self.correctname4)
                return True
            else:
                return False
        except IndexError:
            self.name4 = None
            return True

    def year_entry(self, year):
        try:
            if year != None:
                main.year_value = ''
                self.year = year
                self.correctyear = APA.yearAPA(year)
                if self.correctyear == 'Invalid Year':
                    self.verify_year.config(text='☒',
                                            fg='#8B0000',
                                            state=NORMAL)
                else:
                    self.verify_year.config(text='☑', fg='green', state=NORMAL)
                    main.year_value = self.correctyear
                print(self.correctyear)

                self.year = ''
                return True
            else:
                return False
        except IndexError:
            self.verify_year.config(text='☐', state=DISABLED)
            return True

    def topic_entry(self, topic):
        try:
            if topic != None:
                self.topic = topic
                self.correcttopic = APA.topicAPA(topic)
                if self.correcttopic != 'Err(Low)':
                    if (self.correctname1 != ' ' or self.correctname2 != ' '
                            or self.correctname3 != ' '
                            or self.correctname4 != ' '):
                        if self.correctbook != ' ':
                            main.topic_value = self.correcttopic
                            self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.topic_value = self.correcttopic
                print(self.correcttopic)

                return True
            else:
                self.submitbtn.config(state=DISABLED)
                return False
        except IndexError:
            self.topic = None
            return True

    def book_entry(self, book):
        try:
            if book != None:
                self.book = book
                self.correctbook = APA.bookAPA(book)
                if self.correctbook != 'Err(Low)':
                    if (self.correctname1 != ' ' or self.correctname2 != ' '
                            or self.correctname3 != ' '
                            or self.correctname4 != ' '
                            and self.correcttopic != ' '):
                        main.book_value = self.correctbook
                        self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.book_value = self.correctbook
                print(self.correctbook)
                return True
            else:
                return False
        except:
            return True

    def volume_entry(self, volume):
        try:
            if volume != None:
                self.volume = volume
                self.correctvolume = APA.volumeAPA(volume)
                if self.correctvolume == 'Invalid Volume':
                    self.verify_volume.config(text='☒',
                                              fg='#8B0000',
                                              state=NORMAL)
                    main.volume_value = ''
                elif self.correctvolume == '':
                    self.verify_volume.config(text='☐', state=DISABLED)
                    main.volume_value = ''
                else:
                    self.verify_volume.config(text='☑',
                                              fg='green',
                                              state=NORMAL)
                    main.volume_value = self.correctvolume
                print(self.correctvolume)
                return True
            else:
                return False
        except IndexError:
            self.verify_volume.config(text='☐', state=DISABLED)
            return True

    def issue_entry(self, issue):
        try:
            if issue != None:
                self.issue = issue
                self.correctissue = APA.issueAPA(issue)
                if self.correctissue == 'Invalid Issue':
                    self.verify_issue.config(text='☒',
                                             fg='#8B0000',
                                             state=NORMAL)
                    main.issue_value = ''
                elif self.correctissue == '':
                    self.verify_issue.config(text='☐', state=DISABLED)
                    main.issue_value = ''
                else:
                    self.verify_issue.config(text='☑',
                                             fg='green',
                                             state=NORMAL)
                    main.issue_value = self.correctissue
                print(self.correctissue)
                return True
            else:
                return False
        except IndexError:
            return True

    def page_entry(self, page):
        try:
            if page != None:
                self.page = page
                self.correctpage = APA.pageAPA(page)
                if self.correctpage == 'Invalid Page':
                    self.verify_page.config(text='☒',
                                            fg='#8B0000',
                                            state=NORMAL)
                    main.page_value = ''
                elif self.correctpage == '':
                    self.verify_page.config(text='☐', state=DISABLED)
                    main.page_value = ''
                else:
                    self.verify_page.config(text='☑', fg='green', state=NORMAL)
                    main.page_value = self.correctpage
                print(self.correctpage)
                return True
            else:
                return False
        except IndexError:
            return True

    def enter_txt(self):
        if self.et_al == False:
            total_txt = main.name_value + main.year_value + main.topic_value + main.book_value + main.volume_value + main.issue_value + main.page_value + '\n' + '\n'
        elif self.et_al == True:
            total_txt = main.name_value + 'et.al. ' + main.year_value + main.topic_value + main.book_value + main.volume_value + main.issue_value + main.page_value + '\n' + '\n'
        APA_txt.set_txt(total_txt)
        APA_inputs.__init__(root)
        self.savebtn.config(state=NORMAL, relief=RAISED)

    def hide_names(self):

        self.et_al = True
        self.correctname1 = self.correctname2 = self.correctname3 = self.correctname4 = ' '
        self.name1 = self.iname1.get()
        APA_inputs.name1_entry(self.name1)
        self.iname2.config(state=DISABLED, disabledbackground='#4F4B41')
        self.iname3.config(state=DISABLED, disabledbackground='#4F4B41')
        self.iname4.config(state=DISABLED, disabledbackground='#4F4B41')
        self.etal = Checkbutton(root,
                                text='Et.al?',
                                bg='#2B2B2B',
                                fg='orange',
                                font='bold 12',
                                bd=0,
                                activebackground='#2B2B2B',
                                activeforeground='orange',
                                command=lambda: [APA_inputs.show_names()])
        self.etal.select()
        self.etal.place(x=110, y=195)

    def show_names(self):

        self.et_al = False
        self.iname2.config(state=NORMAL)
        self.iname3.config(state=NORMAL)
        self.iname4.config(state=NORMAL)

        self.name1 = self.iname1.get()
        self.name2 = self.iname2.get()
        self.name3 = self.iname3.get()
        self.name4 = self.iname4.get()

        APA_inputs.name1_entry(self.name1)
        APA_inputs.name2_entry(self.name2)
        APA_inputs.name3_entry(self.name3)
        APA_inputs.name4_entry(self.name4)

        self.etal = Checkbutton(root,
                                text='Et.al?',
                                bg='#2B2B2B',
                                fg='orange',
                                font='bold 12',
                                bd=0,
                                activebackground='#2B2B2B',
                                activeforeground='orange',
                                command=lambda: [APA_inputs.hide_names()])
        self.etal.deselect()
        self.etal.place(x=110, y=195)
コード例 #9
0
class ViewMac:
    main_view = ""
    current_mac = ""
    accepted_characters = [
        'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8',
        '9', '0', ':'
    ]

    def __init__(self, view, spoofing_status):
        self.main_view = view
        self.spoofing_status = spoofing_status
        self.build_window()
        self.popup_gen = PopUpWindow()
        self.set_spoofing_checkbutton()
        self.root.mainloop()

    def build_window(self):
        """
        Generates the window.

        :author: Pablo Sanz Alguacil
        """

        self.root = Toplevel()
        self.root.protocol("WM_DELETE_WINDOW", self.destroy_window)
        self.root.geometry('440x490')
        self.root.resizable(width=False, height=False)
        self.root.title('WiCC - Mac Changer Tools')

        # LABELFRAME - INFO
        self.labelframe_info = LabelFrame(self.root, text="")
        self.labelframe_info.pack(fill="both", expand="no", pady=15)

        # LABEL - INFO
        self.label_info = Label(
            self.labelframe_info,
            pady=15,
            text="In this window you can change your MAC as you want by"
            "\nusing one this options. A great power comes with a"
            "\ngreat responsibility")
        self.label_info.pack(side=TOP)

        # LABELFRAME - CUSTOM MAC
        self.labelframe_custom_mac = LabelFrame(self.root,
                                                text="Write custom MAC")
        self.labelframe_custom_mac.pack(fill="both", expand="no", pady=10)

        # LABEL - CUSTOM MAC
        self.label_custom_mac = Label(self.labelframe_custom_mac,
                                      text="Custom MAC: ")
        self.label_custom_mac.grid(column=1, row=0, padx=5)

        # ENTRY - CUSTOM MAC
        self.entry_custom_mac = ttk.Entry(self.labelframe_custom_mac)
        self.entry_custom_mac.grid(column=2, row=0, padx=8)
        self.entry_custom_mac.bind('<Button-3>', rClicker, add='')

        # BUTTON - CUSTOM MAC
        self.button_custom_mac = ttk.Button(self.labelframe_custom_mac,
                                            text="Set custom MAC",
                                            command=self.customize_mac)
        self.button_custom_mac.grid(column=4, row=0)

        # LABELFRAME - RANDOM MAC
        self.labelframe_random_mac = LabelFrame(self.root,
                                                text="Randomize MAC")
        self.labelframe_random_mac.pack(fill="both", expand="no", pady=10)

        # LABEL - RANDOM MAC
        self.label_random_mac = Label(
            self.labelframe_random_mac,
            text="Changes the current MAC to a completly \nrandom MAC",
            justify=LEFT)
        self.label_random_mac.grid(column=1, row=0, rowspan=2, padx=5)

        # BUTTON - RANDOM MAC
        self.button_random_mac = ttk.Button(self.labelframe_random_mac,
                                            text="Randomize MAC",
                                            command=self.randomize_mac)
        self.button_random_mac.grid(column=3, row=0, padx=5)

        # LABELFRAME - RESTORE ORIGINAL
        self.labelframe_restore_original = LabelFrame(
            self.root, text="Restore original MAC")
        self.labelframe_restore_original.pack(fill="both",
                                              expand="no",
                                              pady=10)

        # LABEL - RESTORE ORIGINAL
        self.label_restore_original = Label(
            self.labelframe_restore_original,
            text="Restores the original selected interface's\nMAC address",
            justify=LEFT)
        self.label_restore_original.grid(column=1, row=0, padx=5)

        # BUTTON - RESTORE ORIGINAL
        self.button_restore_original = ttk.Button(
            self.labelframe_restore_original,
            text="Restore MAC",
            command=self.restore_mac)
        self.button_restore_original.grid(column=3, row=0, padx=5)

        # LABELFRAME - MAC SPOOFING
        self.labelframe_mac_spoofing = LabelFrame(self.root,
                                                  text="MAC spoofing")
        self.labelframe_mac_spoofing.pack(fill="both", expand="no", pady=10)

        # LABEL - MAC SPOOFING)
        self.label_mac_spoofing = Label(
            self.labelframe_mac_spoofing,
            text="Spoof client's MAC address during attack")
        self.label_mac_spoofing.grid(column=1, row=0, padx=5)

        # CHECKBUTTON - MAC SPOOFING
        self.checkbutton_mac_spoofing = Checkbutton(
            self.labelframe_mac_spoofing,
            text="Active",
            command=self.mac_spoofing)
        self.checkbutton_mac_spoofing.grid(column=3, row=0, padx=5)

        # BUTTON - DONE
        self.button_done = ttk.Button(self.root,
                                      text="Done",
                                      command=self.destroy_window)
        self.button_done.pack(padx=15, pady=15)

    def customize_mac(self):
        """
        Sends an order to the main view to set the MAC address to the sended one.
        Filters the address before send it (only hexadecimal values).

        :author: Pablo Sanz Alguacil
        """

        address = self.entry_custom_mac.get().lower()
        colon_count = 0
        address_length = len(self.entry_custom_mac.get())
        address_splited = list(address)
        boolean_fg = True
        for character in address_splited:
            if character in self.accepted_characters and address_length == 17:
                if character == ":":
                    colon_count = colon_count + 1
            else:
                boolean_fg = False
        if boolean_fg and colon_count == 5:
            self.notify_view(0, self.entry_custom_mac.get())
        else:
            self.popup_gen.warning("Warning", "Address not valid")

    def randomize_mac(self):
        """
        Sends an order to the main view to randomize the MAC address.

        :author: Pablo Sanz Alguacil
        """

        self.notify_view(1, "")

    def restore_mac(self):
        """
        Sends an order to the main view to restore the original MAC address.

        :author: Pablo Sanz Alguacil
        """

        self.notify_view(2, "")

    def set_spoofing_checkbutton(self):
        """
        Selects or deselcts the MAC spoofing checkbutton.

        :author: Pablo Sanz Alguacil
        """

        if self.spoofing_status:
            self.checkbutton_mac_spoofing.select()
        else:
            self.checkbutton_mac_spoofing.deselect()

    def mac_spoofing(self):
        """
        Sends an order to the main view to set the MAC spoofing status. Saves the status in a local variable.

        :author: Pablo Sanz Alguacil
        """

        if self.spoofing_status:
            self.spoofing_status = False
            self.notify_view(3, False)
        else:
            self.spoofing_status = True
            self.notify_view(3, True)

    def notify_view(self, operation, value):
        """
        Operation values (int)
        [0] Custom mac
        [1] Random mac
        [2] Restore mac
        [3] Mac spoofing
        Sends and operation and value to the main view.
        :param self:
        :param operation: integer
        :param value: object

        :author: Pablo Sanz Alguacil
        """
        self.main_view.get_notify_childs(operation, value)

    def destroy_window(self):
        """
        Enables all buttons in the main window and destroys this window.

        :author: Pablo Sanz Alguacil
        """

        self.main_view.disable_window(False)
        self.root.destroy()
コード例 #10
0
ファイル: rule_dialog.py プロジェクト: jhaux/beancountManager
    def make_changable(self, name, row_id, kind='text', preVals=None):

        relation = StringVar()
        pattern = StringVar()
        change = StringVar()
        changeTo = StringVar()

        relMenu = OptionMenu(self.diagFrame, relation,
                             *StringComparison.options)
        relMenu.grid(row=row_id, column=1, sticky=W)

        patEntry = Entry(self.diagFrame, textvariable=pattern)
        patEntry.grid(row=row_id, column=2, sticky=W)

        if self.entry and hasattr(self.entry, name):
            inString = getattr(self.entry, name)
        else:
            inString = ''
        chMenu = OptionMenu(self.diagFrame,
                            change,
                            *StringModification.options,
                            command=self.possibleDialog(changeTo, inString))
        chMenu.grid(row=row_id, column=3, sticky=W)

        if name == 'account':
            chVal = CustomMenubutton(self.diagFrame,
                                     self.ledger,
                                     self.entry,
                                     textvariable=changeTo,
                                     indicatoron=True)
        else:
            chVal = Entry(self.diagFrame, textvariable=changeTo)
        chVal.grid(row=row_id, column=4, sticky=W)

        settableItems = [relMenu, patEntry, chMenu, chVal]
        checkVar = IntVar()
        command = self.getCheckcommand(checkVar, settableItems)
        label = Checkbutton(self.diagFrame,
                            text=name.title(),
                            variable=checkVar,
                            onvalue=True,
                            offvalue=False,
                            command=command)
        label.grid(row=row_id, column=0, sticky=E + W)

        if not preVals:
            label.deselect()
        else:
            if not preVals['pattern']:
                label.deselect()
            else:
                label.select()
        command()

        if preVals:
            if 'relation' in preVals:
                relation.set(preVals['relation'])
            if 'pattern' in preVals:
                pattern.set(preVals['pattern'])
            if 'change' in preVals:
                change.set(preVals['change'])
            if 'changeTo' in preVals:
                changeTo.set(preVals['changeTo'])

        return checkVar, relation, pattern, change, changeTo
コード例 #11
0
class PlotManager:
    def __init__(self, controller: utils.ControllerType):
        self.controller = controller
        self.plotter = self.controller.plotter
        self.config_info = controller.config_info
        self.tk_format = utils.TkFormat(self.controller.config_info)

        try:
            with open(self.config_info.local_config_loc + "plot_config.txt",
                      "r") as plot_config:
                self.plot_local_remote = plot_config.readline().strip("\n")
                self.plot_input_file = plot_config.readline().strip("\n")
                self.dataset_name = plot_config.readline().strip("\n")
        except OSError:
            print("No past plotting location found. Using default.")
            with open(self.config_info.local_config_loc + "plot_config.txt",
                      "w+") as f:
                f.write("remote")
                f.write("C:\\Users\n")
                f.write("C:\\Users\n")

            self.plot_local_remote = "remote"
            self.dataset_name = ""
            self.plot_input_file = "C:\\Users"

        self.plot_remote = IntVar()
        self.plot_local = IntVar()
        if self.plot_local_remote == "remote":
            self.plot_remote.set(1)
            self.plot_local.set(0)
        else:
            self.plot_local.set(1)
            self.plot_remote.set(0)

        self.plot_local_check = None
        self.plot_remote_check = None
        self.dataset_name_entry = None
        self.plot_input_dir_entry = None
        self.plot_top = None

    def show(self) -> None:
        self.plot_top = Toplevel(self.controller.master)
        self.plot_top.wm_title("Plot")
        plot_frame = Frame(self.plot_top,
                           bg=self.tk_format.bg,
                           pady=2 * self.tk_format.pady,
                           padx=15)
        plot_frame.pack()

        dataset_name_label = Label(
            plot_frame,
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            bg=self.tk_format.bg,
            fg=self.tk_format.textcolor,
            text="Dataset name:",
        )
        dataset_name_label.pack(padx=self.tk_format.padx, pady=(15, 5))
        self.dataset_name_entry = Entry(
            plot_frame,
            width=50,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        self.dataset_name_entry.insert(0, self.dataset_name)
        self.dataset_name_entry.pack(pady=(5, 20))
        plot_local_remote_frame = Frame(plot_frame, bg=self.tk_format.bg)
        plot_local_remote_frame.pack()

        plot_input_dir_label = Label(
            plot_local_remote_frame,
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            bg=self.tk_format.bg,
            fg=self.tk_format.textcolor,
            text="Path to .csv file:",
        )
        plot_input_dir_label.pack(side=LEFT,
                                  padx=self.tk_format.padx,
                                  pady=self.tk_format.pady)

        self.plot_local_check = Checkbutton(
            plot_local_remote_frame,
            fg=self.tk_format.textcolor,
            text=" Local",
            selectcolor=self.tk_format.check_bg,
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            variable=self.plot_local,
            highlightthickness=0,
            highlightbackground=self.tk_format.bg,
            command=self.local_plot_cmd,
        )
        self.plot_local_check.pack(side=LEFT, pady=(5, 5), padx=(5, 5))

        self.plot_remote_check = Checkbutton(
            plot_local_remote_frame,
            fg=self.tk_format.textcolor,
            text=" Remote",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.plot_remote,
            command=self.remote_plot_cmd,
            selectcolor=self.tk_format.check_bg,
        )
        self.plot_remote_check.pack(side=LEFT, pady=(5, 5), padx=(5, 5))

        # controls whether the file being plotted is looked for locally or on the spectrometer computer
        if self.plot_local_remote == "remote":
            self.plot_remote_check.select()
            self.plot_local_check.deselect()
        if self.plot_local_remote == "local":
            self.plot_local_check.select()
            self.plot_remote_check.deselect()

        plot_file_frame = Frame(plot_frame, bg=self.tk_format.bg)
        plot_file_frame.pack(pady=(5, 10))
        plot_file_browse_button = Button(plot_file_frame,
                                         text="Browse",
                                         command=self.choose_plot_file)
        plot_file_browse_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        plot_file_browse_button.pack(side=RIGHT, padx=self.tk_format.padx)

        self.plot_input_dir_entry = Entry(
            plot_file_frame,
            width=50,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        self.plot_input_dir_entry.insert(0, self.plot_input_file)
        self.plot_input_dir_entry.pack(side=RIGHT)

        plot_button_frame = Frame(plot_frame, bg=self.tk_format.bg)
        plot_button_frame.pack()

        plot_button = Button(
            plot_button_frame,
            fg=self.tk_format.textcolor,
            text="Plot",
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            width=int(self.tk_format.button_width * 1.3),
            bg="light gray",
            command=self.plot_button_cmd,
        )
        plot_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        plot_button.pack(side=LEFT, pady=(20, 20), padx=(15, 15))

        process_close_button = Button(
            plot_button_frame,
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            text="Close",
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            width=int(self.tk_format.button_width * 1.3),
            bg=self.tk_format.buttonbackgroundcolor,
            command=self.close_plot,
        )
        process_close_button.pack(pady=(20, 20), padx=(15, 15), side=LEFT)

    def close_plot(self) -> None:
        self.plot_top.destroy()

    # Toggle back and forth between plotting your data from a remote or local file
    def local_plot_cmd(self) -> None:
        if self.plot_local.get() and not self.plot_remote.get():
            return
        if self.plot_remote.get() and not self.plot_local.get():
            return
        if not self.plot_remote.get():
            self.plot_remote_check.select()
        else:
            self.plot_remote_check.deselect()
        self.plot_input_dir_entry.delete(0, END)

    # Toggle back and forth between plotting your data from a remote or local file
    def remote_plot_cmd(self) -> None:
        if self.plot_local.get() and not self.plot_remote.get():
            return
        if self.plot_remote.get() and not self.plot_local.get():
            return
        if not self.plot_local.get():
            self.plot_local_check.select()
        else:
            self.plot_local_check.deselect()
        self.plot_input_dir_entry.delete(0, END)

    def choose_plot_file(self) -> None:
        init_file = self.plot_input_dir_entry.get()
        relative_file = init_file.split("/")[-1].split("\\")[-1]
        init_dir = init_file.strip(relative_file)
        if self.plot_remote.get():
            RemoteFileExplorer(
                self.controller,
                target=self.plot_input_dir_entry,
                title="Select a file",
                label="Select a file to plot",
                directories_only=False,
            )
        else:
            if os.path.isdir(init_dir):
                file = askopenfilename(initialdir=init_dir,
                                       title="Select a file to plot")
            else:
                file = askopenfilename(initialdir=os.getcwd(),
                                       title="Select a file to plot")
            if file != ():
                self.plot_input_dir_entry.delete(0, "end")
                self.plot_input_dir_entry.insert(0, file)
        self.plot_top.lift()

    def plot_button_cmd(self) -> None:
        plot_input_file = self.plot_input_dir_entry.get()

        if (
                self.plotter.save_dir is None
        ):  # If the user hasn't specified a folder where they want to save plots yet, set the default folder to be
            # the same one they got the data from. Otherwise, leave it as is.
            if self.config_info.opsys == "Windows":
                self.plotter.save_dir = "\\".join(
                    plot_input_file.split("\\")[0:-1])
            else:
                self.plotter.save_dir = "/".join(
                    plot_input_file.split("/")[0:-1])

        self.dataset_name = self.dataset_name_entry.get()
        if self.plot_remote.get():
            self.plot_local_remote = "remote"
        elif self.plot_local.get():
            self.plot_local_remote = "local"

        try:
            with open(self.config_info.local_config_loc + "plot_config.txt",
                      "w") as plot_config:
                plot_config.write(self.plot_local_remote + "\n")
                plot_config.write(plot_input_file + "\n")
                plot_config.write(self.dataset_name + "\n")
        except OSError:
            print("Error saving data location for plots.")

        self.plot_top.destroy()
        if self.plot_local_remote == "remote":
            self.controller.plot_remote(plot_input_file)
        else:
            self.plot(plot_input_file)

    def plot(self, plot_input_file):
        if len(self.controller.queue) > 0:
            if self.plot in self.controller.queue[0]:
                # Happens if we just transferred data from spec compy.
                self.controller.complete_queue_item()
                self.controller.wait_dialog.top.destroy()

        try:
            data_loaded = self.plotter.load_samples(self.dataset_name,
                                                    plot_input_file)
            if not data_loaded:
                ErrorDialog(self.controller, "Error",
                            "Error: Could not load data.")
                print("Error: Could not load data.")
        # pylint: disable = broad-except
        except (IndexError, KeyError, Exception):
            Dialog(
                self.controller,
                "Plotting Error",
                "Error: Plotting failed.\n\nDoes file exist? Is data formatted correctly?\nIf plotting a remote file,"
                " is the server accessible?",
                {"ok": {}},
            )
            return
        self.plotter.new_tab()
コード例 #12
0
class ProcessManager:
    def __init__(self, controller: utils.ControllerType):
        # The commander is in charge of sending all the commands for the spec compy to read
        # If the user has saved spectra with this program before, load in their previously used directories.
        self.controller = controller
        self.config_info = controller.config_info
        self.remote_directory_worker = controller.remote_directory_worker

        self.tk_format = utils.TkFormat(self.controller.config_info)

        self.process_input_dir = ""
        self.process_output_dir = ""
        # TODO: saving a spectrum should result in that directory being set
        #  as the process directory next time the program opens.
        try:
            with open(
                    self.config_info.local_config_loc +
                    "process_directories.txt", "r") as process_config:
                self.proc_local_remote = process_config.readline().strip("\n")
                self.process_input_dir = process_config.readline().strip("\n")
                self.process_output_dir = process_config.readline().strip("\n")

        except OSError:
            with open(
                    self.config_info.local_config_loc +
                    "process_directories.txt", "w+") as f:
                f.write("remote")
                f.write("C:\\Users\n")
                f.write("C:\\Users\n")
                self.proc_local_remote = "remote"
                self.proc_input_dir = "C:\\Users"
                self.proc_output_dir = "C:\\Users"

        self.proc_remote = IntVar()
        self.proc_local = IntVar()
        if self.proc_local_remote == "remote":
            self.proc_remote.set(1)
            self.proc_local.set(0)
        else:
            self.proc_local.set(1)
            self.proc_remote.set(0)

        self.process_save_dir = IntVar()
        self.input_dir_var = StringVar()
        self.process_top = None
        self.input_dir_entry = None
        self.proc_local_check = None
        self.proc_remote_check = None
        self.output_dir_entry = None
        self.output_file_entry = None
        self.process_save_dir_check = None

    def show(self) -> None:
        self.process_top = Toplevel(self.controller.master)
        self.process_top.wm_title("Process Data")
        process_frame = Frame(self.process_top,
                              bg=self.tk_format.bg,
                              pady=15,
                              padx=15)
        process_frame.pack()

        input_dir_label = Label(
            process_frame,
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            bg=self.tk_format.bg,
            fg=self.tk_format.textcolor,
            text="Raw spectral data input directory:",
        )
        input_dir_label.pack(padx=self.tk_format.padx, pady=(10, 5))

        input_frame = Frame(process_frame, bg=self.tk_format.bg)
        input_frame.pack()

        process_input_browse_button = Button(
            input_frame, text="Browse", command=self.choose_process_input_dir)
        process_input_browse_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        process_input_browse_button.pack(side=RIGHT, padx=self.tk_format.padx)

        self.input_dir_var.trace("w", self.validate_input_dir)

        self.input_dir_entry = Entry(
            input_frame,
            width=50,
            bd=self.tk_format.bd,
            textvariable=self.input_dir_var,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        if len(self.input_dir_entry.get()) == 0:
            self.input_dir_entry.insert(0, self.process_input_dir)
        self.input_dir_entry.pack(side=RIGHT,
                                  padx=self.tk_format.padx,
                                  pady=self.tk_format.pady)

        proc_local_remote_frame = Frame(process_frame, bg=self.tk_format.bg)
        proc_local_remote_frame.pack()

        output_dir_label = Label(
            proc_local_remote_frame,
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            bg=self.tk_format.bg,
            fg=self.tk_format.textcolor,
            text="Processed data output directory:",
        )
        output_dir_label.pack(padx=self.tk_format.padx,
                              pady=(10, 5),
                              side=LEFT)

        self.proc_local_check = Checkbutton(
            proc_local_remote_frame,
            fg=self.tk_format.textcolor,
            text=" Local",
            selectcolor=self.tk_format.check_bg,
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            variable=self.proc_local,
            highlightthickness=0,
            highlightbackground=self.tk_format.bg,
            command=self.local_process_cmd,
        )
        self.proc_local_check.pack(side=LEFT, pady=(5, 0), padx=(5, 5))
        if self.proc_local_remote == "local":
            self.proc_local_check.select()

        self.proc_remote_check = Checkbutton(
            proc_local_remote_frame,
            fg=self.tk_format.textcolor,
            text=" Remote",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.proc_remote,
            command=self.remote_process_cmd,
            selectcolor=self.tk_format.check_bg,
        )
        self.proc_remote_check.pack(side=LEFT, pady=(5, 0), padx=(5, 5))
        if self.proc_local_remote == "remote":
            self.proc_remote_check.select()

        process_output_frame = Frame(process_frame, bg=self.tk_format.bg)
        process_output_frame.pack(pady=(5, 10))
        process_output_browse_button = Button(
            process_output_frame,
            text="Browse",
            command=self.choose_process_output_dir)
        process_output_browse_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        process_output_browse_button.pack(side=RIGHT, padx=self.tk_format.padx)

        self.output_dir_entry = Entry(
            process_output_frame,
            width=50,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        self.output_dir_entry.insert(0, self.process_output_dir)
        self.output_dir_entry.pack(side=RIGHT,
                                   padx=self.tk_format.padx,
                                   pady=self.tk_format.pady)

        output_file_label = Label(
            process_frame,
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            bg=self.tk_format.bg,
            fg=self.tk_format.textcolor,
            text="Output file name:",
        )
        output_file_label.pack(padx=self.tk_format.padx,
                               pady=self.tk_format.pady)
        self.output_file_entry = Entry(
            process_frame,
            width=50,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        self.output_file_entry.pack()

        process_check_frame = Frame(process_frame, bg=self.tk_format.bg)
        process_check_frame.pack(pady=(15, 5))

        self.process_save_dir_check = Checkbutton(
            process_check_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text="Save file configuration",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.process_save_dir,
        )
        self.process_save_dir_check.select()

        process_button_frame = Frame(process_frame, bg=self.tk_format.bg)
        process_button_frame.pack()
        process_button = Button(
            process_button_frame,
            fg=self.tk_format.textcolor,
            text="Process",
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            width=int(self.tk_format.button_width * 1.3),
            bg="light gray",
            command=self.controller.process_cmd,
        )
        process_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        process_button.pack(padx=(15, 15), side=LEFT)

        process_close_button = Button(
            process_button_frame,
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            text="Close",
            padx=self.tk_format.padx,
            pady=self.tk_format.pady,
            width=int(self.tk_format.button_width * 1.3),
            bg=self.tk_format.buttonbackgroundcolor,
            command=self.close_process,
        )
        process_close_button.pack(padx=(15, 15), side=LEFT)

    # Closes process frame
    def close_process(self) -> None:
        self.process_top.destroy()

    # Toggle back and forth between saving your processed data remotely or locally
    def local_process_cmd(self) -> None:
        if self.proc_local.get() and not self.proc_remote.get():
            return
        if self.proc_remote.get() and not self.proc_local.get():
            return
        if not self.proc_remote.get():
            self.proc_remote_check.select()
        else:
            self.proc_remote_check.deselect()
            self.proc_local_remote = "local"
            self.output_dir_entry.delete(0, "end")

    # Toggle back and forth between saving your processed data remotely or locally
    def remote_process_cmd(self) -> None:
        if self.proc_local.get() and not self.proc_remote.get():
            return
        if self.proc_remote.get() and not self.proc_local.get():
            return
        if not self.proc_local.get():
            self.proc_local_check.select()
        else:
            self.proc_local_check.deselect()
            self.proc_local_remote = "remote"
            self.output_dir_entry.delete(0, "end")

    def choose_process_output_dir(self) -> None:
        init_dir: str = self.output_dir_entry.get()
        if self.proc_remote.get():
            RemoteFileExplorer(
                self.controller,
                target=self.output_dir_entry,
                title="Select a directory",
                label="Select an output directory for processed data.",
                directories_only=True,
            )
        else:
            self.process_top.lift()
            if os.path.isdir(init_dir):
                output_dir = askdirectory(initialdir=init_dir,
                                          title="Select an output directory")
            else:
                output_dir = askdirectory(initialdir=os.getcwd(),
                                          title="Select an output directory")
            if output_dir != ():
                self.output_dir_entry.delete(0, "end")
                self.output_dir_entry.insert(0, output_dir)
        self.process_top.lift()

    def setup_process(self) -> Tuple[str, str, str]:
        output_file: str = self.output_file_entry.get()

        if output_file == "":
            ErrorDialog(self.controller,
                        label="Error: Enter an output file name")
            raise ProcessFileError

        if output_file[-4:] != ".csv":
            output_file = output_file + ".csv"
            self.output_file_entry.insert("end", ".csv")

        input_directory = self.input_dir_entry.get()
        if input_directory[-1] == "\\":
            input_directory = input_directory[:-1]

        output_directory = self.output_dir_entry.get()

        if self.process_save_dir.get():
            file = open(
                self.config_info.local_config_loc + "process_directories.txt",
                "w+")
            file.write(self.proc_local_remote + "\n")
            file.write(input_directory + "\n")
            file.write(output_directory + "\n")
            file.write(output_file + "\n")
            file.close()

        if self.proc_local.get() == 1:
            self.controller.plot_manager.plot_local_remote = "local"
            check = self.check_local_file(self.output_dir_entry.get(),
                                          output_file,
                                          self.controller.process_cmd)
            if not check:
                raise ProcessFileError  # If the file exists, controller.check_local_file_exists
                # gives the user the option to overwrite, in which case process_cmd gets called again.
            check = self.check_local_folder(output_directory,
                                            self.controller.process_cmd)
            if not check:
                raise ProcessFileError  # Same deal for the folder (except existing is good).
            self.controller.plot_manager.plot_local_remote = "local"
            return input_directory, output_directory, output_file
        if self.proc_local.get() == 0:
            check = self.check_remote_folder(output_directory,
                                             self.controller.process_cmd)
            if not check:
                raise ProcessFileError
            self.controller.plot_manager.plot_local_remote = "remote"

        return input_directory, output_directory, output_file

    def finish_processing(self) -> Tuple[str, str]:
        return
        # #TODO: final_data_destination seems to just become log base?
        # final_data_destination: str = self.output_file_entry.get()
        # if "." not in final_data_destination:
        #     final_data_destination = final_data_destination + ".csv"
        # data_base: str = ".".join(final_data_destination.split(".")[0:-1])
        #
        # if self.config_info.opsys in ("Linux", "Mac"):
        #     final_data_destination: str = self.output_dir_entry.get() + "/" + final_data_destination
        #     log_base: str = self.output_dir_entry.get() + "/" + data_base + "_log"
        # else:
        #     final_data_destination: str = self.output_dir_entry.get() + "\\" + final_data_destination
        #     log_base: str = self.output_dir_entry.get() + "\\" + data_base + "_log"
        #
        # final_log_destination: str = log_base
        # i = 1
        # while os.path.isfile(final_log_destination + ".txt"):
        #     final_log_destination = log_base + "_" + str(i)
        #     i += 1
        # final_log_destination += ".txt"
        #
        # return final_data_destination, final_log_destination

    def check_local_file(self, directory: str, local_file: str,
                         next_action: Any) -> bool:
        def remove_retry(file, action):
            try:
                os.remove(file)
                action()
            except OSError:
                ErrorDialog(self.controller,
                            title="Error overwriting file",
                            label="Error: Could not delete file.\n\n" + file)

        if self.config_info.opsys in ("Linux", "Mac"):
            if directory[-1] != "/":
                directory += "/"
        else:
            if directory[-1] != "\\":
                directory += "\\"

        full_process_output_path = directory + local_file
        if os.path.exists(full_process_output_path):
            buttons = {
                "yes": {
                    remove_retry: [full_process_output_path, next_action]
                },
                "no": {}
            }
            dialog = Dialog(
                self.controller,
                title="Error: File Exists",
                label="Error: Specified output file already exists.\n\n" +
                full_process_output_path +
                "\n\nDo you want to overwrite this data?",
                buttons=buttons,
            )
            width = len(full_process_output_path) * 5 + 100
            dialog.top.wm_geometry(f"{width}x160")
            return False
        return True

    def check_local_folder(self, local_dir: str, next_action: Any) -> bool:
        def try_mk_dir(dir_to_make: str, action: Any) -> None:
            try:
                os.makedirs(dir_to_make)
                action()
            except OSError:
                ErrorDialog(self.controller,
                            title="Cannot create directory",
                            label="Cannot create directory:\n\n" + dir_to_make)

        exists = os.path.exists(local_dir)
        if exists:
            # If the file exists, try creating and deleting a new file there to make sure we have permission.
            try:
                if self.config_info.opsys in ("Linux", "Mac"):
                    if local_dir[-1] != "/":
                        local_dir += "/"
                else:
                    if local_dir[-1] != "\\":
                        local_dir += "\\"

                existing = os.listdir(local_dir)
                i = 0
                delme = "delme" + str(i)
                while delme in existing:
                    i += 1
                    delme = "delme" + str(i)

                os.mkdir(local_dir + delme)
                os.rmdir(local_dir + delme)
                return True

            except OSError:
                ErrorDialog(
                    self.controller,
                    title="Error: Cannot write",
                    label="Error: Cannot write to specified directory.\n\n" +
                    local_dir,
                )
                return False
        else:
            if (
                    self.controller.script_running
            ):  # If we're running a script, just try making the directory automatically.
                try_mk_dir(local_dir, next_action)
            else:  # Otherwise, ask the user.
                buttons = {
                    "yes": {
                        try_mk_dir: [local_dir, next_action]
                    },
                    "no": {}
                }
                ErrorDialog(
                    self.controller,
                    title="Directory does not exist",
                    label=local_dir +
                    "\n\ndoes not exist. Do you want to create this directory?",
                    buttons=buttons,
                )
        # TODO: check these return statements make sense.
        return exists

    # Checks if the given directory exists and is writeable. If not writeable, gives user option to create.
    def check_remote_folder(self, remote_dir: str, next_action: Any) -> bool:
        print(remote_dir)

        def inner_mkdir(dir_to_make: str, action: Any):
            mkdir_status = self.remote_directory_worker.mkdir(dir_to_make)
            print("MKDIR STATUS!!")
            print(mkdir_status)
            if mkdir_status == "mkdirsuccess":
                action()
            elif mkdir_status == "mkdirfailedfileexists":
                ErrorDialog(
                    self.controller,
                    title="Error",
                    label="Could not create directory:\n\n" + dir_to_make +
                    "\n\nFile exists.",
                )
            elif mkdir_status == "mkdirfailedpermission":
                ErrorDialog(
                    self.controller,
                    title="Error",
                    label="Could not create directory:\n\n" + dir_to_make +
                    "\n\nPermission denied.",
                )
            elif "mkdirfailed" in mkdir_status:
                ErrorDialog(self.controller,
                            title="Error",
                            label="Could not create directory:\n\n" +
                            dir_to_make)

        status = self.remote_directory_worker.get_dirs(remote_dir)

        if status == "listdirfailed":
            buttons = {
                "yes": {
                    inner_mkdir: [remote_dir, next_action]
                },
                "no": {}
            }
            ErrorDialog(
                self.controller,
                title="Directory does not exist",
                label=remote_dir +
                "\ndoes not exist. Do you want to create this directory?",
                buttons=buttons,
            )
            return False
        if status == "listdirfailedpermission":
            ErrorDialog(self.controller,
                        label="Error: Permission denied for\n" + remote_dir)
            return False

        if status == "timeout":
            if not self.controller.text_only:
                buttons = {
                    "cancel": {},
                    "retry": {
                        self.controller.spec_commander.remove_from_listener_queue:
                        [["timeout"]],
                        self.controller.next_in_queue: [],
                    },
                }
                dialog = ErrorDialog(
                    self.controller,
                    label=
                    "Error: Operation timed out.\n\nCheck that the automation script is running on the"
                    " spectrometer\n computer and the spectrometer is connected.",
                    buttons=buttons,
                )
                for button in dialog.tk_buttons:
                    button.config(width=15)
            else:
                self.controller.log("Error: Operation timed out.")
            return False

        self.controller.spec_commander.check_writeable(remote_dir)
        t = 3 * utils.BUFFER
        while t > 0:
            if "yeswriteable" in self.controller.spec_listener.queue:
                self.controller.spec_listener.queue.remove("yeswriteable")
                return True
            if "notwriteable" in self.controller.spec_listener.queue:
                self.controller.spec_listener.queue.remove("notwriteable")
                ErrorDialog(
                    self.controller,
                    label=
                    "Error: Permission denied.\nCannot write to specified directory."
                )
                return False
            time.sleep(utils.INTERVAL)
            t = t - utils.INTERVAL
        if t <= 0:
            ErrorDialog(self.controller, label="Error: Operation timed out.")
            return False

    def choose_process_input_dir(self) -> None:
        RemoteFileExplorer(
            self.controller,
            label=
            "Select the directory containing the data you want to process.\nThis must be on a drive mounted on"
            " the spectrometer control computer.\n E.g. R:\\RiceData\\MarsGroup\\YourName\\spectral_data",
            target=self.input_dir_entry,
        )

    def validate_input_dir(self, *args) -> None:
        # TODO: understand mystery args.
        print(args)
        pos = self.input_dir_entry.index(INSERT)
        input_dir = utils.rm_reserved_chars(self.input_dir_entry.get())
        if len(input_dir) < len(self.input_dir_entry.get()):
            pos = pos - 1
        self.input_dir_entry.delete(0, "end")
        self.input_dir_entry.insert(0, input_dir)
        self.input_dir_entry.icursor(pos)
コード例 #13
0
class DistanceFuncFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.isCalcDistanceMode = BooleanVar()
        self.isCriticalShortest = BooleanVar()
        self.cbCalcDistance = Checkbutton(
            self,
            variable=self.isCalcDistanceMode,
            text="calculate distance mode",
            command=self.on_calc_distance_mode_clicked)
        self.cbCriticalShortest = Checkbutton(self,
                                              variable=self.isCriticalShortest,
                                              text="critical")
        self.cbCalcDistance.deselect()
        self.cbCriticalShortest.deselect()
        self.lblStartPos = Label(self)
        self.lblEndPos = Label(self)
        self.lblDistance = Label(self)
        self.firstPosRow = INVALID_ROW
        self.firstPosCol = INVALID_COL

        Label(self).pack(expand=1)
        Label(self).pack(expand=1)
        self.cbCalcDistance.pack(expand=1)
        self.cbCriticalShortest.pack(expand=1)
        self.lblStartPos.pack(expand=1)
        self.lblEndPos.pack(expand=1)
        self.lblDistance.pack(expand=1)

        evtDispatcher.register(EvtIds.EVT_FIRST_POSITION_SELECTED,
                               self.handle_first_position_selected)
        evtDispatcher.register(EvtIds.EVT_SECOND_POSITION_SELECTED,
                               self.handle_second_position_selected)
        evtDispatcher.register(EvtIds.EVT_SHORTEST_DISTANCE_CALCULATED,
                               self.handle_shortest_distance_calculated)

    def handle_first_position_selected(self, content):
        if content is None or content["row"] is None or content["col"] is None:
            return
        self.lblEndPos.config(text="")
        self.lblDistance.config(text="")
        self.lblStartPos.config(text="POS1: (%d, %d)" %
                                (content["col"], content["row"]))
        self.firstPosRow = content["row"]
        self.firstPosCol = content["col"]

    def handle_second_position_selected(self, content):
        if content is None or content["row"] is None or content["col"] is None:
            return
        self.lblEndPos.config(text="POS2: (%d, %d)" %
                              (content["col"], content["row"]))
        self.lblDistance.config(text="calculating...")
        self.update()
        evtDispatcher.dispatch(
            EvtIds.EVT_INFORM_CALC_DISTANCE, {
                "row1": self.firstPosRow,
                "col1": self.firstPosCol,
                "row2": content["row"],
                "col2": content["col"],
                "isCriticalShortest": self.isCriticalShortest.get()
            })

    def handle_shortest_distance_calculated(self, content):
        if content is None or content["distance"] is None: return
        if content["distance"] == UNREACH_DISTANCE:
            self.lblDistance.config(text="UNREACHABLE")
            return
        res = "Shortest Distance: %d" % content["distance"]
        if not self.isCriticalShortest.get():
            res = "Possible Shortest Distance: %d" % content["distance"]
        self.lblDistance.config(text=res)

    def on_calc_distance_mode_clicked(self):
        if not self.isCalcDistanceMode.get():
            self.clean()
            self.cbCriticalShortest.deselect()
        evtDispatcher.dispatch(EvtIds.EVT_SET_CALC_DISTANCE_MODE,
                               {"mode": self.isCalcDistanceMode.get()})

    def clean(self):
        self.lblStartPos.config(text="")
        self.lblEndPos.config(text="")
        self.lblDistance.config(text="")
コード例 #14
0
ファイル: egrul_parser.py プロジェクト: LeontyV/egrul_parser
def choice_proxy():
    global prx

    def proxy_save():
        set_dict = {}
        if login.get() == '' or password.get() == '':
            set_dict[
                'http'] = f'"http": "http://{proxy_address.get()}:{port.get()}"'
            set_dict[
                'https'] = f'"https": "https://{proxy_address.get()}:{port.get()}"'
            set_dict['login'] = ''
            set_dict['pass'] = ''
            set_dict['proxy'] = f'"{prx.get()}"'
            enc_str = str(set_dict).encode('utf-8')
            enc_str_b64 = base64.b64encode(enc_str)
        else:
            set_dict[
                'http'] = f'"http": "http://{proxy_address.get()}:{port.get()}"'
            set_dict[
                'https'] = f'"https": "https://{proxy_address.get()}:{port.get()}"'
            set_dict['login'] = login.get()
            set_dict['pass'] = password.get()
            set_dict['proxy'] = f'"{prx.get()}"'
            enc_str = str(set_dict).encode('utf-8')
            enc_str_b64 = base64.b64encode(enc_str)

        egrul_parser_path = create_folders()
        proxy_settings_path = egrul_parser_path + '/proxy_settings'
        proxy_settings = open(proxy_settings_path, 'wb')
        proxy_settings.write(enc_str_b64)

        proxy_settings.close()

        pw.destroy()
        window.deiconify()

    def on_close_proxy():
        pw.destroy()
        window.deiconify()

    def change_check():
        if prx.get():
            prx.set(0)
        else:
            prx.set(1)

    window.withdraw()

    pw = tk.Tk()
    width = 300
    height = 150
    pw.title("Настройки прокси")
    pw.geometry(f'{str(width)}x{str(height)}')
    pw.resizable(0, 0)

    proxy_lbl = Label(pw, text="адрес: ")
    proxy_lbl.grid(column=0, row=0)

    proxy_address = Entry(pw, width=30)
    proxy_address.grid(column=1, row=0, sticky='w')

    prx = BooleanVar()
    prx.set(0)
    proxy_check = Checkbutton(pw,
                              text='Прокси:',
                              variable=prx,
                              onvalue=1,
                              offvalue=0,
                              command=change_check)
    proxy_check.grid(column=3, row=0, sticky='e')

    port_lbl = Label(pw, text="порт: ")
    port_lbl.grid(column=0, row=1)

    port = Entry(pw, width=5)
    port.grid(column=1, row=1, sticky='w')

    login_lbl = Label(pw, text="логин: ")
    login_lbl.grid(column=0, row=2)

    login = Entry(pw, width=20)
    login.grid(column=1, row=2, sticky='w')

    passwrd_lbl = Label(pw, text="пароль: ")
    passwrd_lbl.grid(column=0, row=3)

    password = Entry(pw, show="*", width=20)
    password.grid(column=1, row=3, sticky='w')

    btn = Button(pw, text="Сохранить", command=proxy_save)
    btn.grid(column=1, row=5)

    btn = Button(pw, text="Закрыть", command=on_close_proxy)
    btn.grid(column=0, row=5)

    egrul_parser_path = create_folders()
    proxy_settings_path = egrul_parser_path + '/proxy_settings'
    if os.path.exists(proxy_settings_path):
        file = open(proxy_settings_path, 'rb')
        proxies_enc = file.read()
        proxies_dec = base64.b64decode(proxies_enc)
        proxies_dec = proxies_dec.decode('utf-8')
        proxies_dec = proxies_dec.replace('"', '\\"')
        proxies_dec = proxies_dec.replace("'", '"')
        proxies_dec = json.loads(proxies_dec)
        file.close()
        _login = proxies_dec.get('login')
        _pass = proxies_dec.get('pass')
        if _login is None or _pass is None:
            logger('Ошибка с парсингом параметров логина и пароля прокси')
            _login = ''
            _pass = ''

        _proxy = proxies_dec.get('http')
        try:
            _address = re.findall('(http:\W\W|@|)([a-z0-9.-]+):\d+',
                                  _proxy)[0][1]
            _port = re.findall(':(\d+)', _proxy)[0]
        except IndexError:
            logger('Ошибка с парсингом параметров адреса и порта прокси')
            _address = ''
            _port = ''

        proxy_address.insert(0, _address)
        port.insert(0, _port)
        login.insert(0, _login)
        password.insert(0, _pass)
        if getboolean(proxies_dec.get('proxy')[1:-1]):
            proxy_check.select()
            prx.set(1)
        else:
            proxy_check.deselect()
            prx.set(0)

    pw.protocol("WM_DELETE_WINDOW", on_close_proxy)

    pw.mainloop()
コード例 #15
0
class PyRegexEvaluator(Frame):

    def centre_window(self):
        """ Display's your gui in the centre of the screen """
        w = 685     # Sets your gui's width
        h = 635     # Sets your gui's height
        sw = self.root.winfo_screenwidth()
        sh = self.root.winfo_screenheight()
        x = (sw - w) // 2   # Use integer devision to avoid having to convert
        y = (sh - h) // 2   # float to int
        self.root.geometry('{:d}x{:d}+{:d}+{:d}'.format(w, h, x, y))

    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.centre_window()
        centre_title_text = (' ' * 40)  # Uses spaces to center Title
        title_text = 'Python Regular Expression Checker  -  By Jack Ackermann'
        self.root.title(centre_title_text + title_text)
        self.root.iconbitmap('images\icon.ico')
        self.grid(column=0, row=0, sticky='nsew', padx=12, pady=5)

        self.create_widgets()
        self.create_right_click_menu()

    def create_widgets(self):
        '''Create and load all widgets'''
        # Entry widget and Label Section
        label_text = 'Please enter regex expression to find: '
        self.regex_label = tk.Label(self, text=label_text)
        self.regex_label.grid(row=0, column=0, sticky="w", pady=15)

        self.regex_pattern = tk.StringVar()
        self.regex_string = Entry(self, textvariable=self.regex_pattern)
        self.regex_string.config(borderwidth=2, relief='sunken', width=70)
        self.regex_string.grid(row=0, column=0, sticky="e", pady=15)

        # Data widget and Label Section. Data to be searched.
        label_data1 = 'Enter data below that you want to search.  '
        label_data2 = 'Results are then highlighted using re.finditer'
        self.data_label = tk.Label(self, text=label_data1 + label_data2)
        self.data_label.grid(row=1, column=0, sticky="w")

        self.data_textbox = Text(self, borderwidth=2, relief='sunken')
        self.data_textbox.config(height=15, width=80)
        self.data_textbox.grid(row=2, column=0, sticky="new")
        self.scrollbar = Scrollbar(self, command=self.data_textbox.yview)
        self.scrollbar.grid(row=2, column=1, sticky='ns')
        self.data_textbox['yscrollcommand'] = self.scrollbar.set

        # Display regex results and Label section
        label_output = 'All the matches below were found using re.findall'
        self.label_output = tk.Label(self, text=label_output)
        self.label_output.grid(row=3, column=0, sticky="w")

        self.output_textbox = Text(self, borderwidth=2, relief='sunken')
        self.output_textbox.config(height=15, width=80)
        self.output_textbox.grid(row=4, column=0, sticky="new")
        self.scrollbar2 = Scrollbar(self, command=self.output_textbox.yview)
        self.scrollbar2.grid(row=4, column=1, sticky='ns')
        self.output_textbox['yscrollcommand'] = self.scrollbar2.set

        # Create Two Button Widgets
        self.find_btn = ttk.Button(self, text='Find', command=self.on_find)
        self.find_btn.grid(row=5, sticky='E')
        self.exit_btn = ttk.Button(self, text='Exit', command=self.on_exit)
        self.exit_btn.grid(row=5, column=0, sticky='W', pady=15)

        # Create a Checkbutton Widget
        self.auto_var = tk.IntVar()
        self.auto_find = Checkbutton(self, variable=self.auto_var,
                                     command=self.on_auto, background='pink')
        self.auto_find.config(text='Turns on Auto Search as you type')
        self.auto_find.grid(row=5, column=0, sticky='')
        self.auto_find.deselect()

    def create_right_click_menu(self):
        '''Creates and binds the right click popup menu'''
        # Instanciate the imported popup class
        self.popup = RightClickMenu(self.master, self.regex_pattern)
        self.popup2 = RightClickMenu(self.master, self.data_textbox)
        self.popup3 = RightClickMenu(self.master, self.output_textbox)
        # Bind the popup menus and Enter Key to the appropriate widgets.
        self.regex_string.bind("<Button-3>", self.popup.entry_popup)
        self.data_textbox.bind("<Button-3>", self.popup2.text_popup)
        self.output_textbox.bind("<Button-3>", self.popup3.text_popup)
        self.regex_string.bind("<Return>", lambda _: self.on_find())

    # Method for the find_btn, <Return> bind and Checkbutton
    def on_find(self, a=None, b=None, c=None):
        """
        Takes three arguments with default values: a, b, c
        These arguments are needed for the trace method of StringVar()

        Instanciate and use the Highlighter class
        """
        self.highlighter = Highlighter(self.regex_pattern, self.data_textbox,
                                       self.output_textbox)
        self.highlighter.find_matches()

    # Method for the self.auto_find checkbutton
    def on_auto(self):
        """
        If the self.auto_find Checkbox is selected,
        the find button is disabled and the <Return> key is unbound
        The self.regex_pattern.trace is created that calls the on_find
        method everytime the variable changes.

        If the self.auto_find Checkbox is unselected,
        the find button gets re-enabled and the <Return> key bind is set.
        And the self.regex_pattern.trace is deleted
        """
        trace_id = ''
        if self.auto_var.get() == 1:
            self.find_btn.config(state='disabled')
            self.regex_string.unbind("<Return>")
            self.regex_pattern.trace_id = self.regex_pattern.trace("w", self.on_find)
        else:
            self.find_btn.config(state='enabled')
            self.regex_string.bind("<Return>", lambda _: self.on_find())
            self.regex_pattern.trace_vdelete("w", self.regex_pattern.trace_id)

    # Exits the program. Linked to the Exit Button
    def on_exit(self):
        self.root.destroy()
コード例 #16
0
class AnalysisToolsManager:
    def __init__(self, controller):
        self.tab = None
        self.controller = controller
        self.tk_format = utils.TkFormat(self.controller.config_info)

        self.analysis_dialog = None
        self.exclude_artifacts = IntVar()
        self.abs_val = IntVar()
        self.use_max_for_centers = IntVar()
        self.use_delta = IntVar()
        self.neg_depth = IntVar()

        self.normalize_entry = None
        self.right_zoom_entry = None
        self.right_zoom_entry2 = None
        self.left_zoom_entry = None
        self.left_zoom_entry2 = None
        self.left_slope_entry = None
        self.right_slope_entry = None
        self.slopes_listbox = None
        self.abs_val_check = None
        self.use_max_for_centers_check = None
        self.use_delta_check = None
        self.neg_depth_check = None
        self.exclude_artifacts_check = None
        self.extra_analysis_check_frame = None
        self.plot_slope_var = None
        self.offset_entry = None
        self.offset_sample_var = None
        self.plot_slope_menu = None
        self.plot_slope_button = None

        self.analyze_var = None

        self.outer_slope_frame = None
        self.slope_results_frame = None

    def show(self, tab):
        self.tab = tab
        self.tab.freeze(
        )  # You have to finish dealing with this before, say, opening another analysis box.
        buttons = {
            "reset": {
                self.select_tab: [],
                self.tab.reset: [],
                self.uncheck_exclude_artifacts: [],
                self.disable_plot: [],
                # utils.thread_lift_widget: [],
            },
            "close": {},
        }
        self.analysis_dialog = VerticalScrolledDialog(self.controller,
                                                      "Analyze Data",
                                                      "",
                                                      buttons=buttons,
                                                      button_width=13)
        self.analysis_dialog.top.attributes("-topmost", True)

        outer_normalize_frame = Frame(self.analysis_dialog.interior,
                                      bg=self.tk_format.bg,
                                      padx=self.tk_format.padx,
                                      pady=15,
                                      highlightthickness=1)
        outer_normalize_frame.pack(expand=True, fill=BOTH)
        slope_title_label = Label(outer_normalize_frame,
                                  text="Normalize:",
                                  bg=self.tk_format.bg,
                                  fg=self.tk_format.textcolor)
        slope_title_label.pack()
        normalize_frame = Frame(outer_normalize_frame,
                                bg=self.tk_format.bg,
                                padx=self.tk_format.padx,
                                pady=15)
        normalize_frame.pack()

        normalize_label = Label(normalize_frame,
                                text="Wavelength (nm):",
                                bg=self.tk_format.bg,
                                fg=self.tk_format.textcolor)
        self.normalize_entry = Entry(
            normalize_frame,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        normalize_button = Button(
            normalize_frame,
            text="Apply",
            command=self.normalize,
            width=6,
            fg=self.tk_format.buttontextcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            bd=self.tk_format.bd,
        )
        normalize_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        normalize_button.pack(side=RIGHT, padx=(10, 10))
        self.normalize_entry.pack(side=RIGHT, padx=self.tk_format.padx)
        normalize_label.pack(side=RIGHT, padx=self.tk_format.padx)

        outer_offset_frame = Frame(self.analysis_dialog.interior,
                                   bg=self.tk_format.bg,
                                   padx=self.tk_format.padx,
                                   pady=15,
                                   highlightthickness=1)
        outer_offset_frame.pack(expand=True, fill=BOTH)
        slope_title_label = Label(outer_offset_frame,
                                  text="Add offset to sample:",
                                  bg=self.tk_format.bg,
                                  fg=self.tk_format.textcolor)
        slope_title_label.pack(pady=(0, 15))
        offset_sample_frame = Frame(outer_offset_frame,
                                    bg=self.tk_format.bg,
                                    padx=self.tk_format.padx,
                                    pady=self.tk_format.pady)
        offset_sample_frame.pack()
        offset_sample_label = Label(offset_sample_frame,
                                    text="Sample: ",
                                    bg=self.tk_format.bg,
                                    fg=self.tk_format.textcolor)
        offset_sample_label.pack(side=LEFT)
        self.offset_sample_var = StringVar()
        sample_names = []
        repeats = False
        max_len = 0
        for sample in self.tab.samples:
            if sample.name in sample_names:
                repeats = True
            else:
                sample_names.append(sample.name)
                max_len = np.max([max_len, len(sample.name)])
        if repeats:
            sample_names = []
            for sample in self.tab.samples:
                sample_names.append(sample.title + ": " + sample.name)
                max_len = np.max([max_len, len(sample_names[-1])])
        self.offset_sample_var.set(sample_names[0])

        # pylint: disable = no-value-for-parameter
        offset_menu = OptionMenu(offset_sample_frame, self.offset_sample_var,
                                 *sample_names)
        offset_menu.configure(
            width=max_len,
            highlightbackground=self.tk_format.highlightbackgroundcolor)
        offset_menu.pack(side=LEFT)
        offset_frame = Frame(outer_offset_frame,
                             bg=self.tk_format.bg,
                             padx=self.tk_format.padx,
                             pady=15)
        offset_frame.pack()
        offset_label = Label(offset_frame,
                             text="Offset:",
                             bg=self.tk_format.bg,
                             fg=self.tk_format.textcolor)
        self.offset_entry = Entry(
            offset_frame,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        offset_button = Button(
            offset_frame,
            text="Apply",
            command=self.offset,
            width=6,
            fg=self.tk_format.buttontextcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            bd=self.tk_format.bd,
        )
        offset_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        offset_button.pack(side=RIGHT, padx=(10, 10))
        self.offset_entry.pack(side=RIGHT, padx=self.tk_format.padx)
        offset_label.pack(side=RIGHT, padx=self.tk_format.padx)

        outer_outer_zoom_frame = Frame(self.analysis_dialog.interior,
                                       bg=self.tk_format.bg,
                                       padx=self.tk_format.padx,
                                       pady=15,
                                       highlightthickness=1)
        outer_outer_zoom_frame.pack(expand=True, fill=BOTH)

        zoom_title_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg)
        zoom_title_frame.pack(pady=(5, 10))
        zoom_title_label = Label(zoom_title_frame,
                                 text="Adjust plot x and y limits:",
                                 bg=self.tk_format.bg,
                                 fg=self.tk_format.textcolor)
        zoom_title_label.pack(side=LEFT, pady=(0, 4))

        outer_zoom_frame = Frame(outer_outer_zoom_frame,
                                 bg=self.tk_format.bg,
                                 padx=self.tk_format.padx)
        outer_zoom_frame.pack(expand=True, fill=BOTH, pady=(0, 10))
        zoom_frame = Frame(outer_zoom_frame,
                           bg=self.tk_format.bg,
                           padx=self.tk_format.padx)
        zoom_frame.pack()

        zoom_label = Label(zoom_frame,
                           text="x1:",
                           bg=self.tk_format.bg,
                           fg=self.tk_format.textcolor)
        self.left_zoom_entry = Entry(
            zoom_frame,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        zoom_label2 = Label(zoom_frame,
                            text="x2:",
                            bg=self.tk_format.bg,
                            fg=self.tk_format.textcolor)
        self.right_zoom_entry = Entry(
            zoom_frame,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        zoom_button = Button(
            zoom_frame,
            text="Apply",
            command=self.apply_x,
            width=7,
            fg=self.tk_format.buttontextcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            bd=self.tk_format.bd,
        )
        zoom_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )
        zoom_button.pack(side=RIGHT, padx=(10, 10))
        self.right_zoom_entry.pack(side=RIGHT, padx=self.tk_format.padx)
        zoom_label2.pack(side=RIGHT, padx=self.tk_format.padx)
        self.left_zoom_entry.pack(side=RIGHT, padx=self.tk_format.padx)
        zoom_label.pack(side=RIGHT, padx=self.tk_format.padx)

        outer_zoom_frame2 = Frame(outer_outer_zoom_frame,
                                  bg=self.tk_format.bg,
                                  padx=self.tk_format.padx)
        outer_zoom_frame2.pack(expand=True, fill=BOTH, pady=(0, 10))
        zoom_frame2 = Frame(outer_zoom_frame2,
                            bg=self.tk_format.bg,
                            padx=self.tk_format.padx)
        zoom_frame2.pack()
        zoom_label3 = Label(zoom_frame2,
                            text="y1:",
                            bg=self.tk_format.bg,
                            fg=self.tk_format.textcolor)
        self.left_zoom_entry2 = Entry(
            zoom_frame2,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        zoom_label4 = Label(zoom_frame2,
                            text="y2:",
                            bg=self.tk_format.bg,
                            fg=self.tk_format.textcolor)
        self.right_zoom_entry2 = Entry(
            zoom_frame2,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        zoom_button2 = Button(
            zoom_frame2,
            text="Apply",
            command=self.apply_y,
            width=7,
            fg=self.tk_format.buttontextcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            bd=self.tk_format.bd,
        )
        zoom_button2.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )

        zoom_button2.pack(side=RIGHT, padx=(10, 10))
        self.right_zoom_entry2.pack(side=RIGHT, padx=self.tk_format.padx)
        zoom_label4.pack(side=RIGHT, padx=self.tk_format.padx)
        self.left_zoom_entry2.pack(side=RIGHT, padx=self.tk_format.padx)
        zoom_label3.pack(side=RIGHT, padx=self.tk_format.padx)

        outer_outer_slope_frame = Frame(self.analysis_dialog.interior,
                                        bg=self.tk_format.bg,
                                        padx=self.tk_format.padx,
                                        pady=15,
                                        highlightthickness=1)
        outer_outer_slope_frame.pack(expand=True, fill=BOTH)

        self.outer_slope_frame = Frame(outer_outer_slope_frame,
                                       bg=self.tk_format.bg,
                                       padx=self.tk_format.padx)
        self.outer_slope_frame.pack(expand=True, fill=BOTH, pady=(0, 10))
        slope_title_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg)
        slope_title_frame.pack(pady=(5, 5))
        slope_title_label = Label(slope_title_frame,
                                  text="Analyze ",
                                  bg=self.tk_format.bg,
                                  fg=self.tk_format.textcolor)
        slope_title_label.pack(side=LEFT, pady=(0, 4))
        self.analyze_var = StringVar()
        self.analyze_var.set("slope")
        analyze_menu = OptionMenu(
            slope_title_frame,
            self.analyze_var,
            "slope",
            "band depth",
            "band center",
            "reflectance",
            # "reciprocity",
            "difference",
            command=self.disable_plot,
        )
        analyze_menu.configure(
            width=10,
            highlightbackground=self.tk_format.highlightbackgroundcolor)
        analyze_menu.pack(side=LEFT)

        # We'll put checkboxes for additional options into this frame at the time the user selects a given option (e.g.
        # select 'difference' from menu, add option to calculate differences based on absolute value
        self.extra_analysis_check_frame = Frame(self.outer_slope_frame,
                                                bg=self.tk_format.bg,
                                                padx=self.tk_format.padx)
        self.extra_analysis_check_frame.pack()

        # Note that we are not packing this checkbutton yet.
        self.abs_val_check = Checkbutton(
            self.extra_analysis_check_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=" Use absolute values for average differences",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.abs_val,
        )

        self.use_max_for_centers_check = Checkbutton(
            self.extra_analysis_check_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=
            " If band max is more prominent than\nband min, use to find center.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.use_max_for_centers,
        )
        self.use_max_for_centers_check.select()

        self.use_delta_check = Checkbutton(
            self.extra_analysis_check_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=" Center at max \u0394" +
            "R from continuum  \nrather than spectral min/max. ",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.use_delta,
        )
        self.use_delta_check.select()

        self.neg_depth_check = Checkbutton(
            self.extra_analysis_check_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=
            " If band max is more prominent than \nband min, report negative depth.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.neg_depth,
        )
        self.neg_depth_check.select()

        slope_frame = Frame(self.outer_slope_frame,
                            bg=self.tk_format.bg,
                            padx=self.tk_format.padx,
                            highlightthickness=0)
        slope_frame.pack(pady=(15, 0))

        slope_label = Label(slope_frame,
                            text="x1:",
                            bg=self.tk_format.bg,
                            fg=self.tk_format.textcolor)
        self.left_slope_entry = Entry(
            slope_frame,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        slope_label_2 = Label(slope_frame,
                              text="x2:",
                              bg=self.tk_format.bg,
                              fg=self.tk_format.textcolor)
        self.right_slope_entry = Entry(
            slope_frame,
            width=7,
            bd=self.tk_format.bd,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        slope_button = Button(
            slope_frame,
            text="Calculate",
            command=self.calculate,
            width=7,
            fg=self.tk_format.buttontextcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            bd=self.tk_format.bd,
        )
        slope_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
        )

        slope_button.pack(side=RIGHT, padx=(10, 10))
        self.right_slope_entry.pack(side=RIGHT, padx=self.tk_format.padx)
        slope_label_2.pack(side=RIGHT, padx=self.tk_format.padx)
        self.left_slope_entry.pack(side=RIGHT, padx=self.tk_format.padx)
        slope_label.pack(side=RIGHT, padx=self.tk_format.padx)
        self.slope_results_frame = Frame(self.outer_slope_frame,
                                         bg=self.tk_format.bg)
        self.slope_results_frame.pack(
            fill=BOTH, expand=True
        )  # We'll put a listbox with slope info in here later after calculating.

        outer_plot_slope_frame = Frame(outer_outer_slope_frame,
                                       bg=self.tk_format.bg,
                                       padx=self.tk_format.padx,
                                       pady=10)
        outer_plot_slope_frame.pack(expand=True, fill=BOTH)
        plot_slope_frame = Frame(outer_plot_slope_frame,
                                 bg=self.tk_format.bg,
                                 padx=self.tk_format.padx)
        plot_slope_frame.pack(side=RIGHT)
        plot_slope_label = Label(plot_slope_frame,
                                 text="Plot as a function of",
                                 bg=self.tk_format.bg,
                                 fg=self.tk_format.textcolor)
        self.plot_slope_var = StringVar()
        self.plot_slope_var.set("e")
        self.plot_slope_menu = OptionMenu(plot_slope_frame,
                                          self.plot_slope_var, "e", "i", "g",
                                          "e,i", "theta", "az, e")
        self.plot_slope_menu.configure(
            width=2,
            highlightbackground=self.tk_format.highlightbackgroundcolor)
        self.plot_slope_button = Button(
            plot_slope_frame,
            text="Plot",
            command=self.plot,
            width=7,
            fg=self.tk_format.buttontextcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            bd=self.tk_format.bd,
        )
        self.plot_slope_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            state=DISABLED,
        )
        self.plot_slope_button.pack(side=RIGHT, padx=(10, 10))
        self.plot_slope_menu.pack(side=RIGHT, padx=self.tk_format.padx)
        plot_slope_label.pack(side=RIGHT, padx=self.tk_format.padx)

        exclude_artifacts_frame = Frame(self.analysis_dialog.interior,
                                        bg=self.tk_format.bg,
                                        padx=self.tk_format.padx,
                                        pady=15,
                                        highlightthickness=1)
        exclude_artifacts_frame.pack(fill=BOTH, expand=True)

        self.exclude_artifacts_check = Checkbutton(
            exclude_artifacts_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=
            " Exclude data susceptible to artifacts\n (high g, 1000-1400 nm)  ",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.exclude_artifacts,
            # TODO: check if the comma is meant to be there in the lambda definition
            command=lambda x="foo", : self.tab.set_exclude_artifacts(
                self.exclude_artifacts.get()),
        )
        self.exclude_artifacts_check.pack()
        if self.tab.exclude_artifacts:
            self.exclude_artifacts_check.select()

        self.analysis_dialog.interior.configure(highlightthickness=1,
                                                highlightcolor="white")

    def calculate(self):
        try:
            self.controller.view_notebook.select(self.tab.top)
        except TclError:
            print("Error selecting tab in analysis_tools_manager.calculate().")
            print(self.tab)
            pass
        artifact_warning = False

        if self.analyze_var.get() == "slope":
            left, right, slopes, artifact_warning = self.tab.calculate_slopes(
                self.left_slope_entry.get(), self.right_slope_entry.get())
            self.update_entries(left, right)
            self.populate_listbox(slopes)
            self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"])

        elif self.analyze_var.get() == "band depth":
            left, right, depths, artifact_warning = self.tab.calculate_band_depths(
                self.left_slope_entry.get(),
                self.right_slope_entry.get(),
                self.neg_depth.get(),
                self.use_delta.get(),
            )
            self.update_entries(left, right)
            self.populate_listbox(depths)
            self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"])

        elif self.analyze_var.get() == "band center":
            left, right, centers, artifact_warning = self.tab.calculate_band_centers(
                self.left_slope_entry.get(),
                self.right_slope_entry.get(),
                self.use_max_for_centers.get(),
                self.use_delta.get(),
            )
            self.update_entries(left, right)
            self.populate_listbox(centers)
            self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"])

        elif self.analyze_var.get() == "reflectance":
            left, right, reflectance, artifact_warning = self.tab.calculate_avg_reflectance(
                self.left_slope_entry.get(), self.right_slope_entry.get())
            self.update_entries(left, right)
            self.populate_listbox(reflectance)
            self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"])

        elif self.analyze_var.get() == "reciprocity":
            left, right, reciprocity, artifact_warning = self.tab.calculate_reciprocity(
                self.left_slope_entry.get(), self.right_slope_entry.get())
            self.update_entries(left, right)
            self.populate_listbox(reciprocity)
            self.update_plot_menu(["e", "i", "g", "e,i"])

        elif self.analyze_var.get() == "difference":
            left, right, error, artifact_warning = self.tab.calculate_error(
                self.left_slope_entry.get(), self.right_slope_entry.get(),
                self.abs_val.get())
            # Tab validates left and right values. If they are no good, put in min and max wavelengths available.
            self.update_entries(left, right)
            self.populate_listbox(error)
            self.update_plot_menu(["\u03bb", "e,i"])

        if artifact_warning:
            ErrorDialog(
                self, "Warning",
                "Warning: Excluding data potentially\ninfluenced by artifacts from 1000-1400 nm."
            )

        self.analysis_dialog.min_height = 1000
        self.analysis_dialog.update()

    def update_plot_menu(self, plot_options):
        self.plot_slope_var.set(plot_options[0])
        self.plot_slope_menu["menu"].delete(0, "end")

        # Insert list of new options (tk._setit hooks them up to var)
        max_len = len(plot_options[0])
        for option in plot_options:
            max_len = np.max([max_len, len(option)])
            # pylint: disable = protected-access
            self.plot_slope_menu["menu"].add_command(label=option,
                                                     command=tkinter._setit(
                                                         self.plot_slope_var,
                                                         option))
        self.plot_slope_menu.configure(width=max_len)

    def update_entries(self, left, right):
        self.left_slope_entry.delete(0, "end")
        self.left_slope_entry.insert(0, str(left))
        self.right_slope_entry.delete(0, "end")
        self.right_slope_entry.insert(0, str(right))

    def populate_listbox(self, results):
        if len(results) > 0:
            self.slope_results_frame.pack(fill=BOTH,
                                          expand=True,
                                          pady=(10, 10))
            try:
                self.slopes_listbox.delete(0, "end")
            except (AttributeError, TclError):
                self.slopes_listbox = utils.ScrollableListbox(
                    self.slope_results_frame,
                    self.tk_format.bg,
                    self.tk_format.entry_background,
                    self.tk_format.listboxhighlightcolor,
                    selectmode=EXTENDED,
                )
                self.slopes_listbox.configure(height=8)
            for result in results:
                self.slopes_listbox.insert("end", result)
            self.slopes_listbox.pack(fill=BOTH, expand=True)
            self.plot_slope_button.configure(state=NORMAL)

    def plot(self):
        if self.analyze_var.get() == "slope":
            self.tab.plot_slopes(self.plot_slope_var.get())
        elif self.analyze_var.get() == "band depth":
            self.tab.plot_band_depths(self.plot_slope_var.get())
        elif self.analyze_var.get() == "band center":
            self.tab.plot_band_centers(self.plot_slope_var.get())
        elif self.analyze_var.get() == "reflectance":
            self.tab.plot_avg_reflectance(self.plot_slope_var.get())
        elif self.analyze_var.get() == "reciprocity":
            self.tab.plot_reciprocity(self.plot_slope_var.get())
        elif self.analyze_var.get() == "difference":
            new = self.tab.plot_error(self.plot_slope_var.get())
            if self.plot_slope_var.get() == "\u03bb":
                x1 = float(self.left_slope_entry.get())
                x2 = float(self.right_slope_entry.get())
                new.adjust_x(x1, x2)
        # TODO: plots not always fully updating
        #  (e.g. contour plot labels not showing up until you do a screen wiggle.

        # utils.thread_lift_widget(self.analysis_dialog.top)

    def normalize(self):
        self.select_tab()
        try:
            self.slopes_listbox.delete(0, "end")
            self.plot_slope_button.configure(state="disabled")
        except (AttributeError, TclError):
            pass
        self.tab.normalize(self.normalize_entry.get())
        # thread = Thread(target=utils.lift_widget, args=(self.analysis_dialog.top,))
        # thread.start()

    def offset(self):
        self.tab.offset(self.offset_sample_var.get(), self.offset_entry.get())

        # This doesn't work - it hangs between thread.start() and thread.join(). Likely because of calls to canvas.draw()
        # thread = Thread(target=self.tab.offset, args=(self.offset_sample_var.get(), self.offset_entry.get()))
        # thread.start()
        # thread.join()
        # utils.lift_widget(self.analysis_dialog.top)

    def remove_topmost(self):
        print("removing!!")
        self.analysis_dialog.top.attributes("-topmost", False)

    def apply_x(self):
        self.controller.view_notebook.select(self.tab.top)

        try:
            x1 = float(self.left_zoom_entry.get())
            x2 = float(self.right_zoom_entry.get())
            self.tab.adjust_x(x1, x2)
            # utils.lift_widget(self.analysis_dialog.top)
        except ValueError:
            # utils.lift_widget(self.analysis_dialog.top)
            ErrorDialog(
                self,
                title="Invalid Zoom Range",
                label="Error! Invalid x limits: " +
                self.left_zoom_entry.get() + ", " +
                self.right_zoom_entry.get(),
            )

    def apply_y(self):
        self.controller.view_notebook.select(self.tab.top)
        try:
            y1 = float(self.left_zoom_entry2.get())
            y2 = float(self.right_zoom_entry2.get())
            self.tab.adjust_y(y1, y2)
            # utils.lift_widget(self.analysis_dialog.top)
        except ValueError:
            # utils.lift_widget(self.analysis_dialog.top)
            ErrorDialog(
                self,
                title="Invalid Zoom Range",
                label="Error! Invalid y limits: " +
                self.left_zoom_entry2.get() + ", " +
                self.right_zoom_entry2.get(),
            )

    def uncheck_exclude_artifacts(self):
        self.exclude_artifacts.set(0)
        self.exclude_artifacts_check.deselect()
        # utils.lift_widget(self.analysis_dialog.top)

    def disable_plot(self, analyze_var="None"):
        try:
            self.slopes_listbox.delete(0, "end")
        except (AttributeError, TclError):
            pass
        self.plot_slope_button.configure(state="disabled")

        if analyze_var == "difference":
            self.analysis_dialog.frame.min_height = 850
            self.neg_depth_check.pack_forget()
            self.use_max_for_centers_check.pack_forget()
            self.use_delta_check.pack_forget()
            self.abs_val_check.pack()
            self.extra_analysis_check_frame.pack()

        elif analyze_var == "band center":
            self.analysis_dialog.frame.min_height = 1000
            self.neg_depth_check.pack_forget()
            self.abs_val_check.pack_forget()
            self.use_delta_check.pack_forget()
            self.use_max_for_centers_check.pack()
            self.use_delta_check.pack()
            self.extra_analysis_check_frame.pack()

        elif analyze_var == "band depth":
            self.analysis_dialog.frame.min_height = 1000
            self.abs_val_check.pack_forget()
            self.use_max_for_centers_check.pack_forget()
            self.use_delta_check.pack_forget()
            self.neg_depth_check.pack()
            self.use_delta_check.pack()
            self.extra_analysis_check_frame.pack()

        else:
            self.analysis_dialog.frame.min_height = 850
            self.abs_val_check.pack_forget()
            self.neg_depth_check.pack_forget()
            self.use_max_for_centers_check.pack_forget()
            self.use_delta_check.pack_forget()

            self.extra_analysis_check_frame.grid_propagate(0)
            self.extra_analysis_check_frame.configure(
                height=1)  # for some reason 0 doesn't work.
            self.extra_analysis_check_frame.pack()
            self.outer_slope_frame.pack()
        # utils.lift_widget(self.analysis_dialog.top)

    # def calculate_photometric_variability(self):
    #     photo_var = self.tab.calculate_photometric_variability(
    #         self.right_photo_var_entry.get(), self.left_photo_var_entry.get()
    #     )
    #     try:
    #         self.photo_var_listbox.delete(0, "end")
    #     except:
    #         self.photo_var_listbox = utils.ScrollableListbox(
    #             self.photo_var_results_frame,
    #             self.tk_format.bg,
    #             self.tk_format.entry_background,
    #             self.tk_format.listboxhighlightcolor,
    #             selectmode=EXTENDED,
    #         )
    #     for var in photo_var:
    #         self.photo_var_listbox.insert("end", var)
    #     self.photo_var_listbox.pack(fill=BOTH, expand=True)

    def select_tab(self):
        self.controller.view_notebook.select(self.tab.top)
コード例 #17
0
def _deselectCheckbutton(cb: tk.Checkbutton):
    cb.deselect()
コード例 #18
0
class EvernoteDumpFrame(Frame):
    def __init__(self, master: EvernoteDump):
        super().__init__(master)

        self.master = master
        self.pack(fill="both")

        self.open_button = Button(
            text='Choose Evernote Export File(s) (.enex)',
            command=self.open_file_picker)
        self.open_button.pack(fill='x', padx=10, pady=10)

        self.export_files_list = Listbox(height=4)
        self.export_files_list.insert(0, "No files selected.")
        self.export_files_list.pack(fill='x', padx=10, pady=10)

        self.preserve = IntVar()
        self.preserve_names = Checkbutton(
            text='Preserve file names for attachments if found',
            variable=self.preserve,
            command=self.toggle_preserve)
        self.preserve_names.pack(anchor='nw', padx=10, pady=10)

        self.use_title = IntVar()
        self.use_title_for_names = Checkbutton(
            text='Use the note\'s title for file attachments',
            variable=self.use_title,
            command=self.toggle_use_title)
        self.use_title_for_names.pack(anchor='nw', padx=10, pady=10)

        self.export_dir_button = Button(text='Choose Export Directory',
                                        command=self.open_directory_picker)
        self.export_dir_button.pack(fill='x', padx=10, pady=10)

        self.export_dir_label = Label(text="Please select an export directory")
        self.export_dir_label.pack(fill='x', padx=10, pady=10)

        self.run_button = Button(text='Start Evernote Conversion to Markdown',
                                 state=DISABLED,
                                 command=self.run)
        self.run_button.pack(fill='x', padx=10, pady=10)

        self.log_box = scrolledtext.ScrolledText()
        self.log_box.pack(fill='x', padx=10, pady=10)

    def check(self):
        if len(self.master.settings.files
               ) > 0 and self.master.settings.export_path != '':
            self.run_button.config(state=NORMAL)
        else:
            self.run_button.config(state=DISABLED)

    def open_directory_picker(self):
        self.master.settings.path = filedialog.askdirectory()
        self.export_dir_label.config(text=f"{self.master.settings.path}")

        self.check()

    def open_file_picker(self):
        self.master.settings.enex = filedialog.askopenfilenames()
        self.export_files_list.delete(0, END)
        for file in self.master.settings.enex:
            self.export_files_list.insert(0, file)

        self.check()

    def run(self):
        self.run_button.config(state=DISABLED)

        def print_callback(print_text: str):
            self.log_box.insert(END, f"{print_text}\n")
            self.log_box.see(END)

        threading.Thread(target=run_parse,
                         args=(self.master.settings, print_callback)).start()

    def toggle_preserve(self):
        self.master.settings.p = bool(self.preserve)
        self.master.settings.n = False
        self.use_title_for_names.deselect()

    def toggle_use_title(self):
        self.master.settings.n = bool(self.preserve)
        self.master.settings.p = False
        self.preserve_names.deselect()
コード例 #19
0
class Page1(Frame):
    def __init__(self, master):
        super().__init__(master, relief='flat', borderwidth=20)
        self.business_logic = BusinessLogic()
        self.init_ui()

    def chk_btn1_onclick(self):
        checked = self.chk_btn_var1.get()
        if checked:
            self.qty_entry1.configure(state=NORMAL)
        else:
            self.qty_entry1.configure(state=NORMAL)
        self.enable_btn()

    def chk_btn2_onclick(self):
        checked = self.chk_btn_var2.get()
        if checked:
            self.qty_entry2.configure(state=NORMAL)
        else:
            self.qty_entry2.configure(state=NORMAL)
        self.enable_btn()

    def chk_btn3_onclick(self):
        checked = self.chk_btn_var3.get()
        if checked:
            self.qty_entry3.configure(state=NORMAL)
        else:
            self.qty_entry3.configure(state=NORMAL)
        self.enable_btn()

    def chk_btn4_onclick(self):
        checked = self.chk_btn_var4.get()
        if checked:
            self.qty_entry4.configure(state=NORMAL)
        else:
            self.qty_entry4.configure(state=NORMAL)
        self.enable_btn()

    def chk_btn5_onclick(self):
        checked = self.chk_btn_var5.get()
        if checked:
            self.qty_entry5.configure(state=NORMAL)
        else:
            self.qty_entry5.configure(state=NORMAL)
        self.enable_btn()

    def enable_btn(self):
        if any((self.chk_btn_var1.get(), self.chk_btn_var2.get(),
                self.chk_btn_var3.get(), self.chk_btn_var4.get(),
                self.chk_btn_var5.get())):
            self.gen_receipt_btn.configure(state=NORMAL)
        else:
            self.gen_receipt_btn.configure(state=DISABLED)

    def qty_entry1_keybind(self, event):
        self.validate_for_int(event, self.qty_entry1)

    def qty_entry2_keybind(self, event):
        self.validate_for_int(event, self.qty_entry2)

    def qty_entry3_keybind(self, event):
        self.validate_for_int(event, self.qty_entry3)

    def qty_entry4_keybind(self, event):
        self.validate_for_int(event, self.qty_entry4)

    def qty_entry5_keybind(self, event):
        self.validate_for_int(event, self.qty_entry5)

    def validate_for_int(self, event, widget):
        val = widget.get()
        try:
            float(widget.get())
        except ValueError as verr:
            print(str(verr))
            if not event.char.isdigit():
                widget.delete(0, END)
                widget.insert(0, val[:-1])

    def _set_header(self):
        for col, item in enumerate(self.business_logic.header):
            Label(self, text=item, font='Helvetica 12 bold').grid(row=0,
                                                                  column=col,
                                                                  sticky='NW')

    def _set_body(self):
        self.chk_btn_var1 = BooleanVar()
        self.chk_btn_var2 = BooleanVar()
        self.chk_btn_var3 = BooleanVar()
        self.chk_btn_var4 = BooleanVar()
        self.chk_btn_var5 = BooleanVar()

        # order column
        self.chk_btn1 = Checkbutton(self,
                                    text="",
                                    variable=self.chk_btn_var1,
                                    command=self.chk_btn1_onclick)
        self.chk_btn1.grid(row=1, column=0, sticky='NW')
        self.chk_btn2 = Checkbutton(self,
                                    text="",
                                    variable=self.chk_btn_var2,
                                    command=self.chk_btn2_onclick)
        self.chk_btn2.grid(row=2, column=0, sticky='NW')
        self.chk_btn3 = Checkbutton(self,
                                    text="",
                                    variable=self.chk_btn_var3,
                                    command=self.chk_btn3_onclick)
        self.chk_btn3.grid(row=3, column=0, sticky='NW')
        self.chk_btn4 = Checkbutton(self,
                                    text="",
                                    variable=self.chk_btn_var4,
                                    command=self.chk_btn4_onclick)
        self.chk_btn4.grid(row=4, column=0, sticky='NW')
        self.chk_btn5 = Checkbutton(self,
                                    text="",
                                    variable=self.chk_btn_var5,
                                    command=self.chk_btn5_onclick)
        self.chk_btn5.grid(row=5, column=0, sticky='NW')

        # item column
        for row, item in enumerate(self.business_logic.items.keys()):
            _row = row + 1
            Label(self, text=f"{item}").grid(row=_row, column=1, sticky='NW')

        # unit price column
        for row, unit_price in enumerate(self.business_logic.items.values()):
            _row = row + 1
            Label(self, text=f"{unit_price}₹").grid(row=_row,
                                                    column=2,
                                                    sticky='NW')

        # quantity column
        self.qty_entry1 = Entry(self, state=DISABLED)
        self.qty_entry1.grid(row=1, column=3)
        self.qty_entry2 = Entry(self, state=DISABLED)
        self.qty_entry2.grid(row=2, column=3)
        self.qty_entry3 = Entry(self, state=DISABLED)
        self.qty_entry3.grid(row=3, column=3)
        self.qty_entry4 = Entry(self, state=DISABLED)
        self.qty_entry4.grid(row=4, column=3)
        self.qty_entry5 = Entry(self, state=DISABLED)
        self.qty_entry5.grid(row=5, column=3)
        self.qty_entry1.bind('<KeyRelease>', self.qty_entry1_keybind)
        self.qty_entry2.bind('<KeyRelease>', self.qty_entry2_keybind)
        self.qty_entry3.bind('<KeyRelease>', self.qty_entry3_keybind)
        self.qty_entry4.bind('<KeyRelease>', self.qty_entry4_keybind)
        self.qty_entry5.bind('<KeyRelease>', self.qty_entry5_keybind)

        self.gen_receipt_btn = Button(self,
                                      text="Generate Receipt",
                                      command=self.on_gen_receipt_btn_click)
        self.gen_receipt_btn.grid(row=8, column=2, padx=20, pady=20)
        self.gen_receipt_btn.configure(state=DISABLED)

        self.cancel_btn = Button(self,
                                 text="Clear",
                                 command=self.on_cancel_btn_click)
        self.cancel_btn.grid(row=8, column=3, padx=20, pady=20)

        Label(self,
              text='(Select your orders and then enter the quantities)',
              font='Helvetica 8 italic').grid(row=9, columnspan=4, sticky='NW')

    def init_ui(self):
        self.master.title(self.business_logic.title)
        self.pack(fill=None, expand=False)
        self._set_header()
        self._set_body()

    def on_cancel_btn_click(self):
        self.clear_all()

    def on_gen_receipt_btn_click(self):
        qty1 = self.qty_entry1.get().strip()
        qty2 = self.qty_entry2.get().strip()
        qty3 = self.qty_entry3.get().strip()
        qty4 = self.qty_entry4.get().strip()
        qty5 = self.qty_entry5.get().strip()
        if any((qty1, qty2, qty3, qty4, qty5)):

            for item, qty in zip(self.business_logic.items,
                                 (qty1, qty2, qty3, qty4, qty5)):
                if bool(qty):
                    self.business_logic.set(item, qty)

            Page2(self.master, self).show()
        else:
            messagebox.showwarning("Quantities", "Empty quantity fields")

    def clear_all(self):
        self.chk_btn1.deselect()
        self.chk_btn2.deselect()
        self.chk_btn3.deselect()
        self.chk_btn4.deselect()
        self.chk_btn5.deselect()

        self.qty_entry1.delete(0, END)
        self.qty_entry2.delete(0, END)
        self.qty_entry3.delete(0, END)
        self.qty_entry4.delete(0, END)
        self.qty_entry5.delete(0, END)

        self.qty_entry1.configure(state=DISABLED)
        self.qty_entry2.configure(state=DISABLED)
        self.qty_entry3.configure(state=DISABLED)
        self.qty_entry4.configure(state=DISABLED)
        self.qty_entry5.configure(state=DISABLED)
        self.gen_receipt_btn.configure(state=DISABLED)

        self.business_logic = BusinessLogic()
コード例 #20
0
    def _create_windowview(self, parent, playlistTable):
        label = tk.Label(self.editPlaylistNameWindow, text="リスト名 :")
        label.grid(row=0, column=0, sticky="w", padx=10, pady=(10, 10))

        self.entry_list_name = Entry(self.editPlaylistNameWindow)
        self.entry_list_name.grid(row=0, column=1, columnspan=3, sticky="we")

        label = tk.Label(self.editPlaylistNameWindow, text="定型文 :")
        label.grid(row=1, column=0, sticky="w", padx=10)

        self.cb_regular_gate = Combobox(self.editPlaylistNameWindow,
                                        state="readonly")
        self.refresh_cb_regular_gate()
        self.cb_regular_gate.current(0)
        self.cb_regular_gate.grid(row=1, column=1, columnspan=3, sticky="wens")

        self.set_entry_list_name(playlistTable)

        settingBtnFrame = tk.Frame(self.editPlaylistNameWindow)
        settingBtnFrame.grid(row=0, column=4, rowspan=3, sticky='ens')

        btn_setting_playlist = Button(
            settingBtnFrame,
            text="設定",
            command=lambda: self.update_playlist_name(playlistTable))
        btn_setting_playlist.grid(sticky='wens',
                                  row=0,
                                  column=0,
                                  padx=5,
                                  pady=(10, 10),
                                  ipadx=5,
                                  ipady=3)

        btn_cancel = Button(settingBtnFrame,
                            text="キャンセル",
                            command=self.close_window)
        btn_cancel.grid(sticky='wens',
                        row=1,
                        column=0,
                        padx=5,
                        ipadx=5,
                        ipady=3)

        regularGateFrame = tk.Frame(self.editPlaylistNameWindow)
        regularGateFrame.grid(row=2, column=0, sticky='wens')

        ck_apply_only_regular_gate = Checkbutton(
            regularGateFrame,
            variable=self.ckValue_apply_only_reguar_gate,
            text="定型文のみ変更",
            onvalue=True,
            offvalue=False)
        ck_apply_only_regular_gate.deselect()
        ck_apply_only_regular_gate.grid(row=0,
                                        column=0,
                                        padx=(6, 0),
                                        pady=(10, 0),
                                        sticky="")

        btn_update_regular_gates = Button(
            regularGateFrame,
            text="定型文編集",
            command=lambda: self.regular_gate_list(parent, playlistTable))
        btn_update_regular_gates.grid(row=1,
                                      column=0,
                                      padx=(10, 0),
                                      pady=(5, 0),
                                      ipady=3,
                                      sticky='we')

        updateModeFrame = tk.LabelFrame(self.editPlaylistNameWindow,
                                        text='変更モード')
        updateModeFrame.grid(row=2,
                             column=2,
                             columnspan=2,
                             rowspan=2,
                             sticky='wens',
                             padx=(10, 0),
                             pady=10)

        rb_selection_update = tk.Radiobutton(
            updateModeFrame,
            text="選択行のみ",
            value=1,
            variable=self.rbPlayListNameUpdateModeValue)
        rb_samename_update = tk.Radiobutton(
            updateModeFrame,
            text="同ー名のみ",
            value=2,
            variable=self.rbPlayListNameUpdateModeValue)
        rb_all_update = tk.Radiobutton(
            updateModeFrame,
            text="全て",
            value=3,
            variable=self.rbPlayListNameUpdateModeValue)
        rb_selection_update.grid(row=0,
                                 column=0,
                                 sticky='w',
                                 padx=10,
                                 pady=(10, 0))
        rb_samename_update.grid(row=1,
                                column=0,
                                sticky='w',
                                padx=10,
                                pady=(5, 0))
        rb_all_update.grid(row=2, column=0, sticky='w', padx=10, pady=(5, 0))
コード例 #21
0
    def __init__(self, masterwin, songindex=None, url=None):
        if songindex == None:
            self.new = True
        else:
            self.new = False

        self.songindex = songindex
        self.masterwin = masterwin
        self.t = Toplevel(masterwin.master)
        self.t.wm_title('Lägg till ny låt')
        self.t.pack_propagate(0)

        lab = Label(self.t, text="Spotify Link", width=10, height=2)
        lab.grid(row=0, column=0, columnspan=2)
        self.spotifylink = Entry(self.t, width=25)
        self.spotifylink.grid(row=1, column=0, columnspan=1)
        self.spotifylink.focus_set()

        self.spotifylink.delete(0, END)

        Button(self.t,
               text="Lägg till",
               width=10,
               height=1,
               command=self.spotifysearch).grid(row=1, column=1)

        lab = Label(self.t, text="Artist", width=10, height=2)
        lab.grid(row=2, column=0, columnspan=2)

        self.artist = Entry(self.t, width=40)
        self.artist.grid(row=3, column=0, columnspan=2)
        self.artist.focus_set()

        self.artist.delete(0, END)
        self.artist.insert(0, "")

        lab = Label(self.t, text="Sång", width=10, height=2)
        lab.grid(row=4, column=0, columnspan=2)

        self.song = Entry(self.t, width=40)
        self.song.grid(row=5, column=0, columnspan=2)
        self.song.focus_set()

        self.song.delete(0, END)
        self.song.insert(0, "")

        lab = Label(self.t, text="BPM", width=10, height=2)
        lab.grid(row=6, column=0, columnspan=2)

        self.bpm = Entry(self.t, width=30)
        self.bpm.grid(row=7, column=0, columnspan=2)
        self.bpm.focus_set()

        self.song.delete(0, END)
        self.song.insert(0, "")

        self.isused = StringVar()
        check = Checkbutton(self.t, text='Redan använd', variable=self.isused)
        check.grid(row=8, column=0, columnspan=2)
        check.deselect()

        self.chosen_genres = []
        self.chosen_blocks = []

        Button(self.t, text="Genre", width=20, height=2,
               command=self.addGenre).grid(row=9, column=0)
        Button(self.t, text="Block", width=20, height=2,
               command=self.addBlock).grid(row=9, column=1)

        if not self.new:
            self.artist.insert(
                END, self.masterwin.fsongs.allsongs[self.songindex].artist)
            self.song.insert(
                END, self.masterwin.fsongs.allsongs[self.songindex].song)
            self.bpm.insert(
                END, str(self.masterwin.fsongs.allsongs[self.songindex].bpm))
            self.spotifylink.insert(
                END,
                self.masterwin.fsongs.allsongs[self.songindex].spotifylink)
            self.chosen_genres = self.masterwin.fsongs.allsongs[
                self.songindex].genre
            self.chosen_blocks = self.masterwin.fsongs.allsongs[
                self.songindex].fits
            if self.masterwin.fsongs.allsongs[self.songindex].used:
                check.select()

        Button(self.t,
               text="Spara",
               width=15,
               height=2,
               command=self.addAndSave).grid(row=10, column=0)
        Button(self.t,
               text="Avbryt",
               width=15,
               height=2,
               command=self.t.destroy).grid(row=10, column=1)

        if url != None:
            print(url)
            self.spotifylink.insert(0, url)
            self.spotifysearch()
        else:
            self.spotifylink.insert(0, "")
コード例 #22
0
class MyFirstGUI1:
    symptoms = []
    Sym = []
    symp_val = []
    i = 2
    j = 0
    k = 0
    result = ""
    def __init__(self, master):
        self.master = master
        master.title("Disease Predictor")

        self.dataloading()

        self.label = Label(master, text="select the problems you are facing:")
        self.label.grid(column=0, row=1)

        for feel in self.symptoms:
            self.symp_val.append(IntVar())
            self.l = Checkbutton(self.master, text=feel, variable=self.symp_val[self.k])
            self.l.grid(column=self.j, row=self.i, sticky='w')
            self.l.deselect()

            self.k = self.k+1
            if(self.j < 5):
                    self.j =self.j+1
            else:
                self.j = 0
                self.i = self.i + 1

        self.Diagnosis = Button(master, text="Start Diagnosis", command=self.diagnosis)
        self.Diagnosis.grid(column=10, row=2)

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.grid(column=10, row=3)

        """self.scrollbar = Scrollbar(master)
        self.scrollbar.grid(column=5)"""



    def mlalgo(self):
        import pandas as pd
        import numpy as np

        # importing data
        dataset = pd.read_csv('Training.csv')
        dataset1 = pd.read_csv('Testing.csv')

        # matrix of features
        X_train = dataset.iloc[:, 0:-1].values
        Y_train = dataset.iloc[:, 132]
        X_test = dataset1.iloc[:, 0:-1].values
        Y_test = dataset1.iloc[:, 132]

        # categorizing the data
        from sklearn.preprocessing import LabelEncoder
        lblenc_train = LabelEncoder()
        lblenc_test = LabelEncoder()
        lblenc_train.fit_transform(Y_train)
        lblenc_test.fit_transform(Y_test)

        from sklearn.tree import DecisionTreeClassifier
        # create naive byes object
        nB = DecisionTreeClassifier(criterion='entropy')

        # train the model using the training sets
        nB.fit(X_train, Y_train)

        # making predictions on the testing set
        y_pred = nB.predict(X_test)

        # processing user data to make it fit in algorithm
        arr = np.asarray(self.Sym)
        mat = np.zeros((132, 132), dtype=int)
        mat[0] = arr
        # print(mat)
        new_df = pd.DataFrame(columns=self.symptoms, data=mat)
        print(new_df)
        new_df1 = pd.DataFrame()
        new_df1 = new_df[0:1]
        print(new_df1)
        # making prediction on user data
        Y_check = nB.predict(new_df1)
        print(Y_check)
        self.result = Y_check[0]



    def diagnosis(self):
        print("keep calm nothing serious!")
        for i in range(0, 132):
            if self.symp_val[i].get() == 1:
                self.Sym[i] = 1
        self.disp()
        self.mlalgo()
        variable = messagebox.askquestion('your diaganosis', self.result)
        if variable:
            self.master.quit()


    def disp(self):
        print(len(self.Sym))


    def dataloading(self):
        import pandas as pd
        dataset = pd.read_csv('Training.csv')
        self.symptoms = list(dataset)
        self.symptoms = self.symptoms[:-1]
        print(len(self.symptoms))
        # crating numeric array which is checked in model
        for i in range(0, 132):
            #print(i)
            self.Sym.append(0)
コード例 #23
0
    def __init__(self, master, songfile):
        self.songfile = songfile
        self.master = master

        self.width = master.winfo_screenwidth()
        self.height = master.winfo_screenheight()
        if self.width > self.height:
            self.width = self.width * 2 / 5
        else:
            self.width = self.width * 2 / 3
        self.height = self.height * 2 / 3
        #        self.master.geometry(str(int(self.width)) + 'x' + str(int(self.height)))
        frame = Frame(self.master)

        self.fsongs = fsongs.friskissongs()
        self.fsongs.loadSongsFromYaml(songfile)
        self.master.title("Friskismusik")

        # bpm search critera

        bpmwin = LabelFrame(self.master, text="BPM sökning", padx=5, pady=3)
        bpmwin.pack(padx=10, pady=10)

        lab = Label(bpmwin, text="BPM", width=20, height=2)
        lab.grid(row=0, column=0)
        self.bpm = Entry(bpmwin, width=20)
        self.bpm.grid(row=1, column=0)
        self.bpm.focus_set()

        self.bpm.delete(0, END)
        self.bpm.insert(0, "0")

        lab = Label(bpmwin, text="BPM tolerans", width=10, height=2)
        lab.grid(row=0, column=1)

        self.bpmtol = Entry(bpmwin, width=10)
        self.bpmtol.grid(row=1, column=1)
        self.bpmtol.focus_set()

        self.bpmtol.delete(0, END)
        self.bpmtol.insert(0, "5")

        self.showused = StringVar()
        check = Checkbutton(bpmwin,
                            text='Visa använda',
                            variable=self.showused)
        check.grid(row=0, column=2)
        check.deselect()

        self.doublebpm = StringVar()
        check = Checkbutton(bpmwin,
                            text='Visa Dubbla BPM',
                            variable=self.doublebpm)
        check.grid(row=1, column=2)
        check.deselect()

        # artist seach

        artistwin = LabelFrame(self.master,
                               text="Sång preferenser",
                               padx=5,
                               pady=3)
        artistwin.pack(padx=10, pady=10)

        lab = Label(artistwin, text="Artist", width=10, height=2)
        lab.grid(row=0, column=0)

        self.artist = Entry(artistwin, width=30)
        self.artist.grid(row=1, column=0)
        self.artist.focus_set()

        self.artist.delete(0, END)
        self.artist.insert(0, "")

        lab = Label(artistwin, text="Song", width=10, height=2)
        lab.grid(row=0, column=1)

        self.song = Entry(artistwin, width=30)
        self.song.grid(row=1, column=1)
        self.song.focus_set()

        self.song.delete(0, END)
        self.song.insert(0, "")

        # typer
        typewin = LabelFrame(self.master, text="Typ av musik", padx=5, pady=3)
        typewin.pack(padx=10, pady=10)

        lab = Label(typewin, text="Passar till", width=20, height=2)
        lab.grid(row=0, column=0)
        StringVar, Checkbutton, OptionMenu
        self.fitsfor = StringVar()
        self.fitsfor.set('Välj Block')
        fitsforlist = OptionMenu(typewin, self.fitsfor,
                                 *set(jtypes.blocktypes + ['Välj Block']))
        fitsforlist.grid(row=1, column=0)

        lab = Label(typewin, text="Genre", width=20, height=2)
        lab.grid(row=0, column=1)

        self.genre = StringVar()
        self.genre.set('Välj Genre')
        genrelist = OptionMenu(typewin, self.genre,
                               *set(jtypes.genres + ['Välj Genre']))
        genrelist.grid(row=1, column=1)

        searchwindow = LabelFrame(self.master, text="Val", padx=1, pady=3)
        searchwindow.pack(padx=10, pady=10)

        Button(searchwindow,
               text="Sök",
               width=15,
               height=2,
               command=self.search).grid(row=0, column=0)
        Button(searchwindow,
               text="Lägg till låt",
               width=15,
               height=2,
               command=self.add_song).grid(row=0, column=1)
        Button(searchwindow,
               text="Välj från låtlista",
               width=15,
               height=2,
               command=self.from_list).grid(row=0, column=2)
        Button(searchwindow,
               text="Stäng",
               width=15,
               height=2,
               command=frame.quit).grid(row=0, column=3)
コード例 #24
0
class ControlAnnouncement:
    def __init__(self, parent):
        self.announcement = Announcement(
            sorted(list(users.keys()))[0],
            sorted(list(mail.keys()))[0])
        self.initializeGui(parent)

    def initializeGui(self, parent):
        self.parent = parent
        self.frame = Frame(self.parent)
        self.frame.grid(column=0, row=0)

        Label(self.frame, text="User").grid(row=0, sticky=W)
        Label(self.frame, text="Type").grid(row=1, sticky=W)

        userList = sorted(list(users.keys()))
        self.comboBoxUser = Combobox(self.frame,
                                     state="readonly",
                                     width=20,
                                     values=userList)
        self.comboBoxUser.set(userList[0])
        self.comboBoxUser.grid(row=0, column=1, sticky=W)
        self.comboBoxUser.bind('<<ComboboxSelected>>', self.updateUser)

        announcementTypes = sorted(list(mail.keys()))
        self.comboBoxType = Combobox(self.frame,
                                     state="readonly",
                                     width=35,
                                     values=announcementTypes)
        self.comboBoxType.set(announcementTypes[0])
        self.comboBoxType.grid(row=1, column=1, sticky=W)
        self.comboBoxType.bind('<<ComboboxSelected>>', self.updateType)

        self.scolledText = ScrolledText(self.frame,
                                        wrap=WORD,
                                        width=80,
                                        height=15)
        self.scolledText.grid(row=2, column=1, columnspan=2)
        self.scolledText.config(state=NORMAL)
        self.scolledText.insert(INSERT, self.announcement.message.as_string())
        self.scolledText.config(state=DISABLED)

        self.buttonSendTestMail = Button(self.frame,
                                         text='Send Test Mail',
                                         command=self.sendTestMail)
        self.buttonSendTestMail.grid(row=4, column=1)

        self.buttonSendMail = Button(self.frame,
                                     text='Send Mail',
                                     command=self.sendMail)
        self.buttonSendMail.grid(row=4, column=2)

        self.checkButtonAttachmentAvailable = Checkbutton(
            self.frame, text="Attachments available")
        self.checkButtonAttachmentAvailable.grid(row=3, sticky=W)

        self.checkAttachments()

    def checkAttachments(self):
        key = self.announcement.getAttachmentKey()
        print("Info: Attachment key is " + str(key))
        self.checkButtonAttachmentAvailable.config(state=NORMAL)
        if key is None:
            self.checkButtonAttachmentAvailable.deselect()
            self.buttonSendTestMail.config(state=NORMAL)
            self.buttonSendMail.config(state=NORMAL)
        else:
            if not self.announcement.attachmentsMissing():
                self.checkButtonAttachmentAvailable.select()
                self.buttonSendTestMail.config(state=NORMAL)
                self.buttonSendMail.config(state=NORMAL)
            else:
                self.checkButtonAttachmentAvailable.deselect()
                # self.buttonSendTestMail.config(state=DISABLED)
                self.buttonSendMail.config(state=DISABLED)
        self.checkButtonAttachmentAvailable.config(state=DISABLED)

    def updateUser(self, *args):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        self.announcement.setUser(self.comboBoxUser.get())
        self.scolledText.config(state=NORMAL)
        self.scolledText.delete(1.0, END)
        self.scolledText.insert(INSERT, self.announcement.message.as_string())
        self.scolledText.config(state=DISABLED)
        self.checkAttachments()

    def updateType(self, *args):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        self.announcement.setMailType(self.comboBoxType.get())
        self.scolledText.config(state=NORMAL)
        self.scolledText.delete(1.0, END)
        self.scolledText.insert(INSERT, self.announcement.message.as_string())
        self.scolledText.config(state=DISABLED)
        self.checkAttachments()

    def sendTestMail(self):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        self.announcement.sendTestMail()

    def sendMail(self):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        pwDialog = PasswordDialog(
            self.frame, title=self.announcement.getFullAddressList()[0])
        # print(pwDialog.result)
        if pwDialog.result:
            self.announcement.attach()
            self.announcement.sendMail(pwDialog.result)
            self.announcement.renderMessage()
コード例 #25
0
ファイル: 19_vars.py プロジェクト: slavaider/python
    check_button2 = Checkbutton(root,
                                text="Квадрат",
                                variable=var1,
                                onvalue="square",
                                offvalue="-")
    check_button3 = Checkbutton(root,
                                text="Треугольник",
                                variable=var2,
                                onvalue="triangle",
                                offvalue="-")
    list_box = Listbox(root, height=3)

    button = Button(root, text="Получить значения")
    button.bind('<Button-1>', result)

    check_button1.deselect()  # "по умолчанию" флажки сняты
    check_button2.deselect()
    check_button3.deselect()

    v = StringVar()
    ent1 = Entry(root, textvariable=v, bg="black", fg="white")
    ent2 = Entry(root, textvariable=v)

    ent1.pack()
    ent2.pack()
    check_button1.pack()
    check_button2.pack()
    check_button3.pack()
    button.pack()
    list_box.pack()