Beispiel #1
0
    def __init__(self, root, control):
        self.__root = root
        self.__control = control

        self.__root.title("Lezioni alla Pari")
        self.__root.geometry("1000x600")
        self.__root.minsize(800, 500)
        # self.__root.resizable(width="False", height="False")

        self.__frameInfo = Frame(self.__root)
        self.__frameInfo.pack(side=TOP, fill=X, padx=5, pady=10)

        self.__frameLesson = Frame(self.__root)
        self.__frameLesson.pack(side=BOTTOM,
                                fill=BOTH,
                                padx=5,
                                pady=10,
                                expand=True)

        Button(self.__frameInfo,
               text="Esci",
               width=10,
               height=1,
               command=self.__control.logout).pack(anchor=NE,
                                                   side=RIGHT,
                                                   padx=5)

        self.__user = None
        self.__list = None
        self.__html = HTMLLabel(
            self.__frameLesson,
            html="<p>Doppio-Click su una lezione per aprirla</p>")
Beispiel #2
0
    def __init__(self, root, title, content):
        self.__root = root
        self.__title = title
        self.__content = content

        self.__view = Toplevel(self.__root)
        self.__view.title(self.__title)
        self.__view.geometry("700x600")
        self.__view.minsize(width=400, height=400)

        self.__html = HTMLLabel(self.__view, html=self.__content)
        self.__html.pack(fill=BOTH, expand=True, padx=20, pady=10)

        self.__view.mainloop()
Beispiel #3
0
class HTMLPreview():
    def __init__(self, html, column="", col=0, rowID=0):
        def update_html(input="", btn=None):
            self.html_text = markdown(input)
            self.dw_htmllabel.set_html(self.html_text)
            self.dw_htmllabel.fit_height()

        rnframe = Tk()

        rnframe.title(f"OpenKeyote - Editing {column}")
        rnframe.geometry(f"900x500+{1000}+{500}")
        rnname = Text(rnframe,
                      font=("Courier", 8),
                      padx=10,
                      pady=10,
                      highlightthickness=1,
                      borderwidth=1,
                      relief="solid",
                      height=10)
        rnname.grid(row=1, column=0, sticky=E + W, padx=10, pady=10)
        rnname.delete("1.0", END)
        rnname.insert(END, html)
        rnname.focus()
        rnname.mark_set('insert', '1.0')

        htmlframe = Frame(rnframe, height=500)
        htmlframe.grid(row=2, column=0)
        self.dw_htmllabel = HTMLLabel(htmlframe, html=markdown("#hi\nnice"))
        #self.dw_htmllabel.grid(row=2, column=0)
        self.dw_htmllabel.pack(fill="both", expand=True)
        #self.dw_htmllabel.fit_height()

        rnframe.columnconfigure(1, weight=1)
        rnframe.rowconfigure(1, weight=1)
        rnokbtn = ttk.Button(rnframe, text="OK", width=10)
        rnokbtn.grid(row=4, column=0, sticky=N + W, padx=5, pady=10)
        rnokbtn.config(
            command=lambda: self.dw_submit(titles=self._dw_t1_rows,
                                           col=self._dw_t1_column,
                                           data=rnname.get("1.0", "end-1c"),
                                           frame=rnframe))
        rncancelbtn = ttk.Button(rnframe,
                                 text="Cancel",
                                 command=rnframe.destroy)
        rncancelbtn.grid(row=4, column=1, sticky=N + W + E, padx=5, pady=10)
        rnname.bind("<KeyRelease>",
                    lambda e=None: update_html(rnname.get("1.0", "end-1c")))
        rnframe.mainloop()
Beispiel #4
0
def di():
    di = to("Dodatkowe informacje", "500x150", 1)
    Label(di, text="Autorzy Programu:\n- Cyprian Lazarowski\n- Kacper Karwot\n- Kacper Muszczyński", justify=LEFT,
          font="Arial 12").grid(row=0, sticky=W + S)
    Label(di, text="Plik pdf z dokumentacją programu oraz instrukcjami dla użytkownika:", justify=LEFT,
          font="Arial 12").grid(row=1, sticky=W + S)
    HTMLLabel(di,
              html='<a href="https://drive.google.com/file/d/1veMlgxby2U9pdjgfJptqZTg6EG-FkLUF/view?usp=sharing"> Dokumentacja Programu </a>').grid(
        row=2, sticky=W + S) #zmienić linka bo ten jest do starej dokumentacji
    
    di.mainloop()
