예제 #1
0
def update_server(frame, server_key):
    show_server = Message(frame,
                          text=server_key,
                          aspect=2000,
                          anchor=W,
                          relief=SUNKEN)
    show_server.place(x=80, y=30, width=215, height=30)
예제 #2
0
def codeCreateUrgency():

    # Interfaz para seleccionar el archivo Excel que contienen los datos necesarios para la creación del cambio
    root.filename = filedialog.askopenfilename(
        filetypes=[("Excel files", ".xlsx .xls .xlsm")])

    # Guarda los respectivos datos para la creación del CH
    dataCH = ReadDataInfo(root.filename)
    tasks, countRB = ReadDataSub(root.filename)

    # crear el cambio
    estadoCH, urlCH = CreationCHU(dataCH, tasks, countRB)

    # Devuelve el resultado de la ejecución del CH
    returnStatus.set(estadoCH)
    returnURL.set(urlCH)

    # Mensajes en la pantalla según el return de la funcion CreationCH
    resultStatus = Message(frame, textvariable=returnStatus, bg="#f8f8fb", fg="#c65185", font=(
        "Alata", 9), width=210, justify="center", cursor="center_ptr")
    resultStatus.place(x=108, y=150)

    resultURL = Entry(frame, textvariable=returnURL, bg="#f8f8fb",
                      fg="#3d3132", font=("Alata", 7), width=52, justify="center")
    resultURL.place(x=83, y=180)
예제 #3
0
    def _message_prompt(self, title, text, width=400, height=300, normal=True):
        top = Toplevel(self.root)
        top.geometry("%dx%d%+d%+d" % (width, height, 250, 125))
        top.title(title)
        help_message = text
        msg = Message(top,
                      text=help_message,
                      justify='left',
                      width=width - 100)
        msg.place(relx=0.5, rely=0.4, anchor='center')
        if normal:
            Button(top, text='Dismiss',
                   command=top.destroy).place(relx=0.5,
                                              rely=0.9,
                                              anchor='center')
        else:

            def couple_func():
                top.destroy()
                self.result_dir = filedialog.askdirectory(
                    title='Select a directory to save results ...',
                    mustexist=True)
                self.count_launch()

            Button(top, text='Continue',
                   command=couple_func).place(relx=0.5,
                                              rely=0.8,
                                              anchor='center')
            Button(top, text='Cancel',
                   command=top.destroy).place(relx=0.5,
                                              rely=0.9,
                                              anchor='center')
예제 #4
0
def create():
    top = Toplevel()
    top.title('使用提示')
    top.geometry("400x400")
    t = "关于照片,新建一个存放图片的文件,用英文命名,然后存里面的图片也用英文命名。关于音乐: 新建一个名字叫音乐的文件,把歌曲添加到该文件夹。"
    msg = Message(top, text=t)
    msg.config(font=('times', 24, 'italic'))
    msg.place(x=0, y=0)
예제 #5
0
def yes_button(label3, label4, new_word, yes, no):
    out = get_meaning(new_word)
    label3.after(25, label3.destroy())
    label4.after(25, label4.destroy())
    yes.after(50, yes.destroy())
    no.after(25, no.destroy())

    label5 = Label(root,
                   text=new_word,
                   bg='black',
                   fg='white',
                   font=("arial", 18, "bold"))
    label5.place(x=50, y=100)

    label6 = Message(root, text=out, fg='blue', font=('arial', 14), width=500)
    label6.place(x=50, y=150)

    btn_exit = Button(root,
                      text="EXIT",
                      bg='red',
                      fg='white',
                      font=('arial', 13),
                      command=lambda: [func2, root.destroy(), if_button])
    btn_exit.place(x=30, y=400)

    btn_search_again = Button(
        root,
        text="SEARCH ANOTHER",
        bg='red',
        fg='white',
        font=('arial', 13),
        command=lambda: [func3, restart(), if_search_button])
    btn_search_again.place(x=390, y=400)
    if if_button():
        btn_exit.wait_variable(var)
    if if_search_button():
        btn_exit.wait_variable(var1)
예제 #6
0
timeoutEN.place(relx=0.22, rely=0.67, relwidth=0.2)
timeoutEN.bind('<KeyRelease>', on_timeout_input)

# countdown and status
statusLB = ttk.Label(root, text='status:', anchor='e', width=8)
statusLB.place(relx=0.01, rely=0.73, relwidth=0.19)