Beispiel #5
0
def getChimeraX(version):

    print("Getting %s version" % version)
    TGZ = getTgz(version)

    def licenceAccepted():
        """ Called when licence has been accepted"""

        root.destroy()
        data = {"file": getFile(version), "choice": "Accept"}
        data = parse.urlencode(data).encode()
        req = request.Request(LICENSE_URL, data)
        resp = request.urlopen(req).read().decode('utf-8')
        # Get the download url
        match = re.search('url=(.*)"', resp)
        if not match:
            raise Exception("Response does not contain expected pattern: %s" %
                            resp)

        downloadUrl = match.group(1)
        downloadUrl = DOMAIN + downloadUrl
        print("Downloading chimera from " + downloadUrl)
        os.system('wget "%s"  --progress=bar -c -O %s' % (downloadUrl, TGZ))
        sys.exit()

    if os.path.exists(TGZ):
        print(TGZ, " found. Skipping download.")
        sys.exit()

    licenseHTML = request.urlopen(
        getLicenseURLwithFile(version)).read().decode()

    licenseHTML = re.sub("<style.*/style>", "", licenseHTML, flags=re.DOTALL)
    licenseHTML = re.sub("<script.*/script>", "", licenseHTML, flags=re.DOTALL)

    root = tk.Tk()
    root.title("ChimeraX Binary Installation: License Page")
    frame = root
    frame.rowconfigure(0, weight=1)
    html_label = HTMLLabel(frame, html=licenseHTML)
    html_label.grid(row=0, column=0, sticky="news")
    html_label.fit_height()

    acceptButton = tk.Button(frame, text="Accept", command=licenceAccepted)
    acceptButton.grid(row=1, column=0, sticky="s")

    root.mainloop()

    print("License not accepted.")
    sys.exit(1)
Beispiel #6
0
def test_html_format():
    #----------------------------------------------------------------------------------------------
    TEXT = '<code style="color: #%06x; background-color: #%06x; text-align: center; font-size:30px"> text color #%06x</code>'
    for _ in range(10):
        try:
            root = tk.Tk()
            break
        except Exception as e:
            exception = e
    else:
        raise exception
    text = HTMLLabel(root, height=10)
    text.pack(fill="both", expand=True)
    for increment in (0x010000, 0x000100, 0x000001):
        for i in range(0, increment * 256, increment):
            text.set_html(TEXT % (i, increment * 255, i))
            root.update()
    root.destroy()
Beispiel #7
0
                    1e-3: 234,
                    1e-2: 235,
                    5: 236
                }
                for i in range(10):
                    coef_matrix_ridge.iloc[i, ] = ridge_regression_PLOTOVANJE(
                        data, predictors, alpha_ridge[i], models_to_plot)
                plt.show()

            if 300 + 100 > mouse[0] > 300 and 725 + 50 > mouse[1] > 725:
                root = tk.Tk()
                root.title("Ispod haube")

                html_label = HTMLLabel(
                    root,
                    html=
                    '<html><div><h1> ----------------- Princip numerike ----------------- </h1> <h4>Princip na kome radi numerika je zasnovan na regresiji i regulaciji. Metode koje koristimo su: Ridge i Lasso metoda takozvane L1 i L2 metode.<br><br>Nas program se samostalno trenira tokom kontinuiranog igranja, odnosno sto vise budemo igrali igru, dobijacemo bolje predikcije tj. savete koja kolona je najbolja da se odigra u sledecem potezu na osnovu naseg predjasnjeg iskustva u igranju protiv AI-a.<br> <br> Voditi racuna da MOD 2 nije optimalan na pocetku vaseg igranja, sto znaci da ce on tek postati kompetentan sa sve vecim vasim igranjem igre, zato sto se zasniva na podacima koje prikuplja od vaseg igranja protiv AI-a.<img src="picture/podaci.png"  width="600" height="350"><br><br>Kada nismo sigurni gde je najpametnije odigrati sledeci potez, nasa numerika ce tada izvrsiti regresiju i regulaciju i reci nam koji potez je optimalan.</h6> <h1> ---------------------- Metode ---------------------- </h1> <p> Metode koje uvode kaznenu funkciju tj. izraz zvan penal, a time koriguju izgled nase krive koja nam saopstava naredni potez su Lasso, Ridge metode. </p><img src="picture/Lm.png" width="600" height="100">  </div></html>'
                )
                html_label.pack(fill="both", expand=True)
                html_label.fit_height()
                root.mainloop()

            if 300 + 100 > mouse[0] > 300 and 650 + 50 > mouse[1] > 650:

                #Define input array with angles from 60deg to 300deg converted to radians
                #x = [1, 1,2 ,2,3,3,3,4,4,4,5,5,6,6,7,7,7,7,8,8,8,8,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
                np.random.seed(10)  #Setting seed for reproducability
                #y = 4.5 + np.random.normal(0,1,len(x))
                data = pd.DataFrame(np.column_stack([x, y]),
                                    columns=['x', 'y'])
                for i in range(2, 16):  #power of 1 is already there