statusVar = StringVar()
statusVar.set('Not Running')
statusLB2 = Message(root,
                    textvariable=statusVar,
                    anchor='nw',
                    justify='left',
                    fg=whitefg,
                    bg=canvasbg,
                    width=380)
statusLB2.place(relx=0.22, rely=0.728)

# Run button
runBT = ttk.Button(root,
                   text='Run',
                   command=toggle_running,
                   width=5,
                   style='Run.TButton')
runBT.place(relx=0.7, rely=0.9, relwidth=0.23)

api_cache()  # set apikey if its found in cache

# tkinter loop
root.mainloop()
def main():
    root = tkinter.Tk()
    root.title("Putty Controller")

    servers_file = "/Documents/servers.txt"
    accounts_file = "/Documents/accounts.txt"

    def destroy_frame(frame):
        for widget in frame.winfo_children():
            widget.destroy()

    w_server = tkinter.Frame(root,
                             width=300,
                             height=290,
                             borderwidth=1,
                             relief=GROOVE)
    destroy_frame(w_server)

    w_buttoms = tkinter.Frame(root,
                              width=120,
                              height=290,
                              borderwidth=1,
                              relief=GROOVE)
    destroy_frame(w_buttoms)

    servers = functions.load_file(servers_file)
    server_key = tkinter.StringVar()
    server_key.set(str(list(servers.keys())[-1]))
    title_server = tkinter.Message(w_server, text="Server", width=100)
    title_server.place(x=1, y=67)

    servers_list = Listbox(w_server, yscrollcommand=Scrollbar.set)
    #servers_list.config(command = servers_list.yview)

    for server in servers.keys():
        servers_list.insert(END, str(server))
    servers_list.place(x=80, y=65, width=200, height=120)

    servers_scroll = tkinter.Scrollbar(w_server)
    servers_scroll.place(x=280, y=65, width=15, height=120)
    servers_scroll.config(command=servers_list.yview)

    title_show_server = tkinter.Message(w_server,
                                        text="Last Opened",
                                        width=100)
    title_show_server.place(x=1, y=32)
    show_server = Message(w_server,
                          text=server_key.get(),
                          aspect=2000,
                          anchor=W,
                          relief=SUNKEN)
    show_server.place(x=80, y=30, width=215, height=30)

    title_server_standalone = tkinter.Message(w_server,
                                              text="Connect to: ",
                                              width=100)
    title_server_standalone.place(x=1, y=193)
    server_standalone = tkinter.Entry(w_server)
    server_standalone.place(x=80, y=195, width=215)

    title_user_standalone = tkinter.Message(w_server, text="User: "******"Password: "******"Use account: ", width=100)
    title_accounts.place(x=1, y=220)

    account_check = Checkbutton(w_server, text="ACC1", variable=accounts_key0)
    account_check.place(x=75, y=220)
    account_check = Checkbutton(w_server, text="ACC2", variable=accounts_key1)
    account_check.place(x=125, y=220)
    account_check = Checkbutton(w_server, text="ACC3", variable=accounts_key2)
    account_check.place(x=175, y=220)
    account_check = Checkbutton(w_server,
                                text="OTHER",
                                variable=accounts_other,
                                command=enable_fields)
    account_check.place(x=235, y=220)

    def do_open_putty(accounts_key0, accounts_key1, accounts_key2,
                      accounts_other):
        if server_standalone.get() != "":
            accounts_used = list()
            if accounts_key0.get() != 0:
                accounts_key0 = "ACC1"
            else:
                accounts_key0 = ""

            if accounts_key1.get() != 0:
                accounts_key1 = "ACC2"
            else:
                accounts_key1 = ""

            if accounts_key2.get() != 0:
                accounts_key2 = "ACC3"
            else:
                accounts_key2 = ""

            if accounts_other.get() != 0:
                accounts_other = user_standalone.get()
            else:
                accounts_other = ""

            accounts_used.append(accounts_key0)
            accounts_used.append(accounts_key1)
            accounts_used.append(accounts_key2)
            accounts_used.append(accounts_other)

            for account in accounts_used:
                if account == "ACC1" or account == "ACC2" or account == "ACC3":
                    user = str(accounts.get(str(account))).split(",")[1]
                    password = str(accounts.get(str(account))).split(",")[2]
                    functions.open_putty(user, password,
                                         server_standalone.get())
                    functions.update_server(w_server, server_standalone.get())
                elif account != "":
                    user = user_standalone.get()
                    password = password_standalone.get()
                    functions.open_putty(user, password,
                                         server_standalone.get())
                    functions.update_server(w_server, server_standalone.get())
        else:
            ip = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[1]
            account = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[2]
            user = str(accounts.get(str(account))).split(",")[1]
            password = str(accounts.get(str(account))).split(",")[2]
            functions.open_putty(user, password, ip)
            functions.update_server(
                w_server, servers_list.get(servers_list.curselection()))

    def button_open_putty():
        do_open_putty(accounts_key0, accounts_key1, accounts_key2,
                      accounts_other)

    def do_open_winscp(accounts_key0, accounts_key1, accounts_key2,
                       accounts_other, sudo_value):
        if server_standalone.get() != "":
            accounts_used = list()
            if accounts_key0.get() != 0:
                accounts_key0 = "ACC1"
            else:
                accounts_key0 = ""
            if accounts_key1.get() != 0:
                accounts_key1 = "ACC2"
            else:
                accounts_key1 = ""
            if accounts_key2.get() != 0:
                accounts_key2 = "ACC3"
            else:
                accounts_key2 = ""
            if accounts_other.get() != 0:
                accounts_other = user_standalone.get()
            else:
                accounts_other = ""

            accounts_used.append(accounts_key0)
            accounts_used.append(accounts_key1)
            accounts_used.append(accounts_key2)
            accounts_used.append(accounts_other)

            for account in accounts_used:
                if account == "ACC1" or account == "ACC2" or account == "ACC3":
                    user = str(accounts.get(str(account))).split(",")[1]
                    password = str(accounts.get(str(account))).split(",")[2]
                    functions.open_winscp(user, password,
                                          server_standalone.get(),
                                          sudo_value.get())
                    functions.update_server(w_server, server_standalone.get())
                elif account != "":
                    user = user_standalone.get()
                    password = password_standalone.get()
                    functions.open_winscp(user, password,
                                          server_standalone.get(),
                                          sudo_value.get())
                    functions.update_server(w_server, server_standalone.get())
        else:
            ip = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[1]
            account = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[2]
            user = str(accounts.get(str(account))).split(",")[1]
            password = str(accounts.get(str(account))).split(",")[2]
            functions.open_winscp(user, password, ip, sudo_value.get())
            functions.update_server(
                w_server, servers_list.get(servers_list.curselection()))

    def button_open_winscp():
        do_open_winscp(accounts_key0, accounts_key1, accounts_key2,
                       accounts_other, sudo_value)

    def do_open_wfreerdp(accounts_key0, accounts_key1, accounts_key2,
                         accounts_other, full_screen_value):

        if server_standalone.get() != "":
            accounts_used = list()
            if accounts_key0.get() != 0:
                accounts_key0 = "ACC1"
            else:
                accounts_key0 = ""
            if accounts_key1.get() != 0:
                accounts_key1 = "ACC2"
            else:
                accounts_key1 = ""
            if accounts_key2.get() != 0:
                accounts_key2 = "ACC3"
            else:
                accounts_key2 = ""
            if accounts_other.get() != 0:
                accounts_other = user_standalone.get()
            else:
                accounts_other = ""

            accounts_used.append(accounts_key0)
            accounts_used.append(accounts_key1)
            accounts_used.append(accounts_key2)
            accounts_used.append(accounts_other)
            title = "Server: " + str(server_standalone.get())
            width = 1440
            height = 900
            for account in accounts_used:
                if account == "ACC1" or account == "ACC2" or account == "ACC3":
                    user = str(accounts.get(str(account))).split(",")[1]
                    password = str(accounts.get(str(account))).split(",")[2]
                    functions.open_wfreerdp(title, server_standalone.get(),
                                            user, password, width, height,
                                            full_screen_value.get())
                    functions.update_server(w_server, server_standalone.get())
                elif account != "":
                    user = user_standalone.get()
                    password = password_standalone.get()
                    functions.open_wfreerdp(title, server_standalone.get(),
                                            user, password, width, height,
                                            full_screen_value.get())
                    functions.update_server(w_server, server_standalone.get())
        else:
            title = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[0]
            ip = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[1]
            account = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[2]
            user = str(accounts.get(str(account))).split(",")[1]
            password = str(accounts.get(str(account))).split(",")[2]
            width = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[3]
            height = str(
                servers.get(str(servers_list.get(
                    servers_list.curselection())))).split(",")[4]
            functions.open_wfreerdp(title, ip, user, password, width, height,
                                    full_screen_value.get())
            functions.update_server(
                w_server, servers_list.get(servers_list.curselection()))

    def button_open_wfreerdp():
        do_open_wfreerdp(accounts_key0, accounts_key1, accounts_key2,
                         accounts_other, full_screen_value)

    button = tkinter.Button(w_buttoms,
                            text='Open Putty',
                            command=button_open_putty)
    button.place(x=8, y=30, width=100, height=30)

    button = tkinter.Button(w_buttoms,
                            text='Open WinSCP',
                            command=button_open_winscp)
    button.place(x=8, y=70, width=100, height=30)

    sudo_value = IntVar()
    sudo_value_check = Checkbutton(w_buttoms,
                                   text="With sudo?",
                                   variable=sudo_value)
    sudo_value_check.place(x=8, y=100)

    button = tkinter.Button(w_buttoms,
                            text='Open WFreeRDP',
                            command=button_open_wfreerdp)
    button.place(x=8, y=130, width=100, height=30)

    full_screen_value = IntVar()
    full_screen_value_check = Checkbutton(w_buttoms,
                                          text="Full Screen?",
                                          variable=full_screen_value)
    full_screen_value_check.place(x=8, y=160)

    def refresh(self):
        root.wm_attributes("-topmost", ontop_value.get())

    def do_refresh():
        refresh(root)

    ontop_value = IntVar()
    ontop_value_check = Checkbutton(w_server,
                                    text="On Top?",
                                    variable=ontop_value,
                                    command=do_refresh)
    ontop_value_check.place(x=1, y=1)

    w_server.pack(padx=1, pady=1, side=LEFT)
    w_buttoms.pack(padx=1, pady=1, side=RIGHT)
    root.wm_attributes("-topmost", ontop_value.get())
    root.resizable(width=False, height=False)
    root.mainloop()
예제 #8
0
def button_action():
    word = entry1.get()
    if word in data:
        main_word = word
        out = get_meaning(word)

        label2.destroy()
        entry1.destroy()
        submit.destroy()

        label3 = Label(root,
                       text=main_word,
                       bg='black',
                       fg='white',
                       font=("arial", 18, "bold"))
        label3.place(x=50, y=100)

        label4 = Message(root,
                         text=out,
                         fg='blue',
                         font=('arial', 14),
                         width=500)
        label4.place(x=50, y=150)

        btn_exit = Button(
            root,
            text="EXIT",
            bg='red',
            fg='white',
            font=('arial', 13),
            command=lambda: [func2, root.destroy(), if_button])
        btn_exit.place(x=30, y=400)

        btn_search_again = Button(
            root,
            text="SEARCH ANOTHER",
            bg='red',
            fg='white',
            font=('arial', 13),
            command=lambda: [func3, restart(), if_search_button])
        btn_search_again.place(x=390, y=400)
        if if_button():
            btn_exit.wait_variable(var)
            raise SystemExit
        if if_search_button():
            btn_exit.wait_variable(var1)

    else:
        label2.destroy()
        entry1.destroy()
        submit.destroy()

        main_word = word
        label3 = Label(root,
                       text=main_word,
                       bg='black',
                       fg='white',
                       font=("arial", 18, "bold"))
        label3.place(x=51, y=100)

        alt_word = get_close_matches(main_word, data.keys())[0]

        label4 = Label(root,
                       text="Did you mean: {}".format(
                           get_close_matches(main_word, data.keys())[0]),
                       fg='blue',
                       font=("arial", 18, "bold"))
        label4.place(x=50, y=160)

        yes = Button(root,
                     text='YES',
                     bg='red',
                     fg='white',
                     font=('arial', 10, 'bold'),
                     command=lambda: [
                         func1(),
                         yes_button(label3, label4, alt_word, yes, no),
                         yes_wait()
                     ])

        yes.place(x=220, y=240)
        no = Button(
            root,
            text='NO',
            bg='red',
            fg='white',
            font=('arial', 10, 'bold'),
            command=lambda:
            [func2, no_button(label3, label4, alt_word, yes, no)])
        no.place(x=300, y=240)

        if yes_wait():
            yes.wait_variable(var)
        else:
            no.wait_variable(var1)