Beispiel #8
0
import tkinter as tk
from tk_html_widgets import HTMLLabel

root = tk.Tk()
html_label = HTMLLabel(
    root, html='<h1 style="color: red; text-align: center"> Hello World </H1>')
html_label.pack(fill="both", expand=True)
html_label.fit_height()
root.mainloop()
Beispiel #9
0
import tkinter as tk
from tk_html_widgets import HTMLLabel

HTML = """
<p style="text-align: center;">
    <b>
        <a  href="https://www.python.org" style="color:#%02x%02x%02x; font-size:30px">
            www.python.org
        </a>
        <img src="py.png" width=50 height=50>
    </b>
</p>"""

root = tk.Tk()
html_label = HTMLLabel(root, html=HTML % (0, 0, 0), width=50)
html_label.pack(fill="both", expand=True)
html_label.fit_height()

rgb = [0, 0, 0]
i = 0
while True:
    for v in range(256):
        if i == 0:
            rgb[i] = v
        elif i == 1 or i == 2:
            rgb[i] = v
            rgb[i - 1] = 255 - v
        elif i == 3:
            rgb[i - 1] = 255 - v

        html_label.set_html(HTML % tuple(rgb))
Beispiel #10
0
    def call_tool_comb(self):
        """
        根据绘图目的和绘图工具的选择,既可以确定到单个的绘图实例,将此绘图实例的绘图数据格式推送给用户
        :return:
        """
        # 初始化绘图向导UI frame
        for widget in self.cv_frame.winfo_children():
            widget.destroy()

        aim_number = self.c_tv_aim.get().strip().split("-")[0]
        tool_number = self.c_tv_tool.get().strip().split("-")[0]
        self.aim_tool_number = ("%s-%s" % (aim_number, tool_number))
        # print("aim_number+tool_number: %s" % self.aim_tool_number)
        """
        根据aim_number + tool_number,定义好绘图的数据接口格式 
        """
        data_format = {
            "01-01": {
                "nodes": ["name", "symbolSize", "..."],
                "links": ["source", "target"],
                "categories": ["name"]
            },
            "01-02": {
                "nodes": ["name", "symbolSize", "..."],
                "links": ["source", "target"],
                "categories": ["name"]
            },
            "02-04": {
                "nodes": ["name", "symbolSize", "..."],
                "links": ["source", "target"],
                "categories": ["name"]
            },
            "03-03": {
                "line": ["node_name", "radius", "angle"]
            },
            "04-071": {
                "line": ["location", "value"]
            },
            "04-072": {
                "line": ["location", "value"]
            },
            "05-05": {
                "line": ["words", "frequency"]
            },
            "06-06": {
                "line": ["date", "values", "theme"]
            }
        }
        # 导出绘图数据格式
        export_frame = LabelFrame(self.cv_frame,
                                  text="第三步:导出数据格式",
                                  width=600,
                                  height=580,
                                  bg='#fff2cc')
        export_frame.grid(row=0, column=0, sticky=W)
        export_frame.grid_propagate(0)  # 组件大小不变
        format_label_text = "<B><i>" + str(data_format[str(
            self.aim_tool_number)]) + "</i></B>"
        # format_label = HTMLLabel(export_frame, text=format_label_text, anchor="w", width=72, bg='#fff2cc')
        format_label = HTMLLabel(export_frame,
                                 html=format_label_text,
                                 width=72,
                                 height=6)
        format_label.grid(row=0, column=0, sticky=W, padx=5)

        if self.aim_tool_number == "01-01":
            format_file = "./samples/01-01(01).json"
            grou_sb_text = "绘图数据示例:" + str(format_file)

            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            # s = ttk.Style()
            # s.configure('TLabelframe.Label', font='arial 14 bold', background='#fff2cc')
            # group_sb = ttk.LabelFrame(export_frame, text=grou_sb_text, width=500, height=500)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = ttk.Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')

            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)
        if self.aim_tool_number == "01-02":
            self.return_main()  # 暂未实现

        if self.aim_tool_number == "02-04":
            format_file = "./samples/02-04(01).json"
            grou_sb_text = "绘图数据示例:" + str(format_file)
            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')
            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)

        if self.aim_tool_number == "03-03":
            format_file = "./samples/03-03(01).csv"
            grou_sb_text = "绘图数据示例:" + str(format_file)
            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')
            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)

        if self.aim_tool_number == "04-071":
            format_file = "./samples/04-071(01).csv"
            grou_sb_text = "绘图数据示例:" + str(format_file)
            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')
            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)

        if self.aim_tool_number == "04-072":
            format_file = "./samples/04-072(01).csv"
            grou_sb_text = "绘图数据示例:" + str(format_file)
            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')
            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)

        if self.aim_tool_number == "05-05":
            format_file = "./samples/05-05(01).csv"
            grou_sb_text = "绘图数据示例:" + str(format_file)
            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')
            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)

        if self.aim_tool_number == "06-06":
            format_file = "./samples/06-06(01).csv"
            grou_sb_text = "绘图数据示例:" + str(format_file)
            # 添加显示文本的信息框
            group_sb = LabelFrame(export_frame,
                                  text=grou_sb_text,
                                  width=500,
                                  height=500,
                                  bg='#fff2cc',
                                  padx=5,
                                  pady=5)
            group_sb.grid(row=1, column=0, columnspan=2, sticky=W, pady=10)
            sb = Scrollbar(group_sb)
            sb.pack(side=RIGHT, fill=Y)
            lb = Listbox(group_sb, yscrollcommand=sb.set, width=80, height=24)
            file_in = open(format_file, 'r', encoding='utf-8')
            for line in file_in.readlines():
                # print(line, end="")
                lb.insert(END, line)
            lb.pack(side=LEFT, fill=BOTH)
            sb.config(command=lb.yview)

        # # 添加下一步按钮
        btn_format = ttk.Button(export_frame,
                                text="下一步",
                                width=8,
                                command=self.call_format_btn)
        btn_format.grid(row=0, column=1, sticky=W, padx=5)