예제 #9
0
class PageResult():
    def __init__(self):
        self.root = Tk()
        self.createWidgets()
        self.root.mainloop()

    def initialize_variables(self):
        # Initial size of the app
        self.HEIGHT = 600
        self.WIDTH = 800
        self.root.title("Categorization Dialog Widget")
        self.root.minsize(750, 550)

    def createWidgets(self):
        self.initialize_variables()

        # Background
        self.canvas = Canvas(self.root, height=self.HEIGHT, width=self.WIDTH)
        self.background_label = Label(self.root, bg='#3C1E5F')
        self.background_label.place(relwidth=1, relheight=1)
        self.canvas.pack()

        # Upper frame with logo and info message
        self.higher_frame = Frame(self.root, bg='#FFD164', bd=5)
        self.higher_frame.place(relx=0.5,
                                rely=0.1,
                                relwidth=0.85,
                                relheight=0.35,
                                anchor='n')
        self.logo = Canvas(self.higher_frame, bd=1)
        self.logo.place(relx=0, rely=0, relwidth=1, relheight=0.5)
        self.img = PhotoImage(file="logo.png")
        self.img = self.img.subsample(6)
        self.logo.create_image(0, 0, anchor='nw', image=self.img)
        self.var = "Categorization of txt files from a given folder to sub-folders and presenting them in a table"
        self.infoMessage = Message(self.higher_frame,
                                   text=self.var,
                                   justify='center',
                                   width=350,
                                   font=("Courier bold", 14))
        self.infoMessage.place(relx=0.4,
                               rely=0.05,
                               relwidth=0.5,
                               relheight=0.3)

        # Middle frame with info message and button
        self.middle_frame = Frame(self.root, bg='#FFD164', bd=5)
        self.middle_frame.place(relx=0.5,
                                rely=0.25,
                                relwidth=0.85,
                                relheight=0.1,
                                anchor='n')
        self.openFolder = Label(self.middle_frame,
                                text="Open a folder with \ninput files",
                                justify='center',
                                bg='white',
                                fg='#EE7C7D',
                                font=(
                                    "Courier",
                                    12,
                                ))
        self.openFolder.place(relx=0, rely=0, relwidth=0.65, relheight=1)
        self.button = Button(self.middle_frame,
                             text="Browse",
                             font=("Courier", 12),
                             bg='#b3b3b3',
                             activebackground='#f2d9e6',
                             command=lambda: self.fileDialog())
        self.button.place(relx=0.7, relwidth=0.3, relheight=1)

        # Lower frame with scrollbars for displaying of categories and file names
        self.lower_frame = Frame(self.root, bg='#FFD164', bd=5)
        self.lower_frame.place(relx=0.5,
                               rely=0.35,
                               relwidth=0.85,
                               relheight=0.55,
                               anchor='n')
        self.lower_frame.grid_rowconfigure(0, weight=1)
        self.lower_frame.grid_columnconfigure(0, weight=1)
        self.results = Listbox(self.lower_frame,
                               font=("Courier", 12),
                               bg='white',
                               fg='#EE7C7D',
                               justify='left',
                               bd=3)
        self.results.grid(column=1, row=1, padx=10, ipady=10)
        self.results.place(relwidth=1, relheight=1)
        self.scrollbar_vertical = Scrollbar(self.lower_frame, orient=VERTICAL)
        self.scrollbar_vertical.pack(side=RIGHT, fill=Y)
        self.scrollbar_vertical.configure(command=self.results.yview)
        self.scrollbar_horizontal = Scrollbar(self.lower_frame,
                                              orient=HORIZONTAL)
        self.scrollbar_horizontal.pack(side=BOTTOM, fill=X)
        self.scrollbar_horizontal.configure(command=self.results.xview)
        self.results.configure(yscrollcommand=self.scrollbar_vertical.set)
        self.results.configure(xscrollcommand=self.scrollbar_horizontal.set)

    # Gets the selected folder by the user and uses keywordSearch in txt files, then presents categories and file names
    def fileDialog(self):
        try:

            self.folderSelected = filedialog.askdirectory()
            self.categorizer = Categorizer(self.folderSelected)

            #1. Shows the amount of analyzed Emails
            amountOfFiles = self.categorizer.amountOfFiles(self.folderSelected)
            self.results.insert(
                END, "Amount of analysed Emails: " + str(amountOfFiles))
            self.results.insert(END, "\n")

            #Shows a List of categories with their emails
            self.dict_obj = self.categorizer.categorizeFilesFromDirectoryInMapAndSubDirectory(
            )
            self.results.insert(END, "Category".ljust(20, ' ') + "File name")
            self.results.insert(END, "\n")
            for key, val in self.dict_obj.items():
                self.results.insert(END, str(key).ljust(20, ' ') + str(val))
        except UnicodeDecodeError:
            self.results.insert(END,
                                "Selected folder does not contain txt files.")
class PageOptions():
    def __init__(self):
        self.root = Tk()
        self.createWidgets()
        self.root.mainloop()

    def initialize_variables(self):
        # Initial size of the app
        self.HEIGHT = 600
        self.WIDTH = 800
        self.root.title("Categorization Dialog Widget")
        self.root.minsize(750, 550)

    def createWidgets(self):
        self.initialize_variables()

        # Background
        self.canvas = Canvas(self.root, height=self.HEIGHT, width=self.WIDTH)
        self.background_label = Label(self.root, bg='#3C1E5F')
        self.background_label.place(relwidth=1, relheight=1)
        self.canvas.pack()

        # Upper frame with logo and info message
        self.higher_frame = Frame(self.root, bg='#FFD164', bd=5)
        self.higher_frame.place(relx=0.5, rely=0.1, relwidth=0.85, relheight=0.35, anchor='n')
        self.logo = Canvas(self.higher_frame, bd=1)
        self.logo.place(relx=0, rely=0, relwidth=1, relheight=0.5)
        self.img = PhotoImage(file="logo.png")
        self.img = self.img.subsample(6)
        self.logo.create_image(0, 0, anchor='nw', image=self.img)
        self.var = "Sentiment Classification and Categorization of txt files"
        self.infoMessage = Message(self.higher_frame, text=self.var, justify='center', width=350, font=("Courier bold", 16))
        self.infoMessage.place(relx=0.4, rely=0.05, relwidth=0.5, relheight=0.3)

        # Menubar with Option, Result and Direct input
        self.menubar()

        # Lower frame with scrollbars for displaying of categories and file names
        self.lower_frame = Frame(self.root, bg='#FFD164', bd=5)
        self.lower_frame.place(relx=0.5, rely=0.35, relwidth=0.85, relheight=0.55, anchor='n')
        self.lower_frame.grid_rowconfigure(0, weight=1)
        self.lower_frame.grid_columnconfigure(0, weight=1)
        self.optionCanvas = Canvas(self.lower_frame, bg='white', bd=3)
        self.optionCanvas.place(relwidth=1, relheight=1)
        # select language (English or Swedish)
        self.selectLanguage(self.optionCanvas)
        # open folder with input files
        self.openFolder = Label(self.optionCanvas, text="Open a folder with input files", justify='left',
                                bg='white',
                                font=("Courier bold", 12))
        self.openFolder.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.2)
        self.button = Button(self.optionCanvas, text="Browse", font=("Courier", 12), bg='#EE7C7D',
                             activebackground='#f2d9e6',
                             command=lambda: self.fileDialog())
        self.button.place(relx=0.5, rely=0.4, relwidth=0.3, relheight=0.15)
        # save result in excel file
        self.CheckVar = IntVar()
        self.excelFileCheckbutton = Checkbutton(self.optionCanvas, text="Save as excel", variable=self.CheckVar, \
                         onvalue=1, offvalue=0, bg='white', font=("Courier bold", 12), height=5, width=20)
        self.excelFileCheckbutton.place(relx=0.1, rely=0.6, relwidth=0.3, relheight=0.15)

    # Middle frame with buttons bar
    def menubar(self):
        self.middle_frame = Frame(self.root, bg='#FFD164', bd=5)
        self.middle_frame.place(relx=0.5, rely=0.25, relwidth=0.85, relheight=0.1, anchor='n')
        self.button = Button(self.middle_frame, text="Options", font=("Courier", 12), bg='#EE7C7D',
                             activebackground='#f2d9e6',
                             command=lambda: self.fileDialog())
        self.button.place(relx=0.1, relwidth=0.2, relheight=1)
        self.button = Button(self.middle_frame, text="Result", font=("Courier", 12), bg='#EE7C7D',
                             activebackground='#f2d9e6',
                             command=lambda: self.fileDialog())
        self.button.place(relx=0.4, relwidth=0.2, relheight=1)
        self.button = Button(self.middle_frame, text="Direct input", font=("Courier", 12), bg='#EE7C7D',
                             activebackground='#f2d9e6',
                             command=lambda: self.fileDialog())
        self.button.place(relx=0.7, relwidth=0.2, relheight=1)

    # select language (English or Swedish)
    def selectLanguage(self, parentWidget):
        # Create a Tkinter variable
        self.tkvar = StringVar()
        # Dictionary with options
        self.choices = {'English', 'Swedish'}
        self.tkvar.set('English')  # set the default option
        # Popup menu with languages
        self.popupMenu = OptionMenu(parentWidget, self.tkvar, *self.choices)
        self.popupLabel = Label(parentWidget, text="Choose a language", bg='white', justify='left',
                                font=("Courier bold", 12))
        self.popupLabel.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.2)
        self.popupMenu.configure(bd=3, bg='#EE7C7D')
        self.popupMenu.place(relx=0.5, rely=0.1, relwidth=0.3, relheight=0.15)
        # on change dropdown value
        def change_dropdown(*args):
            print(self.tkvar.get())
        # link function to change dropdown
        self.tkvar.trace('w', change_dropdown)

    # Gets the selected folder by the user and uses keywordSearch in txt files, then presents categories and file names
    def fileDialog(self):
        try:
            self.folderSelected = filedialog.askdirectory()
            self.categorizer = Categorizer(self.folderSelected)
            self.dict_obj = self.categorizer.categorizeFilesFromDirectoryInMapAndSubDirectory()
            self.results.insert(END, "Category".ljust(20, ' ') + "File name")
            self.results.insert(END, "\n")
            for key, val in self.dict_obj.items():
                self.results.insert(END, str(key).ljust(20, ' ') + str(val))
        except UnicodeDecodeError:
            self.results.insert(END, "Selected folder does not contain txt files.")