Beispiel #11
0
class View:
    def __init__(self, root, control):
        self.__root = root
        self.__control = control

        self.__root.title("Lezioni alla Pari")
        self.__root.geometry("1000x600")
        self.__root.minsize(800, 500)
        # self.__root.resizable(width="False", height="False")

        self.__frameInfo = Frame(self.__root)
        self.__frameInfo.pack(side=TOP, fill=X, padx=5, pady=10)

        self.__frameLesson = Frame(self.__root)
        self.__frameLesson.pack(side=BOTTOM,
                                fill=BOTH,
                                padx=5,
                                pady=10,
                                expand=True)

        Button(self.__frameInfo,
               text="Esci",
               width=10,
               height=1,
               command=self.__control.logout).pack(anchor=NE,
                                                   side=RIGHT,
                                                   padx=5)

        self.__user = None
        self.__list = None
        self.__html = HTMLLabel(
            self.__frameLesson,
            html="<p>Doppio-Click su una lezione per aprirla</p>")

    def setView(self, user):
        """
        Setta utente e crea grafica
        :param user: User
        """
        self.__user = user

        text = "Ciao " + self.__user.getName() + " " + self.__user.getSurname(
        ) + "!"
        Label(self.__frameInfo, text=text,
              font=("Helvetica", 18)).pack(side=LEFT, anchor=NW)

        # classes = "Classi: " if len(self.__user.getClass()) > 1 else "Classe: "
        # for classroom in self.__user.getClass():
        #     classes += classroom
        #     if classroom != self.__user.getClass()[-1]:  # Non la prima del ciclo, allora ','
        #          classes += ", "
        # Label(self.__frame, text=classes).pack()

        self.__list = List(self.__frameLesson)
        self.__list.getObjectList().bind("<Double-Button-1>",
                                         self.__control.openElement)

        self.__html.pack(side=RIGHT, anchor=W, fill=BOTH, expand=True)

        if user.getState() != "S":
            Button(self.__frameInfo,
                   text="Nuova Lezione",
                   width=10,
                   height=1,
                   command=self.__control.newLesson).pack(anchor=NE,
                                                          side=RIGHT,
                                                          padx=2)

    def setList(self, lessons):
        self.__list.setList(lessons)  # Carica lista elementi

    def getList(self):
        return self.__list

    def setHTML(self, content):
        self.__html.set_html(content, strip=True)