def process_img():
    # panjang citra di GUI
    width = 240
    # lebar citra di GUI
    height = 240
    # mendeklarasikan panel yang sudah dideklarasikan menjadi global
    global panel_photo, panel_photo_bw, panel_histogram_gs, panel_message
    # jika fungsi process_img() sudah dijalankan sebelumnya
    # maka tutup / hapus panel yang sudah ada sebelumnya
    if panel_photo != None:
        panel_photo.destroy()
        panel_photo_bw.destroy()
        panel_histogram_gs.get_tk_widget().destroy()
        panel_message.destroy()

    # tampilkan jendela untuk memilih file citra yang akan diproses
    file_name = filedialog.askopenfilename(title='Select Image')
    # simpan file sebagai citra
    img = Image.open(file_name)
    # ubah ukuran citra sesuai panjang dan lebar yg telah ditentukan
    img_resized = img.resize((width, height), Image.ANTIALIAS)
    # ubah citra menjadi citra untuk GUI
    img_tk = ImageTk.PhotoImage(img_resized)
    # tampilkan citra di panel_photo dengan posisi x=10 dan y=50
    panel_photo = Canvas(root)
    panel_photo.place(x=10, y=50)
    # posisikan citra di dalam panel photo di x=0, y=0
    # dan terletak di northwest(kiri atas)
    panel_photo.create_image(0, 0, anchor='nw', image=img_tk)
    panel_photo.image = img_tk

    # threshold untuk mengubah citra abu - abu menjadi hitam putih umumnya 128
    # nilai threshold tidaklah mutlak 128
    # untuk menyesuaikan dengan output yang paper referensi maka threshold kita ubah menjadi 60
    # citra diubah menjadi hitam putih agar dapat menampilkan garis semangka
    threshold = 60
    # ubah citra dari RGBA ke abu - abu
    img_gs = img_resized.convert('L')
    # ubah citra dari abu - abu ke hitam putih
    img_bw = img_gs.point(lambda p: 255 if p > threshold else 0, mode='1')
    # ubah citra hitam putih menjadi citra untuk GUI
    img_bw_tk = ImageTk.PhotoImage(img_bw)
    # tampilkan citra di panel_photo_bw dengan posisi x=260 dan y=50
    panel_photo_bw = Canvas(root)
    panel_photo_bw.place(x=260, y=50)
    # posisikan citra di dalam panel photo di x=0, y=0
    # dan terletak di northwest(kiri atas)
    panel_photo_bw.create_image(0, 0, anchor='nw', image=img_bw_tk)
    panel_photo_bw.image = img_bw_tk

    # ambil seluruh representasi derajat keabuan citra pada tiap piksel
    # lalu jadikan sebagai array
    a = np.array(img_gs.getdata())
    # buat Figure / visualisasi dengan panjang=5, lebar=4 dan 100 dot per inch
    f = Figure(figsize=(5, 4), dpi=100)
    # buat Figure / visualisasi dapat ditampilkan di GUI
    panel_histogram_gs = FigureCanvasTkAgg(f, root)
    # posisikan visualisasi di x=510 dan y=10
    panel_histogram_gs.get_tk_widget().place(x=510, y=10)
    # ambil instance axis milik figure lalu assign ke variabel p
    p = f.gca()
    # buat histogram dengan isi array a dan bins=[0,...,255]
    p.hist(a, bins=range(256))

    # deklarasi variabel total dan threshold atas bawah untuk r,g,b
    # threshold ini menentukan apakah semangka matang berdasar nilai rgbnya
    total = 0
    red_lower_threshold = 92
    red_upper_threshold = 100
    green_lower_threshold = 170
    green_upper_threshold = 210
    blue_lower_threshold = 0
    blue_upper_threshold = 90
    # ubah citra dari RGBA menjadi RBG lalu ambil total kemunculan RGB dan nilai RGBnya
    list_count_rgb = img_resized.convert('RGB').getcolors(width * height)
    # loop untuk tiap anggota list
    for count_rgb in list_count_rgb:
        # cek nilai merah, jika berada di dalam threshold maka
        # total += total kemunculan rgb
        if count_rgb[1][0] >= red_lower_threshold and \
            count_rgb[1][0] <= red_upper_threshold:
            total += count_rgb[0]
        # cek nilai hijau, jika berada di dalam threshold maka
        # total += total kemunculan rgb
        if count_rgb[1][1] >= green_lower_threshold and \
            count_rgb[1][1] <= green_upper_threshold:
            total += count_rgb[0]
        # cek nilai biru, jika berada di dalam threshold maka
        # total += total kemunculan rgb
        if count_rgb[1][2] >= blue_lower_threshold and \
            count_rgb[1][2] <= blue_upper_threshold:
            total += count_rgb[0]
    # hitung persentase kematangan berdasarkan nilai rgb
    ripe_percentage = (total / (3 * width * height)) * 100
    # deklarasi pesan
    message = 'Belum Matang'
    # jika persentase kematangan >= 25 maka matang
    # (berdasarkan training dari percobaan yg ada)
    if ripe_percentage >= 25:
        message = 'Matang'
    # deklarasi panel_message untuk menampilkan pesan status semangka
    panel_message = Message(root, text='Status Semangka: {}'.format(message))
    # tampilkan pesan di x=10, y=300
    panel_message.place(x=10, y=300)

    # deklarasi panjang dan lebar untuk sample file csv
    width_sample = 30
    height_sample = 30
    # resize citra abu - abu sesuai panjang lebar sample
    img_gs_resized = img_gs.resize((width_sample, height_sample),
                                   Image.ANTIALIAS)
    # ambil derajat nilai keabuan tiap piksel
    pix_gs_resized = img_gs_resized.load()
    # tulis derajat nilai keabuan tiap piksel ke file csv
    with open('gs_pixel.csv', 'w+') as f:
        for x in range(width_sample):
            for y in range(height_sample):
                gs_val = pix_gs_resized[y, x]
                f.write('{},'.format(gs_val))
            f.write('\n')
    # resize citra hitam putih sesuai panjang lebar sample
    img_bw_resized = img_bw.resize((width_sample, height_sample),
                                   Image.ANTIALIAS)
    # ambil derajat nilai hitam putih tiap piksel
    pix_bw_resized = img_bw_resized.load()
    # tulis derajat nilai keabuan tiap piksel ke file csv
    with open('bw_pixel.csv', 'w+') as f:
        # read the details of each pixel and write them to the file
        for x in range(width_sample):
            for y in range(height_sample):
                bw_val = pix_bw_resized[y, x]
                # karena derajat nilai hitam putih direpesentasikan dengan 0 dan 255
                # kita dapat mengubahnya menjadi 0 1 sebagai berikut
                if bw_val == 255:
                    bw_val = 1
                f.write('{},'.format(bw_val))
            f.write('\n')