Beispiel #12
0
 def _create_howto_window(self, source_html=''):
     self.howto_window = tk.Toplevel(self)
     self.html_howto = HTMLLabel(self.howto_window, html=source_html)
     self.html_howto.pack(fill="both", expand=True)
     self.html_howto.fit_height()
Beispiel #13
0
class ExampleApp(tk.Tk):
    PATH_DRAWER = 'path_coloring_thread'
    LABEL_PADDING = ' ' * 10
    PATH_TO_HOWTO_HTML = 'howTo.html'

    def __init__(self):
        self.threads = {}
        tk.Tk.__init__(self)
        self.init_ui()

    def start_timer(self):
        self.started_time = time.time()

    def stop_timer(self):
        self.stopped_time = time.time()

    def resume_timer(self):
        self.started_time += (time.time() - self.stopped_time)

    def end_timer(self, target=None, append_text='', prepend_text=''):
        time_diff = None

        if self.started_time:
            time_diff = time.time() - self.started_time

            if target:
                target.config(text=prepend_text + str(round(time_diff, 5)) +
                              ' sec' + append_text)

        return time_diff

    def switch_statusbar(self, active=False, text=''):
        if self.statusbar:
            if active:
                self.statusbar.config(bg='salmon',
                                      fg='white',
                                      text=text or 'Executing...')
            else:
                self.statusbar.config(bg='light sky blue',
                                      fg='grey39',
                                      text=text or 'Idle')

    @staticmethod
    def validate_entry(entry, validateion_func=int):
        pass

    def check_task_alive(self, thread_name=PATH_DRAWER):
        return self.threads.get(
            thread_name) and self.threads[thread_name].isAlive()

    def decorator_task_alive(self,
                             thread_name=PATH_DRAWER,
                             action=None,
                             return_on_err=True):
        def decorator(func):
            def wrapper(*args, **kwargs):
                if self.check_task_alive(thread_name):
                    if action:
                        action()
                        if return_on_err: return None
                    else:
                        raise Exception('Thread alive')
                return func(*args, **kwargs)

            return wrapper

        return decorator

    @staticmethod
    def set_widget_text(widget, new_value=''):
        widget['text'] = new_value

    @staticmethod
    def message_task_runnig():
        messagebox.showerror(
            'Error', 'Task is already running.\nYou need to stop it first')

    def draw_main(self, base):
        grid_width = 5
        grid_height = 5
        upperbound = 50
        lowerbound = -50

        grid_sizes = (5, 6, 7, 8, 9, 10)
        approaches = OrderedDict([('Brute force', Algorithm.GREATEST),
                                  ('Dynamic programming', Algorithm.DYNAMIC)])
        highlighting_options = OrderedDict([('Off', None), ('Lightning', 0),
                                            ('Very fast', 0.05),
                                            ('Fast', 0.15), ('Medium', 0.25),
                                            ('Slow', 0.5), ('Very slow', 1)])

        path_highlighting_speed = highlighting_options['Very fast']
        approach = approaches['Brute force']

        t = SimpleTable(base, grid_height, grid_width, lowerbound, upperbound)

        @self.decorator_task_alive(thread_name=ExampleApp.PATH_DRAWER,
                                   action=self.message_task_runnig)
        def change_grid_height(event):
            nonlocal t
            nonlocal grid_height
            t.destroy()
            grid_height = int(dropdown.get())
            t = SimpleTable(base, grid_height, grid_width, lowerbound,
                            upperbound)
            t.grid(row=1, column=1, padx=(10, 10))

        @self.decorator_task_alive(action=self.message_task_runnig,
                                   thread_name=ExampleApp.PATH_DRAWER)
        def change_grid_width(event):
            nonlocal t
            nonlocal grid_width
            t.destroy()
            grid_width = int(dropdown2.get())
            t = SimpleTable(base, grid_height, grid_width, lowerbound,
                            upperbound)
            t.grid(row=1, column=1, padx=(10, 10))

        @self.decorator_task_alive(action=self.message_task_runnig,
                                   thread_name=ExampleApp.PATH_DRAWER)
        def change_upperbound(value):
            nonlocal t
            nonlocal upperbound
            if value != '' and value != None:
                t.destroy()
                upperbound = value
                t = SimpleTable(base, grid_height, grid_width, lowerbound,
                                upperbound)
                t.grid(row=1, column=1, padx=(10, 10))

        @self.decorator_task_alive(action=self.message_task_runnig,
                                   thread_name=ExampleApp.PATH_DRAWER)
        def change_lowerbound(value):
            nonlocal t
            nonlocal lowerbound
            if value != '' and value != None:
                t.destroy()
                lowerbound = value
                t = SimpleTable(base, grid_height, grid_width, lowerbound,
                                upperbound)
                t.grid(row=1, column=1, padx=(10, 10))

        @self.decorator_task_alive(action=self.message_task_runnig,
                                   thread_name=ExampleApp.PATH_DRAWER)
        def change_speed(event):
            nonlocal path_highlighting_speed
            path_highlighting_speed = highlighting_options[dropdown3.get()]

        @self.decorator_task_alive(action=self.message_task_runnig,
                                   thread_name=ExampleApp.PATH_DRAWER)
        def change_approach(event):
            nonlocal approach
            approach = approaches[dropdown4.get()]

        validate_upperbound = ValidatorFunctor(
            lowerbound=-999,
            upperbound=999,
            validation_func=lambda x: int(x) >= lowerbound,
            converion_func=int,
            exception_func=lambda x: x == '',
            throw=False,
            return_self=True,
            action=messagebox.showerror,
            action_args=
            ("Error",
             f"Upperbound value must be integer between -999 and 999 inclusive;\nUpperbound must be greater/equal lowerbound\n"
             f"Previous upperbound: {upperbound}\nPrevious lowerbound: {lowerbound}"
             ))

        validate_lowerbound = ValidatorFunctor(
            lowerbound=-999,
            upperbound=999,
            validation_func=lambda x: int(x) <= upperbound,
            converion_func=int,
            exception_func=lambda x: x == '',
            throw=False,
            return_self=True,
            action=messagebox.showerror,
            action_args=
            ("Error",
             f"Lowerbound value must be integer between -999 and 999 inclusive;\nLowerbound must be less/equal upperbound\n"
             f"Previous upperbound: {upperbound}\nPrevious lowerbound: {lowerbound}"
             ))

        output_widget = tk.Frame(base)
        label_output_text = tk.Label(output_widget, text='Result: ')
        label_output = tk.Label(output_widget,
                                text=ExampleApp.LABEL_PADDING,
                                bg='white')
        output_clear_button = tk.Button(
            output_widget,
            text='Clear',
            command=lambda: self.set_widget_text(
                label_output, new_value=ExampleApp.LABEL_PADDING))
        label_output_text.grid(row=0, column=0)
        label_output.grid(row=0, column=1)
        output_clear_button.grid(row=0, column=2)

        buttons = tk.Frame(base)
        rerandom_grid_button = tk.Button(
            buttons,
            text='Rerandom grid',
            command=lambda: change_upperbound(upperbound))
        rerandom_grid_button.grid(row=0, column=0, columnspan=2, pady=(0, 10))

        input_frame1 = tk.Frame(buttons,
                                highlightbackground="light grey",
                                highlightthickness=1)
        label1 = tk.Label(input_frame1, text='Upperbound: ')
        entry1 = tk.Entry(input_frame1, width=20)
        label1.grid(row=0, column=0)
        entry1.grid(row=1, column=0, padx=(10, 10))
        # submit_button1.grid(row=0, column=1)

        label2 = tk.Label(input_frame1, text='Lowerbound: ')
        label2.grid(row=2, column=0)
        # input_frame2 = tk.Frame(buttons)
        entry2 = tk.Entry(input_frame1, width=20)
        # submit_button2 = tk.Button(input_frame1, text='Ok', command=lambda : change_lowerbound(validate_lowerbound.check(entry2.get())))
        entry2.grid(row=3, column=0, padx=(10, 10))

        # submit_button2.grid(row=0, column=1)
        # input_frame2.grid(row=4, column=0, columnspan=2)

        def process_input_frame1(event=None):
            change_upperbound(validate_upperbound.check(entry1.get()))
            change_lowerbound(validate_lowerbound.check(entry2.get()))

        submit_button1 = tk.Button(input_frame1,
                                   text='Ok'.center(26),
                                   command=process_input_frame1)
        entry1.bind('<Return>', process_input_frame1)
        entry2.bind('<Return>', process_input_frame1)
        # submit_button1.place(in_=input_frame1, x=0, rely=1, anchor=tk.CENTER)
        submit_button1.grid(row=4, column=0, columnspan=2, pady=(5, 5))

        input_frame1.grid(row=2, column=0, columnspan=2)

        label3 = tk.Label(buttons, text='Grid height:')
        dropdown = ttk.Combobox(buttons, value=grid_sizes)
        dropdown.current(0)
        dropdown.bind('<<ComboboxSelected>>', change_grid_height)
        label3.grid(row=5, column=0)
        # label3.configure(anchor="center")
        dropdown.grid(row=6, column=0, columnspan=2)

        label4 = tk.Label(buttons, text='Grid width:')
        dropdown2 = ttk.Combobox(buttons, value=grid_sizes)
        dropdown2.current(0)
        dropdown2.bind('<<ComboboxSelected>>', change_grid_width)
        label4.grid(row=7, column=0)
        dropdown2.grid(row=8, column=0, columnspan=2)

        label5 = tk.Label(buttons, text='Path highlighting: ')
        dropdown3 = ttk.Combobox(buttons,
                                 value=list(highlighting_options.keys()))
        dropdown3.current(2)
        dropdown3.bind('<<ComboboxSelected>>', change_speed)
        label5.grid(row=9, column=0)
        dropdown3.grid(row=10, column=0, columnspan=2)

        label6 = tk.Label(buttons, text='Approach: ')
        dropdown4 = ttk.Combobox(buttons, value=list(approaches.keys()))
        dropdown4.current(0)
        dropdown4.bind('<<ComboboxSelected>>', change_approach)
        label6.grid(row=11, column=0)
        dropdown4.grid(row=12, column=0, columnspan=2)

        start_terminate_btn_frame = tk.Frame(buttons)

        def start_pause_resume_thread(event=None):
            if not self.threads.get(ExampleApp.PATH_DRAWER):
                self.thread_walkt(
                    t,
                    sleep_time=path_highlighting_speed,
                    draw=True if path_highlighting_speed != None else False,
                    on_raise=lambda _: messagebox.showerror(
                        'Error',
                        'Task is already running.\nYou need to stop it first'),
                    send_res_action=lambda res: self.set_widget_text(
                        label_output,
                        str(res['PATH_SUM']).rjust(
                            len(ExampleApp.LABEL_PADDING))
                    )  # .rjust(len(ExampleApp.LABEL_PADDING), ' ')
                    ,
                    algo=approach)
                self.switch_statusbar(active=True)
                self.start_timer()
                start_button.config(text='Pause')
            elif not self.threads[ExampleApp.PATH_DRAWER].stopped():
                self.threads[ExampleApp.PATH_DRAWER].stop()
                self.switch_statusbar(active=True, text='Paused')
                self.stop_timer()
                start_button.config(text='Resume')
            else:
                self.threads[ExampleApp.PATH_DRAWER].resume()
                self.switch_statusbar(active=True)
                self.resume_timer()
                start_button.config(text='Pause')

        def kill_thread(event=None):
            if not self.threads.get(ExampleApp.PATH_DRAWER):
                t.highlight_all('white')
                return
            self.threads[ExampleApp.PATH_DRAWER].kill()
            self.threads[ExampleApp.PATH_DRAWER].resume()
            del self.threads[ExampleApp.PATH_DRAWER]
            self.switch_statusbar(active=False)
            start_button.config(text='Go')

        start_button = tk.Button(start_terminate_btn_frame,
                                 text='Go',
                                 command=start_pause_resume_thread,
                                 width=10)
        terminate_button = tk.Button(start_terminate_btn_frame,
                                     text='Stop',
                                     command=kill_thread,
                                     width=10)
        self.bind('<space>', start_pause_resume_thread)
        self.bind('c', kill_thread)

        start_button.grid(row=0, column=0)
        self.start_button = start_button
        terminate_button.grid(row=0, column=1)

        start_terminate_btn_frame.grid(row=13,
                                       column=0,
                                       columnspan=2,
                                       pady=(10, 0))

        label_main = tk.Label(base,
                              text='Find the greatest path',
                              pady=10,
                              font='Helvetica 11 bold')

        label_main.grid(row=0, column=0, columnspan=2)
        t.grid(row=1, column=1, padx=(10, 10))
        buttons.grid(row=1, column=0, padx=(10, 10))
        output_widget.grid(row=2, column=1, pady=(0, 10))

    def terminate(self):
        self.destroy()

    def create_about_window(self):
        self.about_window = tk.Toplevel(self)
        name = tk.Label(self.about_window,
                        text='IndustriouSlime',
                        font='Helvetica 11 bold')
        version = tk.Label(self.about_window,
                           text='Version: 1.0.0',
                           anchor=tk.W)
        created_by = tk.Label(self.about_window,
                              text='Created by: Sergey Orlovskyi',
                              anchor=tk.W)
        creation_date = tk.Label(self.about_window,
                                 text='Createion date: 2020-05-07',
                                 anchor=tk.W)
        contact_info = tk.Label(self.about_window,
                                text='Contact info: [email protected]',
                                anchor=tk.W)
        purpose = tk.Label(
            self.about_window,
            text=
            'Purpose: App targeted at finding path with the greatest sum of nodes',
            anchor=tk.W)
        name.pack()
        version.pack(fill='both')
        created_by.pack(fill='both')
        creation_date.pack(fill='both')
        contact_info.pack(fill='both')
        purpose.pack(fill='both')

    def create_howto_window(self):
        self._create_howto_window(
            source_html=read_file(self.PATH_TO_HOWTO_HTML))

    def _create_howto_window(self, source_html=''):
        self.howto_window = tk.Toplevel(self)
        self.html_howto = HTMLLabel(self.howto_window, html=source_html)
        self.html_howto.pack(fill="both", expand=True)
        self.html_howto.fit_height()

    def draw_header(self):
        menubar = tk.Menu(self)

        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label='Exit', command=self.terminate)
        menubar.add_cascade(label='App', menu=filemenu)
        self.bind('q', lambda e: self.terminate())

        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label='HowTo', command=self.create_howto_window)
        helpmenu.add_command(label='About', command=self.create_about_window)
        menubar.add_cascade(label='Help', menu=helpmenu)
        self.bind('<F1>', lambda e: self.create_howto_window())

        supportmenu = tk.Menu(menubar, tearoff=0)
        supportmenu.add_command(
            label='Donate',
            command=lambda: messagebox.showinfo('Donate', 'Just kidding :)'))
        menubar.add_cascade(label='Support', menu=supportmenu)

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

    def draw_footer(self):
        self.statusbar = tk.Label(self,
                                  text='Idle ',
                                  bd=1,
                                  relief=tk.SUNKEN,
                                  anchor=tk.E,
                                  bg='white')
        self.statusbar.pack(side=tk.BOTTOM, fill=tk.X)
        self.switch_statusbar(active=False)

    def init_ui(self):
        self.base = tk.Frame()
        self.base.pack()

        self.draw_header()
        self.draw_footer()

        self.draw_main(self.base)

    def thread_walkt(self,
                     t,
                     sleep_time=0.05,
                     draw=True,
                     send_res_action=None,
                     on_raise=None,
                     algo=Algorithm.GREATEST):
        try:
            if self.threads.get(ExampleApp.PATH_DRAWER) and self.threads[
                    ExampleApp.PATH_DRAWER].isAlive():
                raise Exception('Thread is still runnig')
            thread = StoppableThread(target=self.walkt,
                                     args=(
                                         t,
                                         sleep_time,
                                         draw,
                                         send_res_action,
                                         algo,
                                     ))
            thread.daemon = True
            self.threads[ExampleApp.PATH_DRAWER] = thread
            thread.start()
        except Exception as ex:
            if on_raise:
                on_raise(ex)
            else:
                raise ex

    @staticmethod
    def raise_termination():
        raise 'The thread has been terminated'

    def walkt(self,
              t,
              sleep_time,
              draw=True,
              send_res_action=None,
              algo=Algorithm.GREATEST):
        path_tracker = t.createDynamicTracker(idle_time=sleep_time)

        def highlight_task(path):
            if threading.current_thread().killed():
                t.highlight_all('white')
                self.raise_termination()
            elif not threading.current_thread().stopped():
                path_tracker.highlight_path_common(path, 'red')
            else:
                threading.current_thread().wait_for_resume()

        def idle_task(path):
            if threading.current_thread().killed():
                self.raise_termination()
            elif not threading.current_thread().stopped():
                pass
            else:
                threading.current_thread().wait_for_resume()

        callback_ = highlight_task if draw else idle_task

        a = Algorithm(t._widgets,
                      algo,
                      callback=callback_,
                      getter=lambda a: int(a['text']))
        res = None
        try:
            res = a.run()
            t.highlight_all('white')
            t.highlight_path(res['PATH'], 'green2')
            if send_res_action: send_res_action(res)

            if self.threads.get(self.PATH_DRAWER):
                self.threads[self.PATH_DRAWER].kill(
                )  # TODO: don't like this approach, bounding function to thread name; threading.current_thread doesn't work
                del self.threads[self.PATH_DRAWER]

            self.switch_statusbar(active=False)
            self.end_timer(target=self.statusbar, prepend_text='Executed in ')
            self.start_button.config(text='Go')
        except:
            pass