Esempio n. 1
0
 def setup_gui(self):
     self.parent.title("Stein - Saks - Papir")
     self.style.theme_use("default")
     self.pack(fill=BOTH, expand=1)
     # Label for rapportering
     label = Label(self.parent, textvariable=self.resultat_label)
     label.place(x=800, y=50)
     # Buttons
     # Disse fyrer av metoden self.arranger_enkeltspill som er
     # definert i klassen. Denne metoden tar aksjonen til mennesket
     # som startup, og gjennomfoerer spillet
     # Samme type oppfoersel for de tre aksjons-knappene
     rock_button = Button(self, text="Stein",
                          command=lambda: self.arranger_enkeltspill(Action("rock")))
     rock_button.place(x=800, y=400)
     scissors_button = Button(self, text="Saks",
                              command=lambda: self.arranger_enkeltspill(Action("scissor")))
     scissors_button.place(x=900, y=400)
     paper_button = Button(self, text="Papir",
                           command=lambda: self.arranger_enkeltspill(Action("paper")))
     paper_button.place(x=1000, y=400)
     # quit_button avslutter GUI'et naar den trykkes
     quit_button = Button(self, text="Quit", command=self.quit)
     quit_button.place(x=1000, y=450)
     # Embedde en graf i vinduet for aa rapportere fortloepende score
     self.fig = FigureCanvasTkAgg(pylab.figure(), master=self)
     self.fig.get_tk_widget().grid(column=0, row=0)
     self.fig.show()
Esempio n. 2
0
 class PredictionWidget(Frame):
     """Shows a prediction to the user."""
     def __init__(self, master):
         """Make boxes, register callbacks etc."""
         Frame.__init__(self, master)
         self.active_category = StringVar()
         self.bind("<Configure>", self.onResize)
         self.date = None
         self.predictor = Predictor()
         self.category_buttons = self.createCategoryButtons()
         self.text = Label(self, justify=CENTER, font="Arial 14")
     def createCategoryButtons(self):
         """Create the buttons used to choose category. Return them."""
         result = []
         icons = self.readIcons()
         categories = self.predictor.categories()
         for i in categories:
             if i in icons:
                 icon = icons[i]
             else:
                 icon = icons["= default ="]
             category_button = Radiobutton(self, image=icon,
                  variable=self.active_category, value=i, indicatoron=False,
                  width=icon_size, height=icon_size, command=self.update)
             category_button.image_data = icon
             result.append(category_button)
         self.active_category.set(categories[0])
         return result
     def readIcons(self):
         """Read the gui icons from disk. Return them."""
         result = {}
         categories = open(nextToThisFile("icons.txt")).read().split("\n\n")
         for i in categories:
             category_name, file_data = i.split("\n", maxsplit=1)
             image = PhotoImage(data=file_data)
             result[category_name] = image
         return result
     def onResize(self, event):
         """Rearrange the children when the geometry of self changes."""
         if event.widget == self:
             center = (event.width / 2, event.height / 2)
             radius = min(center) - icon_size / 2
             self.text.place(anchor=CENTER, x=center[0], y=center[1])
             for i, j in enumerate(self.category_buttons):
                 turn = 2 * math.pi
                 angle = turn * (1 / 4 - i / len(self.category_buttons))
                 j.place(anchor=CENTER,
                         x=center[0] + math.cos(angle) * radius,
                         y=center[1] - math.sin(angle) * radius)
     def update(self, date=None):
         """Change contents based on circumstances. Set date if given."""
         if date:
             self.date = date
         if self.date:
             predictions = self.predictor.predict(self.date)
             prediction = predictions[self.active_category.get()]
             prediction = textwrap.fill(prediction, width=20)
         else:
             prediction = ""
         self.text.configure(text=prediction)
Esempio n. 3
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=210)

    def onSelect(self, val):

        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)
Esempio n. 4
0
    def initUI(self):
        # Initialize and name Window
        self.parent.title("Poly Pocket")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        def new_baseline():

            return
        def old_baseline():
            return
        def test(baseline):
            return
        def spark_connect():
            return
        def leap_connect():
            return
        def quit():
            self.parent.destroy()
            return

        welcome = "Welcome to Poly Pocket!"
        welcome_label = Label(self, text=welcome, font=("Helvetica", 24))
        welcome_label.place(x=5, y=5)
        welcome_label.pack()
        
        baseline_button = Button(self, text="New Baseline",
                command=new_baseline())
        recover_baseline_button = Button(self, text="Recover Baseline",
                command=old_baseline())
        test_button = Button(self, text="Conduct Test",
                command=test(self.baseline))
        connect_leap_button = Button(self, text="Establish Leap Connection",
                command=leap_connect)
        connect_spark_button = Button(self, text="Establish Spark Connection",
                command=spark_connect)
        exit_button = Button(self, text="Quit",
                command=quit)
        
        baseline_button.place(relx=0.5, rely=0.3, anchor=CENTER)
        recover_baseline_button.place(relx=0.5, rely=0.4, anchor=CENTER)
        test_button.place(relx=0.5, rely=0.5, anchor=CENTER)
        connect_leap_button.place(relx=0.5, rely=0.6, anchor=CENTER)
        connect_spark_button.place(relx=0.5, rely=0.7, anchor=CENTER)
        exit_button.place(relx=0.5, rely = 0.8, anchor=CENTER)
Esempio n. 5
0
class Pencil(Frame): # pylint: disable=too-many-ancestors
    """A smaller box (of 0-9) representing the pencil marks in a normal box."""

    def __init__(self, master):
        """Construct a Pencil frame with parent master.

        Args:
            master: The parent frame.
        """
        Frame.__init__(self, master, width=10, height=10, style=styles.BOX_FRAME)
        self.position = (0, 0)
        self.number_value = ' '
        self.number_text = StringVar(self, ' ')

        self.label = Label(self, textvariable=self.number_text, style=styles.PENCIL_LABEL)
        self.label.place(relx=0.5, rely=0.5, anchor='center')

    def place_at_position(self, position):
        """Places this frame in its parent at the given position.

        Args:
            position: Tuple of (x, y) for the position to place at.
        """
        row = position[0]
        col = position[1]
        self.position = position
        frame_index = row * 3 + col
        self.number_value = str(frame_index + 1)

    def show(self, flag):
        """Show or hide the pencil frame, based on the flag.

        Args:
            flag: `True` to show this pencil mark, `False` to hide it.
        """
        self.number_text.set(self.number_value if flag else ' ')
Esempio n. 6
0
class App_test(object):
    def __init__(self):
        self.win = Tk()
        self.win.title('12306火车票查询系统V2.6')
        self.win.geometry('860x400')
        self.creat_res()
        self.add_train_info()
        self.add_check_button()
        self.res_config()
        self.train_message = {}
        # self.get_train_args()
        self.win.mainloop()

    def creat_res(self):
        self.v = IntVar()  #车票查询
        self.v.set(True)
        self.temp = StringVar()  #开始站
        self.temp2 = StringVar()  #目的站
        self.start_mon = StringVar()  #出发月
        self.start_day = StringVar()  #出发日
        self.start_year = StringVar()  #出啊年
        self.E_startstation = Entry(self.win, textvariable=self.temp)
        self.E_endstation = Entry(self.win, textvariable=self.temp2)
        self.La_startstation = Label(self.win, text="出发站:")
        self.La_endstation = Label(self.win, text="目的站:")
        self.La_time = Label(self.win, text="请选择出发时间-年-月-日", fg="blue")
        self.B_search = Button(self.win, text="搜索")
        self.R_site = Radiobutton(self.win,
                                  text="车票查询",
                                  variable=self.v,
                                  value=True)
        self.R_price = Radiobutton(self.win,
                                   text="票价查询",
                                   variable=self.v,
                                   value=False)
        self.B_buy_tick = Button(self.win, text="购票")
        self.C_year = Combobox(self.win, textvariable=self.start_year)
        self.C_mon = Combobox(self.win, textvariable=self.start_mon)
        self.La_s = Label(self.win, text="--")
        self.C_day = Combobox(self.win, textvariable=self.start_day)
        self.S_move = Scrollbar(self.win)
        self.E_startstation.place(x=70, y=10, width=65, height=30)
        self.E_endstation.place(x=70, y=60, width=65, height=30)
        self.La_startstation.place(x=10, y=10, width=50, height=30)
        self.La_endstation.place(x=10, y=60, width=50, height=30)
        self.La_time.place(x=10, y=100, width=150, height=30)
        self.C_year.place(x=10, y=140, width=70, height=30)
        self.C_mon.place(x=100, y=140, width=50, height=30)
        self.C_day.place(x=100, y=180, width=50, height=30)
        self.La_s.place(x=80, y=140, width=20, height=30)
        self.B_search.place(x=10, y=180, width=50, height=30)
        self.S_move.place(x=834, y=40, width=30, height=350)
        self.B_buy_tick.place(x=10, y=260, width=80, height=40)
        self.R_site.place(x=10, y=230, width=70, height=30)
        self.R_price.place(x=90, y=230, width=70, height=30)

    def res_config(self):
        self.C_year.config(values=[x for x in range(2018, 2020)])
        self.C_mon.config(values=["{:02d}".format(x)
                                  for x in range(1, 13)])  #时间格式是2018-01-01
        self.C_day.config(values=["{:02d}".format(x) for x in range(1, 32)])
        self.B_search.config(command=self.search_train_message)
        self.S_move.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.S_move.set)

    def add_train_info(self):
        lis_train = ["C" + str(x) for x in range(0, 15)]
        tuple_train = tuple(lis_train)
        self.tree = Treeview(self.win,
                             columns=tuple_train,
                             height=30,
                             show="headings")
        self.tree.place(x=168, y=40, width=670, height=350)
        train_info = [
            ' 车次 ', ' 出发/到达站', '出发/到达时间', '历时 ', '商/特座', '一等座', '二等座', '高软',
            '软卧', '动卧', '硬卧', '软座', '硬座', '无座', '其他'
        ]
        for i in range(0, len(lis_train)):
            self.tree.column(lis_train[i],
                             width=len(train_info[i]) * 11,
                             anchor='center')
            self.tree.heading(lis_train[i], text=train_info[i])

    def add_check_button(self):
        self.v1 = IntVar()
        self.v2 = IntVar()
        self.v3 = IntVar()
        self.v4 = IntVar()
        self.v5 = IntVar()
        self.v6 = IntVar()
        self.v7 = IntVar()
        self.v1.set("T")
        self.Check_total = Checkbutton(self.win,
                                       text="全部车次",
                                       variable=self.v1,
                                       onvalue='T')
        self.Check_total.place(x=168, y=7, width=80, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="G-高铁",
                                       variable=self.v2,
                                       onvalue='T')
        self.Check_total.place(x=258, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="D-动车",
                                       variable=self.v3,
                                       onvalue='T')
        self.Check_total.place(x=348, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="Z-直达",
                                       variable=self.v4,
                                       onvalue='T')
        self.Check_total.place(x=418, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="T-特快",
                                       variable=self.v5,
                                       onvalue='T')
        self.Check_total.place(x=488, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="K-快速",
                                       variable=self.v6,
                                       onvalue='T')
        self.Check_total.place(x=568, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="其他",
                                       variable=self.v7,
                                       onvalue='T')
        self.Check_total.place(x=648, y=7, width=60, height=30)

    def get_train_args(self):  #输出获得的日期,出发站代码,目的站代码
        date = self.start_year.get() + "-" + self.start_mon.get(
        ) + "-" + self.start_day.get()
        start_station = self.temp.get()
        end_station = self.temp2.get()
        start_station_str = ""
        end_station_str = ""
        count1, count2 = 0, 0
        with open("res/dict2.txt", mode='r', encoding='utf-8') as f:
            mes = f.readlines()
            for i in mes:
                d = json.loads(i)
                if start_station in d:
                    start_station_str = d[start_station]
                else:
                    count1 += 1
                if end_station in d:
                    end_station_str = d[end_station]
                else:
                    count2 += 1
            if count1 == len(mes) or count2 == len(mes):
                messagebox.showwarning(title="友情提示", message="无法找到车站数据")
        return date, start_station_str, end_station_str

    def is_leapyear(self):
        #先判断输入是否是日期,如果是日期执行方法体,
        a = self.C_year.get()
        b = self.C_mon.get()
        c = self.C_day.get()
        pa_year = '20[\d][\d]'  # 2018
        if re.compile(pa_year).findall(a) and b in [
                "{:02d}".format(x) for x in range(1, 13)
        ] and c in ["{:02d}".format(x) for x in range(1, 32)]:
            nowtime = time.localtime()
            now_time_sp = time.mktime(nowtime)
            start_time = a + "-" + b + "-" + c + " 23:59:29"  #"2018-08-09  23:59:29"
            start_timestrip = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            start_times = time.mktime(start_timestrip)
            days = (start_times - now_time_sp) / 60 / 60 / 24
            print(days)
            print(a, b, c)
            if days > 29:
                messagebox.showerror(title="警告", message="大于30天无法获取数据")
            elif days < 0:
                messagebox.showerror(title="警告", message="小于1天无法获取数据")
            elif days > 0 and days < 30:
                if int(a) % 4 == 0 and int(a) % 100 != 0 or int(
                        a) % 400 == 0:  #如果是闰年
                    if (int(b) in (1, 3, 5, 7, 8, 10, 12) and int(c) > 31) or (
                        (int(b) in (4, 6, 9, 11)
                         and int(c) > 30)) or (int(b) == 2 and int(c) > 29):
                        messagebox.showerror(title="警告", message="你确定这个月有这一天么")
                else:
                    if (int(b) in (1, 3, 5, 8, 10, 12) and int(c) > 31) or (
                        (int(b) in (4, 6, 9, 11)
                         and int(c) > 30)) or (int(b) == 2 and int(c) > 28):
                        messagebox.showerror(title="警告", message="你确定这个月有这一天么")
        else:
            messagebox.showerror(title="警告", message="请输入正确格式的年:月:日")

    def manage_date(self):  #处理时间,闰年以及当天时间
        self.is_leapyear()

    def change_str(self, mm):
        for i, j in mm.items():
            with open("res/dict.txt", mode='r', encoding='utf-8') as f:
                mes = f.readlines()
                for s in mes:
                    d = json.loads(s)
                    if j[0] in d:
                        j[0] = d[j[0]]
                    if j[1] in d:
                        j[1] = d[j[1]]
        # print(self.new_train_message) #车次信息
        non_empty_str = ['']
        for m, n in mm.items():
            mm[m] = ['-' if x in non_empty_str else x for x in n]  # 替换''字符为'-'
        return mm

    def trans_train_dic(self):  #输出出发站-目的站-名字
        date, start_station, end_station = self.get_train_args()
        print(date, start_station, end_station)
        try:
            p = Pro_train(date, start_station, end_station)
            self.train_message = p.get_train_res()  # 获得车次信息字典 车次英文
            self.train_tick = p.get_tarin_ticket()  #获得票价信息
            # print(self.train_message) #车次信息
            self.new_train_message = self.train_message  #复制一份
            self.new_train_tick = self.train_tick
            self.new_train_message = self.change_str(self.new_train_message)
            self.new_train_tick = self.change_str(self.new_train_tick)
            return self.new_train_message, self.new_train_tick  # 中文字典
        except Exception as e:
            # messagebox.showerror(title="警告",message="无法解析数据,请重新选择")
            print("错误码:", e.args)

    def search_train_message(self):
        self.manage_date()  #处理日期-True-transe-view
        if self.v.get():
            self.view_list()
        else:
            self.view_price()

    def clear_tree(self):
        x = self.tree.get_children()
        for n in x:
            self.tree.delete(n)

    def view_list(self):  #显示到网格
        # 车次 出发/站 出发到达时间 历时 商务座31  一等座30 二等座29  高软20 软卧22 动卧 硬卧27 软座23 硬座28 无座25 其他21
        try:
            self.clear_tree()
            self.new_train_message, x = self.trans_train_dic()  #生成新车次字典
            for i, j in self.new_train_message.items():
                self.tree.insert("",
                                 "end",
                                 values=(i, j[0] + "->" + j[1],
                                         j[2] + "->" + j[3], j[4], j[5], j[6],
                                         j[7], j[8], j[9], j[10], j[11], j[12],
                                         j[13], j[14], j[15]))
        except Exception as e:
            # messagebox.showerror(title="警告",message="无法处理数据")
            print("错误:", e.args)

    def view_price(self):
        print("-------票价ok-------")
        try:
            self.clear_tree()
            y, self.new_train_tick = self.trans_train_dic()  #生成新车次字典
            for i, j in self.new_train_tick.items():
                self.tree.insert("",
                                 "end",
                                 values=(i, j[0] + "->" + j[1],
                                         j[2] + "->" + j[3], j[4], j[5], j[6],
                                         j[7], j[8], j[9], j[10], j[11], j[12],
                                         j[13], j[14], "-"))
        except Exception as e:
            # messagebox.showerror(title="警告",message="无法处理数据")
            print("错误:", e.args)
Esempio n. 7
0
class main():
    def __init__(self, tk):

        self.frame_lgn = Frame(lgn_Screen, width=450, height=750)
        self.frame_lgn.pack()

        #Separator
        self.pane_W = LabelFrame(lgn_Screen,
                                 text='Your Credentials',
                                 width=300,
                                 height=200)
        self.pane_W.place(x=1, y=10)

        #Login Entry
        self.usr_label = Label(lgn_Screen, text="Usuário:")
        self.usr_label.place(x=22, y=53)
        self.usr_entry = Entry(lgn_Screen, width=25)
        self.usr_entry.place(x=72, y=50)
        #Passowrd Entry
        self.pw_label = Label(lgn_Screen, text="Senha:")
        self.pw_label.place(x=30, y=103)
        self.pw_entry = Entry(lgn_Screen, show="*", width=25)
        self.pw_entry.place(x=72, y=100)

        def validate():
            usr = str(self.usr_entry.get())
            pw = str(self.pw_entry.get())

            print(usr)
            print(pw)

        #Separator message
        self.pane_W_Text = LabelFrame(lgn_Screen,
                                      text='Your Message:',
                                      width=300,
                                      height=200)
        self.pane_W_Text.place(x=1, y=210)
        #textbox
        self.tb = Text(lgn_Screen, width=35, height=8, borderwidth=0)
        self.tb.place(x=7, y=225)

        #Separator data
        self.pane_groups = LabelFrame(lgn_Screen,
                                      text='Seus Grupos aparecerão aqui:',
                                      width=300,
                                      height=200)
        self.pane_groups.place(x=1, y=410)

        self.tvGroups = Treeview(lgn_Screen)
        self.tvGroups.place(x=7, y=425, width=287, height=130)

        #Aviso de Botão
        fontStyle = tkFont.Font(size=8)
        self.advcLbl = Label(
            lgn_Screen,
            text=
            "* Aviso: o botão para confirmar o grupo será \nliberado em breve!",
            font=fontStyle)
        self.advcLbl.place(x=7, y=610)

        def conf_Message():
            msg = str(self.tb.get('1.0', 'end-1c'))
            print(msg)
            from selenium import webdriver
            from time import sleep
            from selenium.webdriver.common.keys import Keys

            url = "https://facebook.com/"
            d = webdriver.Chrome()
            d.get(url)

            sleep(2)

            target_user = d.find_element_by_xpath('//*[@id="email"]')
            target_pw = d.find_element_by_xpath('//*[@id="pass"]')
            target_user.click()
            sleep(2)
            target_user.send_keys(str(self.usr_entry.get()))
            sleep(2)
            target_pw.send_keys(str(self.pw_entry.get()))
            sleep(6)
            log_in = d.find_element_by_xpath('//*[@id="u_0_b"]')
            sleep(1)
            log_in.click()
            sleep(3)
            webdriver.ActionChains(d).send_keys(Keys.ESCAPE).perform()
            sleep(4)
            explore_Group = d.find_element_by_xpath(
                '//*[@id="navItem_1434659290104689"]/a/div')
            explore_Group.click()
            sleep(3)
            webdriver.ActionChains(d).send_keys(Keys.ESCAPE).perform()
            sleep(1)
            try:
                while True:
                    see_more = d.find_element_by_xpath(
                        "//*[contains(text(), 'Ver mais')]")
                    see_more.click()
                    sleep(2)
            except:
                pass
            sleep(3)
            groups = d.find_elements_by_class_name('_2yaa')
            l_groups = []
            for g_names in groups:
                l_groups.append(str(g_names.text))

            print(l_groups)
            group_index = []
            counter = 0
            for j in l_groups[:-1]:
                if str(j) == 'Descobrir':
                    continue
                print(str(counter) + " - " + str(j))
                counter += 1
                self.tvGroups.insert('', 'end', text=j)

            #selected_Group = ""
            def confirmGroup():
                self.cur = self.tvGroups.focus()
                self.selectedItem = str(self.tvGroups.item(self.cur)['text'])
                print(self.selectedItem)

                openGroup = d.find_element_by_xpath("//*[contains(text(), '" +
                                                    self.selectedItem + "')]")
                openGroup.click()
                sleep(6)
                postit = d.find_element_by_xpath(
                    "//*[@name='xhpc_message_text']")
                postit.send_keys(str(self.tb.get('1.0', 'end-1c')))
                sleep(5)
                publish = d.find_element_by_class_name('_332r')
                publish.click()

            self.selgroup = Button(lgn_Screen,
                                   text="Confirmar",
                                   width=10,
                                   font='Verdana 8',
                                   borderwidth=0,
                                   bg='#FFFFFF',
                                   fg='#363636',
                                   command=confirmGroup)
            self.selgroup.place(x=175, y=570)

        self.cnf_Msg = Button(lgn_Screen,
                              text="Confirmar",
                              width=10,
                              font='Verdana 8',
                              borderwidth=0,
                              bg='#FFFFFF',
                              fg='#363636',
                              command=conf_Message)
        self.cnf_Msg.place(x=175, y=370, height=20)
Esempio n. 8
0
class App(ThemedTk):
    def __init__(self):
        ThemedTk.__init__(self, theme='black')
        self.title('Установщик F_Reference_H')
        self.geometry('500x200')
        x = (self.winfo_screenwidth() -
             self.winfo_reqwidth()) / 2
        y = (self.winfo_screenheight() -
             self.winfo_reqheight()) / 2
        self.wm_geometry("+%d+%d" % (x - 150, y - 20))
        self.resizable(width=False, height=False)
        self.iconphoto(
            True,
            PhotoImage(file='bin/ico/ico_main.png')
        )
        flow_hack_png = Image.open(f'bin/ico/max_flowhack.png')
        flow_hack_png = ImageTk.PhotoImage(flow_hack_png)
        browse_png = Image.open(f'bin/ico/browse.png')
        browse_png = ImageTk.PhotoImage(browse_png)
        self.frame = Frame(self)
        self.frame.place(relwidth=1, relheight=1)
        self.url = ''
        self._path = getcwd()

        flow_hack_label = Label(
            self.frame,
            image=flow_hack_png,
            cursor='heart'
        )
        flow_hack_label.bind('<Button-1>', open_web)
        flow_hack_label.place(anchor='c', relx=.5, rely=.1)
        self.check_icon = BooleanVar()
        self.check_icon.set(bool(True))
        Checkbutton(
            self.frame,
            text='Создать ярлык на рабочем столе',
            var=self.check_icon,
            cursor='cross'
        ).place(relx=.5, y=60, anchor='c')
        Label(
            self.frame,
            text='Выберите папку для установки',
            font=('Times New Roman', 10, 'bold italic')
        ).place(relx=.5, rely=.485, anchor='c')
        self.input_url = Entry(
            self.frame,
            state=DISABLED,
            font=('Times New Roman', 9, 'bold italic'),
            foreground='black'
        )
        self.input_url.place(
            rely=.6,
            relx=.5,
            height=20,
            relwidth=.7,
            anchor='c'
        )
        Button(
            self.frame,
            image=browse_png,
            cursor='hand1',
            command=self.directory
        ).place(relx=.86, rely=.455)
        Button(
            self.frame,
            image=browse_png,
            cursor='hand1',
            command=self.directory
        ).place(relx=.045, rely=.455)
        Button(
            self.frame,
            text='Установить',
            cursor='hand1',
            command=self.install
        ).place(relx=.5, rely=.75, anchor='c')
        self.license = Label(
            self.frame,
            text='Для подтверждения согласия с лицензионным '
                 'соглашением\nНажмите на "Установить" правой кнопкой мыши',
            font=('Times New Roman', 9, 'bold italic'),
            foreground='black',
            cursor='hand1',
            justify='center'
        )
        self.license.bind(
            '<Button-1>',
            lambda no_matter: webopen('https://flowhack.github.io/')
        )
        self.license.place(relx=.5, rely=.93, anchor='c')

        self.mainloop()

    def directory(self):
        fits: bool = False
        while fits == bool(False):
            self.url = askdirectory()
            if ('\\' not in self.url) and ('/' not in self.url):
                showerror(
                    'Error',
                    'Мы заметили, что вы выбрали неверный адрес!'
                )
            else:
                fits: bool = True

        self.input_url.configure(state=NORMAL)
        self.input_url.insert(END, self.url)
        self.input_url.after(
            6000,
            lambda: self.input_url.configure(state=DISABLED)
        )

    def install(self):
        url = path.join(self.url)
        try:
            if url == '':
                raise NameError('is empty')
            elif ('\\' not in self.url) and ('/' not in self.url):
                raise NameError('not file')
            move_file('bin/dist/F_Reference_H', url)
            if self.check_icon.get():
                system(
                    f'@powershell \"$x=(New-Object -ComObject '
                    f'WScript.Shell).CreateShortcut('
                    f'\'%USERPROFILE%/Desktop/F_Reference_H.lnk\');$x'
                    f'.TargetPath=\''
                    f'{url}/F_Reference_H/F_Reference_H.exe\';$x'
                    f'.WorkingDirectory=\''
                    f'{url}/F_Reference_H\';$x.Save()\" '
                )
                system(
                    f'@powershell \"$x=(New-Object -ComObject '
                    f'WScript.Shell).CreateShortcut('
                    f'\'%APPDATA%\Microsoft\Windows\Start '
                    f'Menu\Programs\F_Reference_H.lnk\');$x'
                    f'.TargetPath=\''
                    f'{url}/F_Reference_H/F_Reference_H.exe\';$x'
                    f'.WorkingDirectory=\'{url}/F_Reference_H\';$x.Save()\"')
                showinfo('Successfully', 'Установка прошла успешно!')
                exit_ex()

        except NameError as error:
            if str(error) == 'is empty':
                showerror('Error', 'Пустое поле пути к папке!')
            if str(error) == 'not file':
                showerror(
                    'Error',
                    'Мы заметили, что вы выбрали неверный адрес!'
                )
Esempio n. 9
0
class Box(Frame):  # pylint: disable=too-many-ancestors
    """Represents a single box (of 0-9) in the sudoku board."""
    _counter = 0

    def __init__(self, master):
        """Construct a Box frame with parent master.

        Args:
            master: The parent frame.
        """
        Frame.__init__(self, master, style=styles.BOX_FRAME)
        self.position = (0, 0)
        self.binding_tag = 'BoxFrame' + str(Box._counter)
        self.number_text = StringVar(self, '')
        Box._counter += 1

        self.borders = dict()
        for edge in 'nesw':
            self.borders[edge] = Border(self, edge)

        self.inner_frame = Frame(self,
                                 width=30,
                                 height=30,
                                 style=styles.BOX_FRAME)
        self.pencil_marks = _build_3x3_grid(self.inner_frame, Pencil)

        self.label = Label(self.inner_frame,
                           textvariable=self.number_text,
                           style=styles.NUMBER_LABEL)

        _tag_widget(self, self.binding_tag)
        _tag_widget(self.inner_frame, self.binding_tag)
        _tag_widget(self.label, self.binding_tag)
        for mark in self.pencil_marks:
            _tag_widget(mark, self.binding_tag)
            _tag_widget(mark.label, self.binding_tag)

    def place_at_position(self, position):
        """Places this frame in its parent at the given position.

        Args:
            position: Tuple of (x, y) for the position to place at.
            parent_position: Tuple of (x, y) for the position the parent is in relative to the grandparent.
        """
        row = position[0]
        col = position[1]

        parent_position = self.master.position  # master "ought to be" SubGrid
        self.position = (parent_position[0] * 3 + row,
                         parent_position[1] * 3 + col)

        padx = (0, _BOX_PADDING) if col < 2 else 0
        pady = (0, _BOX_PADDING) if row < 2 else 0
        self.grid(row=row, column=col, padx=padx, pady=pady, sticky='nesw')

        self.inner_frame.pack(padx=_BORDER_WIDTH,
                              pady=_BORDER_WIDTH,
                              expand=True)
        self.number = 0

    @property
    def number(self):
        """The number the box contains. Setting this value may change the box's style."""
        try:
            return int(self.number_text.get())
        except ValueError:
            return 0

    @number.setter
    def number(self, value):
        for pencil_mark in self.pencil_marks:
            pencil_mark.grid_forget()
        self['style'] = styles.BOX_FRAME
        self.inner_frame['style'] = styles.BOX_FRAME
        self.label['style'] = styles.NUMBER_LABEL

        self.label.place(relx=0.5, rely=0.5, anchor='center')
        self.number_text.set(str(value or ' ')[0])

    @property
    def given(self):
        """The given value for this box. Setting this value may change the box's style."""
        if self['style'] != styles.GIVEN_FRAME:
            return 0
        else:
            return self.number

    @given.setter
    def given(self, value):
        for pencil_mark in self.pencil_marks:
            pencil_mark.grid_forget()
        self['style'] = styles.GIVEN_FRAME
        self.inner_frame['style'] = styles.GIVEN_FRAME
        self.label['style'] = styles.GIVEN_LABEL

        self.label.place(relx=0.5, rely=0.5, anchor='center')
        self.number_text.set(str(value or ' ')[0])

    def set_pencils(self, values=0b111111111):
        """Sets the box's pencils to showing.

        Args:
            values: Which pencil marks to display.
                Bit0 set means display the '1' pencil mark, bit1 set means display the '2' pencil mark, etc.
        """
        self.label.place_forget()
        self['style'] = styles.BOX_FRAME
        self.inner_frame['style'] = styles.BOX_FRAME

        for i in range(0, 9):
            pencil_mark = self.pencil_marks[i]
            pencil_mark.show(values & (1 << i))
            pencil_mark.grid(row=pencil_mark.position[0],
                             column=pencil_mark.position[1],
                             sticky='nesw')

    def set_borders(self, color, edges='nesw'):
        """Sets the borders on this box frame.

        Args:
            color: Color of borders to set, or `None` to hide the borders.
            edges: A subset of 'nesw' for which borders to show.
        """
        for edge in self.borders.keys():
            if edge in edges:
                self.borders[edge].set_color(color)
            else:
                self.borders[edge].set_color(None)
    def initUI(self):
        """
        Function defines basic layout of whole program.
        """

        # Start instances atributes
        self.master.title("Image Compare")
        self.pack(fill=BOTH, expand=1)
        self.listOfPaths = []
        self.lenght = 0
        self.i = 0
        self.directory1 = "C:\\Plots1"
        self.directory2 = "C:\\Plots2"

        Style().configure("TFrame", background="#333")

        # Defining entrys, lables and text fields
        self.path1 = Entry(self, width=50)
        self.path1.place(x=10, y=10)

        self.path2 = Entry(self, width=50)
        self.path2.place(x=10, y=35)

        self.startFromEntry = Entry(self, width=5)
        self.startFromEntry.place(x=550, y=10)

        self.plot1PathText = Text(self, height=3, width=75)
        self.plot1PathText.place(x=620, y=670)

        self.plot2PathText = Text(self, height=3, width=75)
        self.plot2PathText.place(x=1230, y=670)

        self.lb = Listbox(self, height=15, width=100)
        self.lb.place(x=620, y=740)

        self.numberOfPlotsText = Text(self, height=1, width=5)
        self.numberOfPlotsText.place(x=790, y=10)

        self.currentPlotsText = Text(self, height=1, width=5)
        self.currentPlotsText.place(x=930, y=10)

        numberOfPlotsLabel = Label(self, text="Nuber of plots:")
        numberOfPlotsLabel.place(x=700, y=10)

        currentPlotsLabel = Label(self, text="Current plot:")
        currentPlotsLabel.place(x=850, y=10)

        # Defining buttons
        previousButton = Button(self,
                                text="Previous",
                                command=self.previousButtonFunction)
        previousButton.place(x=10, y=670)

        nextButton = Button(self, text="Next", command=self.nextButtonFunction)
        nextButton.place(x=100, y=670)

        differentButton = Button(self,
                                 text="Different",
                                 command=self.differentButtonFunction)
        differentButton.place(x=300, y=670)

        deleteButton = Button(self,
                              text="Delete",
                              command=self.deleteButtonFunction)
        deleteButton.place(x=380, y=670)

        getPathButton = Button(self,
                               text="Get Path",
                               command=self.get_filepaths)
        getPathButton.place(x=350, y=8)

        startFromButton = Button(self,
                                 text="Start From",
                                 command=self.startFromButtonFunction)
        startFromButton.place(x=600, y=8)
Esempio n. 11
0
class UnrealAirSimGUI(multiprocessing.Process):
    
    def __init__(self, dataPipe, vehicle_names):
        multiprocessing.Process.__init__(self)
        self.dataPipe = dataPipe
        self.vehicle_names = vehicle_names
        self.WIDTH = 580
        self.HEIGHT = 500
        self.update_tracking_interval = 20
        self.start()
    
    def run(self):
        
    # 1/2 Configure the Individual GUI Tabs    
        print("Start GUI Setup!")
        
        self.root = tk.Tk() # The GUI
        self.root.title("Unreal Vehicle GUI")
        self.nb = Notebook(self.root)
        
        # Add Main Tab
        self.StateFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT) # Top of Gui 
        self.nb.add(self.StateFrame, text = "Vehicle State")
        
        # Get Notebook Gridded
        self.nb.grid(row = 0, column = 0)
        
        # Configure Video Tab
        self.VideoFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.VideoFrame, text = "Video Feed")
        
        # Configure Plotting Tab
        self.PlottingFrame = Frame(self.nb, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.PlottingFrame, text = "Track n' Map")
        self.fig = plt.figure(1, figsize= (4,4))
        self.ax = Axes3D(self.fig)
        self.last_3d_viz_x_pos = 0
        self.last_3d_viz_y_pos = 0
        self.last_3d_viz_z_pos = 0
        self.ax.scatter(self.last_3d_viz_x_pos,self.last_3d_viz_y_pos,self.last_3d_viz_z_pos)
        self.canvas = FigureCanvasTkAgg(self.fig, self.PlottingFrame)
        self.canvas.get_tk_widget().grid(row = 1, column = 0)
        
        # Configure Virtual IMU Tab:
        self.embed = tk.Frame(self.root, width = self.WIDTH, height = self.HEIGHT)
        self.nb.add(self.embed, text="Virtual IMU")
        os.environ['SDL_WINDOWID'] = str(self.embed.winfo_id())  #Tell pygame's SDL window which window ID to use
        
        # Start PYGAME for IMU Visualization
        pygame.init()
        self.screen = Screen(500,500, scale=1.5)
        self.cube = Cube(40,40,40)
        # END Initialization
        self.root.update()
        
    # 2/2 Configure the Labels and Entries on the GUI    
        # For Switch Vehicle Feeds
        self.current_vehicle_feed = tk.StringVar(self.StateFrame) # Linked to current vehicle choice
        self.switch_vehicle_feed = Combobox(self.StateFrame, textvariable = self.current_vehicle_feed)
        self.switch_vehicle_feed['values'] = self.vehicle_names
        self.switch_vehicle_feed.grid(row = 0, column = 3)
        self.switch_vehicle_feed.current(0)
        
        # Labels for state variables
        self.label_posx = Label(self.StateFrame, text = "PosX:")
        self.label_posy = Label(self.StateFrame, text = "PosY:")
        self.label_posz = Label(self.StateFrame, text = "PosZ:")
        self.label_velx = Label(self.StateFrame, text = "Vel X:")
        self.label_vely = Label(self.StateFrame, text = "Vel Y:")
        self.label_velz = Label(self.StateFrame, text = "Vel Z:")
        self.label_accx = Label(self.StateFrame, text = "Acc X:")
        self.label_accy = Label(self.StateFrame, text = "Acc Y:")
        self.label_accz = Label(self.StateFrame, text = "Acc Z:")
        self.label_rollrate = Label(self.StateFrame, text = "Roll Rate:")
        self.label_pitchrate = Label(self.StateFrame, text = "Pitch Rate:")
        self.label_yawrate = Label(self.StateFrame, text = "Yaw Rate:")
        self.label_angaccx = Label(self.StateFrame, text = "AngAcc X:")
        self.label_angaccy = Label(self.StateFrame, text = "AngAcc Y:")
        self.label_angaccz = Label(self.StateFrame, text = "AngAcc Z:")
        self.label_roll = Label(self.StateFrame, text = "Roll:")
        self.label_pitch = Label(self.StateFrame, text = "Pitch:")
        self.label_yaw = Label(self.StateFrame, text = "Yaw:")        
        
        # Assemble into grid -- No need to pack if you are using grid
        self.label_posx.grid(row = 0, column = 0)
        self.label_posy.grid(row = 1, column = 0)
        self.label_posz.grid(row = 2, column = 0)
        self.label_velx.grid(row = 3, column = 0)
        self.label_vely.grid(row = 4, column = 0)
        self.label_velz.grid(row = 5, column = 0)
        self.label_accx.grid(row = 6, column = 0)
        self.label_accy.grid(row = 7, column = 0)
        self.label_accz.grid(row = 8, column = 0)
        self.label_rollrate.grid(row = 9, column = 0)
        self.label_pitchrate.grid(row = 10, column = 0)
        self.label_yawrate.grid(row = 11, column = 0)
        self.label_angaccx.grid(row = 12, column = 0)
        self.label_angaccy.grid(row = 13, column = 0)
        self.label_angaccz.grid(row = 14, column = 0)
        self.label_roll.grid(row = 15, column = 0)
        self.label_pitch.grid(row = 16, column = 0)
        self.label_yaw.grid(row = 17, column = 0)
        
        # Entries for State Updates:
        self.entry_posx = Entry(self.StateFrame, text = "PosX:")
        self.entry_posy = Entry(self.StateFrame, text = "PosY:")
        self.entry_posz = Entry(self.StateFrame, text = "PosZ:")
        self.entry_velx = Entry(self.StateFrame, text = "Vel X:")
        self.entry_vely = Entry(self.StateFrame, text = "Vel Y:")
        self.entry_velz = Entry(self.StateFrame, text = "Vel Z:")
        self.entry_accx = Entry(self.StateFrame, text = "Acc X:")
        self.entry_accy = Entry(self.StateFrame, text = "Acc Y:")
        self.entry_accz = Entry(self.StateFrame, text = "Acc Z:")
        self.entry_roll = Entry(self.StateFrame, text = "Roll:")
        self.entry_pitch = Entry(self.StateFrame, text = "Pitch:")
        self.entry_yaw = Entry(self.StateFrame, text = "Yaw:")
        self.entry_rollrate = Entry(self.StateFrame, text = "Roll Rate:")
        self.entry_pitchrate = Entry(self.StateFrame, text = "Pitch Rate:")
        self.entry_yawrate = Entry(self.StateFrame, text = "Yaw Rate:")
        self.entry_angaccx = Entry(self.StateFrame, text = "AngAcc X:")
        self.entry_angaccy = Entry(self.StateFrame, text = "AngAcc Y:")
        self.entry_angaccz = Entry(self.StateFrame, text = "AngAcc Z:")

        # Entries Gridded
        self.entry_posx.grid(row = 0, column = 1)
        self.entry_posy.grid(row = 1, column = 1)
        self.entry_posz.grid(row = 2, column = 1)
        self.entry_velx.grid(row = 3, column = 1)
        self.entry_vely.grid(row = 4, column = 1)
        self.entry_velz.grid(row = 5, column = 1)
        self.entry_accx.grid(row = 6, column = 1)
        self.entry_accy.grid(row = 7, column = 1)
        self.entry_accz.grid(row = 8, column = 1)
        self.entry_roll.grid(row = 15, column = 1)
        self.entry_pitch.grid(row = 16, column = 1)
        self.entry_yaw.grid(row = 17, column = 1)
        self.entry_rollrate.grid(row = 9, column = 1)
        self.entry_pitchrate.grid(row = 10, column = 1)
        self.entry_yawrate.grid(row = 11, column = 1)
        self.entry_angaccx.grid(row = 12, column = 1)
        self.entry_angaccy.grid(row = 13, column = 1)
        self.entry_angaccz.grid(row = 14, column = 1)
        
        # Meta Data For the State Page
        self.entry_action = Entry(self.StateFrame, text = "Action")
        self.entry_action_name = Entry(self.StateFrame, text = "Action Name")
        self.entry_env_state = Entry(self.StateFrame, text = "Env State")
        self.entry_mode = Entry(self.StateFrame, text = "GUI Mode")
        self.entry_act_time = Entry(self.StateFrame, text = "Action Time")
        self.entry_sim_image_time = Entry(self.StateFrame, text = "Sim Image Get Time")
        self.entry_sim_state_time = Entry(self.StateFrame, text = "Sim State Get Time")
        self.entry_reward_time = Entry(self.StateFrame, text = "Sim Calc Reward Time")
        self.entry_step_time = Entry(self.StateFrame, text = "Step Time")
        self.entry_reward = Entry(self.StateFrame, text = "Reward")
        self.entry_done = Entry(self.StateFrame, text = "Done Flag")
        
        
        self.label_action = Label(self.StateFrame, text = "Action:")
        self.label_action_name = Label(self.StateFrame, text = "Action Name:")
        self.label_env_state = Label(self.StateFrame, text = "Env State:")
        self.label_mode = Label(self.StateFrame, text = "GUI Mode:")
        self.label_act_time = Label(self.StateFrame, text = "Action Time:")
        self.label_sim_image_time = Label(self.StateFrame, text = "Sim Image Get Time:")
        self.label_sim_state_time = Label(self.StateFrame, text = "Sim State Get Time:")
        self.label_reward_time = Label(self.StateFrame, text = "Calc Reward Time:")
        self.label_step_time = Label(self.StateFrame, text = "Env Step Time:")
        self.label_reward = Label(self.StateFrame, text = "Reward:")
        self.label_done = Label(self.StateFrame, text = "Done:")
        
        # Grid Meta Data Display
        self.label_action.grid(row = 5, column = 2)
        self.label_action_name.grid(row = 6, column = 2)
        self.label_env_state.grid(row = 7, column = 2)
        self.label_mode.grid(row = 8, column = 2)
        self.label_act_time.grid(row = 9, column = 2)
        self.label_sim_image_time.grid(row = 10, column = 2)
        self.label_sim_state_time.grid(row = 11, column = 2)
        self.label_reward_time.grid(row = 12, column = 2)
        self.label_step_time.grid(row = 13, column = 2)
        self.label_reward.grid(row = 14, column = 2)
        self.label_done.grid(row = 15, column = 2)
        
        self.entry_action.grid(row = 5, column = 3)
        self.entry_action_name.grid(row = 6, column = 3)
        self.entry_env_state.grid(row = 7, column = 3)
        self.entry_mode.grid(row = 8, column = 3)
        self.entry_act_time.grid(row = 9, column = 3)
        self.entry_sim_image_time.grid(row = 10, column = 3)
        self.entry_sim_state_time.grid(row = 11, column = 3)
        self.entry_reward_time.grid(row = 12, column = 3)
        self.entry_step_time.grid(row = 13, column = 3)
        self.entry_reward.grid(row = 14, column = 3)
        self.entry_done.grid(row = 15, column = 3)
        
        # Initialize the Vehicle's Virtual IMU Visualization
        self.label_yaw = Label(self.embed, text = "Yaw:")
        self.label_pitch = Label(self.embed, text = "Pitch:")
        self.label_roll = Label(self.embed, text = "Roll:")
        self.label_yaw.place(x=500,y = 0) # Place the Labels on the far right of the frame
        self.label_pitch.place(x=500, y = 50)
        self.label_roll.place(x=500, y = 100)
        
        self.entry_imu_yaw = Entry(self.embed, text = "Yaw:")
        self.entry_imu_pitch = Entry(self.embed, text = "Pitch:")
        self.entry_imu_roll = Entry(self.embed, text = "Roll:")
        self.entry_yaw.place(x = 500, y = 25)
        self.entry_pitch.place(x = 500, y = 75)
        self.entry_roll.place(x = 500, y = 125)
        
        print("GUI Setup DONE!")
        t_upd = threading.Thread(target = self.updates)
        t_upd.start()
        self.root.mainloop()
        

    
    def updates(self):
        time.sleep(1.5)
        while True:
            # Data comes in as a dictionary of 'obs', 'state', 'meta'
            data = self.dataPipe.recv()
            vehicle_name = self.current_vehicle_feed.get()
            # Run the inertial update thread
            self.t_states = threading.Thread(target = self.update_inertial_states, 
                                             args = (data[vehicle_name]['state'],))
            self.t_states.start() # Start Updater thread by setting the event
            # Run the Image Data thread
            self.t_imgs = threading.Thread(target = self.update_image_feeds,
                                           args = (data[vehicle_name]['obs'],))
            self.t_imgs.start()
            # Run the meta data update
            self.t_meta = threading.Thread(target = self.update_metas,
                                            args = (data[vehicle_name]['meta'],))
            self.t_meta.start()
            
            self.t_v_imu_viz = threading.Thread(target = self.update_virtual_imu_visualization,
                                                args = (data[vehicle_name]['state'],))
            self.t_v_imu_viz.start()
            
            self.t_3d_track_viz = threading.Thread(target = self.update_object_3DVisualization, 
                                                   args = (data[vehicle_name]['state'],))
            self.t_3d_track_viz.start()
            
            # Join Threads
            self.t_states.join()
            self.t_imgs.join()
            self.t_meta.join()
            self.t_v_imu_viz.join()
            self.t_3d_track_viz.join()
            
        
    def update_metas(self, data):
        meta = data
        self.entry_action_name.delete(0,tk.END)
        self.entry_action_name.insert(0,str(meta['action_name']))
        self.entry_action.delete(0,tk.END)
        self.entry_action.insert(0,str(meta['action']))
        self.entry_env_state.delete(0,tk.END)
        self.entry_env_state.insert(0,str(meta['env_state']))
        self.entry_mode.delete(0,tk.END)
        self.entry_mode.insert(0,str(meta['mode']))
        self.entry_act_time.delete(0, tk.END)
        self.entry_act_time.insert(0, str(meta['times']['act_time']))
        self.entry_sim_image_time.delete(0,tk.END)
        self.entry_sim_image_time.insert(0,str(meta['times']['sim_img_time']))
        self.entry_sim_state_time.delete(0,tk.END)
        self.entry_sim_state_time.insert(0,str(meta['times']['sim_state_time']))
        self.entry_reward_time.delete(0,tk.END)
        self.entry_reward_time.insert(0,str(meta['times']['reward_time']))
        self.entry_step_time.delete(0, tk.END)
        self.entry_step_time.insert(0, str(meta['times']['step_time']))
        self.entry_reward.delete(0, tk.END)
        self.entry_reward.insert(0, str(meta['reward']))
        self.entry_done.delete(0, tk.END)
        self.entry_done.insert(0, str(meta['done']))

    def update_image_feeds(self, data):
        scalar = 3
        col_count = 0
        row_count = 0
        
        sim_images = data
        print("GUI Image Update:")
        start_time = time.time()
        
        for key in sim_images:
            if len(sim_images[key][0]) > 0:
                
        
        
        for i in range(self.num_video_feeds):
            sim_image = sim_images[:,:,scalar*i:scalar*(i+1)]
            if scalar == 1:
                sim_image = np.reshape(sim_image, (sim_image.shape[0], sim_image.shape[1]))
            if ((i % 3) == 0):
                col_count = 0
                row_count += 1
            #print('sim image shape ', sim_image.shape, type(sim_image), sim_image, self.isNormal)
            if self.isNormal:
                sim_image = np.array(sim_image * 255, dtype = np.uint8)
            else:
                sim_image = np.array(sim_image, dtype = np.uint8)
            img = Image.fromarray(sim_image)
            imgtk = ImageTk.PhotoImage(image = img)
            if self.VideoFeeds[i] is None: # Initialize the image panel
                self.VideoFeeds[i] = Label(self.VideoFrame, image=imgtk)
                self.VideoFeeds[i].image = imgtk
                self.VideoFeeds[i].grid(row = row_count, column = col_count)
            else:
                self.VideoFeeds[i].configure(image = imgtk)
                self.VideoFeeds[i].image = imgtk
            col_count += 1
        col_count = 0
        row_count = 0
        print("Feed Update Time: ", time.time() - start_time)
    

    
    def update_inertial_states(self, data):
            #print(current_inertial_states)
            current_inertial_state = data
            quatx, quaty, quatz, quatw = current_inertial_state[15:]
            yaw, pitch, roll = SO3Rotation.quaternion_to_euler_angles((quatw, quatx, quaty, quatz))

            print('GUI State Update!')
            start_time = time.time()
            #print(current_inertial_states, current_inertial_state)
            self.entry_posx.delete(0,tk.END)
            self.entry_posx.insert(0, str(current_inertial_state[0]))
            self.entry_posy.delete(0,tk.END)
            self.entry_posy.insert(0, str(current_inertial_state[1]))
            self.entry_posz.delete(0,tk.END)
            self.entry_posz.insert(0, str(current_inertial_state[2]))
            self.entry_velx.delete(0,tk.END)
            self.entry_velx.insert(0, str(current_inertial_state[3]))
            self.entry_vely.delete(0,tk.END)
            self.entry_vely.insert(0, str(current_inertial_state[4]))
            self.entry_velz.delete(0,tk.END)
            self.entry_velz.insert(0, str(current_inertial_state[5]))
            self.entry_accx.delete(0,tk.END)
            self.entry_accx.insert(0, str(current_inertial_state[6]))
            self.entry_accy.delete(0,tk.END)
            self.entry_accy.insert(0, str(current_inertial_state[7]))
            self.entry_accz.delete(0,tk.END)
            self.entry_accz.insert(0, str(current_inertial_state[8]))
            self.entry_roll.delete(0,tk.END)
            self.entry_roll.insert(0, str(roll))
            self.entry_pitch.delete(0,tk.END)
            self.entry_pitch.insert(0, str(pitch))
            self.entry_yaw.delete(0,tk.END)
            self.entry_yaw.insert(0, str(yaw))
            self.entry_rollrate.delete(0,tk.END)
            self.entry_rollrate.insert(0, str(current_inertial_state[9]))
            self.entry_pitchrate.delete(0,tk.END)
            self.entry_pitchrate.insert(0, str(current_inertial_state[10]))
            self.entry_yawrate.delete(0,tk.END)
            self.entry_yawrate.insert(0, str(current_inertial_state[11]))
            self.entry_angaccx.delete(0,tk.END)
            self.entry_angaccx.insert(0, str(current_inertial_state[12]))
            self.entry_angaccy.delete(0,tk.END)
            self.entry_angaccy.insert(0, str(current_inertial_state[13]))
            self.entry_angaccz.delete(0,tk.END)
            self.entry_angaccz.insert(0, str(current_inertial_state[14]))
            print('GUI State Update Time! ', time.time() - start_time)        
             

    def update_virtual_imu_visualization(self, data):

        quatx = data[15]
        quaty = data[16]
        quatz = data[17]
        quatw = data[18]
        yaw, pitch, roll = SO3Rotation.quaternion_to_euler_angles((quatw, quatx, quaty, quatz))
        self.entry_yaw.delete(0,tk.END)
        self.entry_yaw.insert(0, str(yaw))
        self.entry_pitch.delete(0,tk.END)
        self.entry_pitch.insert(0, str(pitch))
        self.entry_roll.delete(0,tk.END)
        self.entry_roll.insert(0, str(roll))
        q = Quaternion(quatw, quatx, quaty, quatz).normalized()
        self.cube.draw(self.screen,q)
        event = pygame.event.poll()
        pygame.display.flip()
        pygame.time.delay(10) # ms
        self.cube.erase(self.screen)
        #TKINTER
        self.root.update()

    def update_object_3DVisualization(self, data):
        if self.update_tracking_interval % 20 == 0:
            print("RUNNING 3D VISULIZATION")
            print(data[0], data[1], data[2])
            xpos = data[0]
            ypos = data[1]
            zpos = data[2]
            self.ax.plot3D([self.last_3d_viz_x_pos, xpos],
                           [self.last_3d_viz_y_pos,ypos],
                           zs = [self.last_3d_viz_z_pos, zpos])
            self.ax.scatter(xpos, ypos, zpos, color = 'green')
            self.canvas.draw()
            
            self.last_3d_viz_x_pos = xpos
            self.last_3d_viz_y_pos = ypos
            self.last_3d_viz_z_pos = zpos
        self.update_tracking_interval += 1
Esempio n. 12
0
class MainWindow:
    def __init__(self) -> None:
        self.Root = Tk()
        self.App = Frame(self.Root, padding=(5, 2))
        self.UpdatesFrame = LabelFrame(self.App, text='Обновление',
                                       borderwidth=2, relief='sunken', padding=(5, 2))
        self.upd_enabled = BooleanVar()  # Флаг обновлений
        self.upd_unit = StringVar()  # Единица измерения времени
        self.time_units = {Minutes: 'Минут', Hours: 'Часов',
                           Days: 'Дней', Weeks: 'Недель', Months: 'Месяцев'}
        self.size_units = {Bytes: 'Байт', KBytes: 'Кбайт', MBytes:'Мбайт',
                           GBytes:'Гбайт', TBytes:'Тбайт'}  # Список единиц измерения времени
        self.maxfsize = StringVar()  # Максимальный размер файла
        self.size_unit = StringVar()  # Единица измерения информации
        self.units_amount1 = StringVar()  # Количество единиц
        self.quar = BooleanVar()  # False - удалять, True - карантин
        self.quar_path = StringVar() # Расположение карантина
        self.rpt_enabled = BooleanVar()  # Флаг отправки отчета
        self.email = StringVar()  # Адрес отправки
        self.passwd = StringVar() # Пароль исходящего ящика
        self.rpt_unit = StringVar()  # Единица измерения времени
        self.units_amount2 = StringVar()  # Количество единиц

        self.Upd_Label1 = Label(self.UpdatesFrame, text='Проверять обновления антивирусных баз')
        self.Upd_Checkbutton1 = Checkbutton(self.UpdatesFrame, variable=self.upd_enabled)
        self.Upd_Label2 = Label(self.UpdatesFrame, text='Частота проверки:   каждые')
        self.Upd_Spinbox1 = Spinbox(self.UpdatesFrame, textvariable=self.units_amount1,
                                    from_=1, to=999999999, width=4)
        self.Upd_OptionMenu1 = OptionMenu(self.UpdatesFrame, self.upd_unit, *self.time_units.values())
        self.Upd_Button1 = Button(
            self.UpdatesFrame, text='Источники антивирусных сигнатур', command=EntryOptionsWindow('AV_SOURCES', self.Root).main)

        self.ScanFrame = LabelFrame(self.App, text='Сканирование',
                                    borderwidth=2, relief='sunken', padding=(5, 2))
        self.Scn_Label1 = Label(self.ScanFrame, text='Максимальный размер файла:')
        self.Scn_Spinbox1 = Spinbox(self.ScanFrame, textvariable=self.maxfsize,
                                    from_=0, to=999999999, width=8)

        self.Quar_Label = Label(self.ScanFrame, text='При обнаружении угрозы')
        self.Quar_RadButton1 = Radiobutton(self.ScanFrame, text='Удаление', variable=self.quar, value=False)
        self.Quar_RadButton2 = Radiobutton(self.ScanFrame, text='Карантин', variable=self.quar, value=True)

        self.Scn_OptionMenu1 = OptionMenu(self.ScanFrame, self.size_unit, *self.size_units.values())
        self.Scn_Edit_Targets = Button(self.ScanFrame, text='Цели сканирования', command=EntryOptionsWindow('SCAN_TARGETS', self.Root, select_path=True).main)
        self.Scn_Edit_Exceptions = Button(self.ScanFrame, text='Исключения', command=EntryOptionsWindow('SCAN_EXCLUDE', self.Root).main)
        self.Quar_Button1 = Button(self.ScanFrame, text='Расположение карантина',
                                   command=lambda: self.quar_path.set(filedialog.askdirectory()))

        self.ReportFrame = LabelFrame(self.App, text='Отправка отчета',
                                      borderwidth=2, relief='sunken', padding=(5, 2))

        self.Rpt_Label1 = Label(self.ReportFrame, text='Отправлять отчеты о сканировании')
        self.Rpt_Checkbutton1 = Checkbutton(self.ReportFrame, variable=self.rpt_enabled)
        self.Rpt_Label2 = Label(self.ReportFrame, text='Адрес отправки отчетов:')
        self.Rpt_Entry1 = Entry(self.ReportFrame, textvariable=self.email, width=32)
        self.Rpt_Label3 = Label(self.ReportFrame, text='Пароль:')
        self.Rpt_Entry2 = Entry(self.ReportFrame, textvariable=self.passwd, width=32, show='*')
        self.Rpt_Label4 = Label(self.ReportFrame, text='Частота:')
        self.Rpt_Spinbox1 = Spinbox(self.ReportFrame, textvariable=self.units_amount2,
                                    from_=1, to=999999999, width=4)
        self.Rpt_OptionMenu1 = OptionMenu(self.ReportFrame, self.rpt_unit, *self.time_units.values())
        self.Rpt_Button1 = Button(self.ReportFrame, text='Получатели', command=EntryOptionsWindow('SEND_TO', self.Root).main)

        self.Buttons = Frame(self.App, padding=(5, 2))
        self.Button1 = Button(self.Buttons, text='Готово', command=self.save_conf)
        self.Button2 = Button(self.Buttons, text='Отмена', command=self.Root.destroy)

    def main(self) -> None:
        self.upd_unit.set(self.time_units[type(UPDATE_FREQ)])
        self.units_amount1.set(UPDATE_FREQ.value)
        self.upd_enabled.set(CHECK_FOR_UPDATES)
        self.Upd_Checkbutton1.configure(command=(
            lambda: self.__change_state(
                self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1, self.Upd_Button1)
            and self.upd_enabled.set(not self.upd_enabled.get())))
        self.Rpt_Checkbutton1.configure(command=(
            lambda: self.__change_state(
                self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2,
                 self.Rpt_Label4, self. Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1)
                 and self.rpt_enabled.set(not self.rpt_enabled.get())))
        self.maxfsize.set(MAX_FILE_SIZE.value)
        self.size_unit.set(self.size_units[type(MAX_FILE_SIZE)])
        self.quar.set(REMOVE_THREATS)
        self.quar_path.set(QUARANTINE_PATH)
        self.rpt_enabled.set(SEND_SCAN_REPORTS)
        self.email.set(SEND_FROM)
        self.passwd.set(SEND_PASSWD)
        self.rpt_unit.set(self.time_units[type(SEND_FREQ)])
        self.units_amount2.set(SEND_FREQ.value)

        self.App.pack(fill='both', expand=True)
        center_win(self.Root, '500x500')
        self.Root.resizable(False, False)
        self.Root.title('CobraAV Configuration')

        self.UpdatesFrame.place(y=0, height=150, width=490)
        self.__change_state(self.upd_enabled, self.Upd_Label2,
                            self.Upd_Spinbox1, self.Upd_OptionMenu1)

        self.__change_state(self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3,
                            self.Rpt_Entry2, self.Rpt_Label4, self.Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1)

        self.Upd_Label1.place(relx=.01, rely=.05)  # Проверять обновления ?
        self.Upd_Checkbutton1.place(relx=.8, rely=.05)  # Да/Нет

        self.Upd_Label2.place(relx=.01, rely=.3)  # Частота проверки
        self.Upd_Spinbox1.place(relx=.55, rely=.3, width=60)  # Количество
        self.Upd_OptionMenu1.place(relx=.72, rely=.28)  # Единицы измерения
        self.Upd_Button1.place(relx=.01, rely=.65)  # Источники сигнатур

        self.ScanFrame.place(y=150, height=150, width=490)

        self.Scn_Label1.place(relx=.01, rely=.05)  # Максимальный размер файла
        self.Scn_Spinbox1.place(relx=.55, rely=.05, width=60)  # Количество

        self.Quar_Label.place(relx=.01, rely=.35)
        self.Quar_RadButton1.place(relx=.52, rely=.35)  # Переключатель на удаление угрозы
        self.Quar_RadButton2.place(relx=.72, rely=.35)  # Переключатель на добавление вкарантина угрозы
        self.Quar_Button1.place(relx=.56, rely=.65)  # Расположение карантина

        self.Scn_OptionMenu1.place(relx=.72, rely=.014)  # Единицы измерения
        self.Scn_Edit_Targets.place(relx=.01, rely=.65)  # Цели сканирования
        self.Scn_Edit_Exceptions.place(relx=.33, rely=.65)  # Исключения

        self.Rpt_Label1.place(relx=.01, rely=.05)  # Отправлять отчеты ?
        self.Rpt_Checkbutton1.place(relx=.8, rely=.05)  # Да/Нет

        self.ReportFrame.place(y=300, height=150, width=490)
        self.Rpt_Label2.place(relx=.01, rely=.35)  # Адрес отправки отчетов:
        self.Rpt_Entry1.place(relx=.35, rely=.35)  # Ввод адреса отправки отчетов
        self.Rpt_Label3.place(relx=.01, rely=.50) # Пароль:
        self.Rpt_Entry2.place(relx=.35, rely=.50) # Ввод пароля:
        self.Rpt_Label4.place(relx=.01, rely=.75)  # Частота отправки
        self.Rpt_Spinbox1.place(relx=.35, rely=.75, width=60)  # Количество
        self.Rpt_OptionMenu1.place(relx=.52, rely=.72)  # Единицы измерения
        self.Rpt_Button1.place(relx=.72, rely=.74) # Получатели

        self.Buttons.place(y=450, height=50, width=490)
        self.Button1.place(relx=.62, rely=.2) # Кнопка "Готово"
        self.Button2.place(relx=.82, rely=.2) # Кнопка "Отмена"

        self.Root.mainloop()

    @staticmethod
    def __change_state(state: BooleanVar, *args: Widget) -> None:
        for i in args:
            i.configure(state=('disabled', 'normal')[state.get()])

    def save_conf(self) -> None:
        size_units = {v: k for k, v in self.size_units.items()}
        time_units = {v: k for k, v in self.time_units.items()}

        def wrap_list(a: 'list[str]') -> str:
            return '[' + ', '.join(f"r'{i}'" for i in a) + ']'

        def wrap_cls(_unit: Variable, amount: Variable) -> str:
            unit = _unit.get()
            if unit in size_units:
                return size_units[unit].__name__ + f'({amount.get()})'
            elif unit in time_units:
                return time_units[unit].__name__ + f'({amount.get()})'
            else:
                raise NotImplementedError

        with open(CONF_PATH, 'w') as f:
            f.write(
                f"""from libunits import *

CHECK_FOR_UPDATES = {int(self.upd_enabled.get())}  # Check for updates
UPDATE_FREQ = {wrap_cls(self.upd_unit, self.units_amount1)}  # Check interval
MAX_FILE_SIZE = {wrap_cls(self.size_unit, self.maxfsize)}  # Max file size

# Antivirus database sources
AV_SOURCES = {wrap_list(AV_SOURCES)}

# Antivirus database path
DB_PATH = r'{DB_PATH}'

# On threat:
# 0 - quarantine
# 1 - remove
REMOVE_THREATS = {int(self.quar.get())}

# Directories to scan
SCAN_TARGETS = {wrap_list(SCAN_TARGETS)}

# Exclude from scanning
SCAN_EXCLUDE = {wrap_list(SCAN_EXCLUDE)}

# quarantine location
QUARANTINE_PATH = r'{self.quar_path.get() or QUARANTINE_PATH}'

# Send scan reports
SEND_SCAN_REPORTS = {int(self.rpt_enabled.get())}

# Scan reports frequency
SEND_FREQ = {wrap_cls(self.rpt_unit, self.units_amount2)}

# Send from this email
SEND_FROM = r'{self.email.get()}'

# Sender email password
SEND_PASSWD = r'{self.passwd.get()}'

# Send to these emails
SEND_TO = {wrap_list(SEND_TO)}
""")
        self.Root.destroy()
Esempio n. 13
0
class Application_ui(Frame):
    # 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title('Excel2DDLCMod')
        self.master.geometry('600x343')
        self.createWidgets()

    def createWidgets(self):
        self.top = self.winfo_toplevel()

        self.style = Style()
        self.bkg_gif = PhotoImage(data=base64.b64decode(back_ground_gif_data))
        self.background_label = Label(self.top, image=self.bkg_gif)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)

        self.Text = Text(self.top, font=('微软雅黑', 9))
        self.Text.place(relx=0.066, rely=0.07, relwidth=0.869, relheight=0.563)
        # self.Text.insert(END, "Excel2DDLCMod by DokiMod\n基于凉宫春日应援团的 Excel2RpyScript 开发\n")

        self.saveAddr = Entry(self.top, font=('微软雅黑', 9))
        self.saveAddr.place(relx=0.355,
                            rely=0.84,
                            relwidth=0.409,
                            relheight=0.052)

        self.ComboList = ['源文件目录', '自定义目录']
        self.Combo = Combobox(self.top,
                              values=self.ComboList,
                              font=('微软雅黑', 9),
                              state='readonly')
        self.Combo.place(relx=0.184,
                         rely=0.84,
                         relwidth=0.146,
                         relheight=0.058)
        self.Combo.set(self.ComboList[0])
        self.Combo.bind('<<ComboboxSelected>>', self.comboEvent)

        self.style.configure('InputButton.TButton', font=('微软雅黑', 9))
        self.InputButton = Button(self.top,
                                  text='浏览',
                                  command=self.InputButton_Cmd,
                                  style='InputButton.TButton')
        self.InputButton.place(relx=0.184,
                               rely=0.7,
                               relwidth=0.133,
                               relheight=0.073)

        self.Haruhi_gif = PhotoImage(data=base64.b64decode(haruhi_gif_data))
        self.style.configure('ConvertButton.TButton', font=('微软雅黑', 9))
        self.ConvertButton = Button(self.top,
                                    image=self.Haruhi_gif,
                                    command=self.ConvertButton_Cmd,
                                    style='ConvertButton.TButton')
        self.ConvertButton.place(relx=0.788,
                                 rely=0.7,
                                 relwidth=0.146,
                                 relheight=0.236)

        self.style.configure('OutputLabel.TLabel',
                             anchor='w',
                             font=('微软雅黑', 9))
        self.OutputLabel = Label(self.top,
                                 text='保存目录:',
                                 style='OutputLabel.TLabel')
        self.OutputLabel.place(relx=0.066,
                               rely=0.84,
                               relwidth=0.107,
                               relheight=0.05)

        self.style.configure('InputLabel.TLabel', anchor='w', font=('微软雅黑', 9))
        self.InputLabel = Label(self.top,
                                text='输入设置:',
                                style='InputLabel.TLabel')
        self.InputLabel.place(relx=0.066,
                              rely=0.723,
                              relwidth=0.107,
                              relheight=0.05)

        menubar = Menu(self.top)
        filemenu = Menu(menubar, tearoff=0)  # tearoff意为下拉
        moremenu = Menu(menubar, tearoff=0)  # tearoff意为下拉
        menubar.add_cascade(label='帮助', menu=filemenu)
        filemenu.add_command(label='视频教程', command=self.open_help_url)
        filemenu.add_command(label='检查更新', command=self.check_for_update)
        menubar.add_cascade(label='更多', menu=moremenu)
        moremenu.add_command(label='关于 Excel2DDLCMod', command=self.open_about)
        moremenu.add_command(label='DokiMod 官网', command=self.open_dokimod)

        self.top.config(menu=menubar)
Esempio n. 14
0
    def initUI(self):
        self.title("Feedback..")
        self.geometry("600x400")
        self.style = Style()
        self.style.theme_use("default")  # default
        xpos = 40
        ypos = 30
        xpos2 = xpos + 100
        l1 = Label(self,
                   text="First Name",
                   foreground="#ff0000",
                   background="light blue",
                   font="Arial 9")  # Arial 12 bold italic
        l1.place(x=xpos, y=ypos)
        self.txtFirstName = Entry(self)
        self.txtFirstName.place(x=xpos2, y=ypos, width=70)

        ypos += 30
        l2 = Label(self,
                   text="Email",
                   foreground="#ff0000",
                   background="light blue",
                   font="Arial 9")  # Arial 12 bold italic
        l2.place(x=xpos, y=ypos)
        self.txtEmail = Entry(self)
        self.txtEmail.place(x=xpos2, y=ypos)

        ypos += 30
        l3 = Label(self,
                   text="Your interest in type of our products:",
                   foreground="#ff0000",
                   background="light blue",
                   font="Arial 9")  # Arial 12 bold italic
        l3.place(x=xpos, y=ypos)

        ypos += 30
        self.electronicsChoice = BooleanVar()
        self.electronicsChoice.set(True)
        self.chkElectronics = Checkbutton(self,
                                          text="Electronics",
                                          variable=self.electronicsChoice)

        self.chkElectronics.place(x=xpos2, y=ypos)

        self.sportsChoice = BooleanVar()
        self.chkSports = Checkbutton(self,
                                     text="Sports",
                                     variable=self.sportsChoice)
        self.chkSports.place(x=xpos2 + 80, y=ypos)

        self.gardeningChoice = StringVar()
        self.gardeningChoice.set("YES")
        self.chkGardening = Checkbutton(self,
                                        text="Gardening",
                                        variable=self.gardeningChoice,
                                        onvalue="YES",
                                        offvalue="NO")
        self.chkGardening.place(x=xpos2 + 160, y=ypos)

        #----------radio buttons---------------
        serviceChoices = [("Disappointed", "0"), ("Satisfied", "1"),
                          ("Good", "2"), ("Excellent", "3")]
        self.serviceFeedback = StringVar()
        self.serviceFeedback.set("2")  # initial value
        inc = 0
        for text, val in serviceChoices:
            radBtn = Radiobutton(self,
                                 text=text,
                                 variable=self.serviceFeedback,
                                 value=val)
        radBtn.place(x=xpos2 + inc, y=ypos)
        inc += 100

        ypos += 30
        #--------listbox-----------
        states = [("Connecticut", "0"), ("New York", "1"), ("New Jersey", "2"),
                  ("Massachussetts", "3")]
        self.lb = Listbox(self, selectmode=EXTENDED, height=len(states))
        self.lb.place(x=xpos2, y=ypos)
        self.lb.delete(0, END)  # clear
        for key, val in states:
            self.lb.insert(END, key)
        self.data = val

        #---------------------------
        ypos += 80
        #--------drop down listbox-----------
        #departments = [("Sales","100"),("Marketing","200"), ("HR","300"),("Technology","300")]
        departments = ["Sales", "Marketing", "HR", "Technology"]
        self.dept = StringVar()
        self.dept.set("HR")  # initial value
        #self.ddlDept = OptionMenu(self, self.dept,*(dict(departments).keys()))
        self.ddlDept = OptionMenu(self, self.dept, *departments)
        self.ddlDept.place(x=xpos2, y=ypos)
        #---------------------------

        ypos += 30 * (len(states) - 1)
        style = Style()
        style.configure("Exit.TButton", foreground="red", background="white")
        #T.Checkbutton for checboxes
        style.configure("MainButton.TButton",
                        foreground="yellow",
                        background="red")

        btnSubmit = Button(self, text="Submit", command=self.btnSubmitClick)
        btnSubmit.configure(style="MainButton.TButton")
        btnSubmit.place(x=xpos2, y=ypos)
Esempio n. 15
0
def imu_visualization():
    #TKINTER setup
    root = tk.Tk()
    root.title = 'Imu visualization'
    nb = Notebook(root)
    #Grid the notebook
    nb.grid(row = 0, column = 0)
    
    #initialize the frame
    embed = tk.Frame(root, width=580, height = 500)
    #if the notebook is grided, no need to pack, if not, use the following one line of code
    #embed.pack()

    nb.add(embed, text="imuviz tab")

    



    #Tell pygame's SDL window which window ID to use
    os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
    #show the window so it's assigned an ID
    root.update()

    label_yaw = Label(embed, text = "Yaw:")
    label_pitch = Label(embed, text = "Pitch:")
    label_roll = Label(embed, text = "Roll:")

    label_yaw.place(x=500,y = 0)
    label_pitch.place(x=500, y = 50)
    label_roll.place(x=500, y = 100)

    entry_yaw = Entry(embed, text = "Yaw:")
    entry_pitch = Entry(embed, text = "Pitch:")
    entry_roll = Entry(embed, text = "Roll:")

    entry_yaw.place(x = 500, y = 25)
    entry_pitch.place(x = 500, y = 75)
    entry_roll.place(x = 500, y = 125)

    #PYGAME
    pygame.init()
    screen = Screen(500,500,scale=1.5)
    cube = Cube(40,30,60)
    
    # test the ponycube
    q = Quaternion(1,0,0,0)
    incr = Quaternion(0.96,0.01,0.01,0).normalized()

    #initialize client
    imuc = IMUTCPClient.IMUTCPClient()
    
    while True:
        #recieve IMU data
        control = imuc.recv_imu_update() 
        if control is not None: 
            print(control) 
            
            entry_yaw.delete(0,tk.END)
            entry_yaw.insert(0, str(control["yaw"]))
            entry_pitch.delete(0,tk.END)
            entry_pitch.insert(0, str(control["pitch"]))
            entry_roll.delete(0,tk.END)
            entry_roll.insert(0, str(control["roll"]))
             
            # #test the entry using random numbers
            # entry_yaw.delete(0,tk.END)
            # entry_yaw.insert(0, str(round(numpy.random.randn(),6)))
            # entry_pitch.delete(0,tk.END)
            # entry_pitch.insert(0, str(round(numpy.random.randn(),6)))
            # entry_roll.delete(0,tk.END)
            # entry_roll.insert(0, str(round(numpy.random.randn(),6)))
            
            q = Quaternion(control["quatW"], control["quatX"], control["quatY"], control["quatZ"]).normalized()

            # #test the ponycube
            # q = q * incr

            cube.draw(screen,q)
            event = pygame.event.poll()
            pygame.display.flip()
            pygame.time.delay(50) 
            cube.erase(screen)
            #TKINTER
            root.update()
Esempio n. 16
0
    def centerWindow(self):
        w = 520
        h = 250

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

        variants = {
            'D-Link': [
                'DES 1100-06', 'DES 1100-10', 'DES 1210-28', 'DES 1210-52',
                'DES 3528', 'DES 3552', 'DGS 1100-06', 'DGS 1100-10',
                'DGS 1210-28', 'DGS 1210-52'
            ],
            'Huawei': ['Quidway S2326TP-EI', 'Quidway S2352P-EI'],
            'Cisco': ['C3750']
        }

        def change_depend(variant):
            sub_variants = variants[variant]
            combo_depend["values"] = sub_variants
            combo_depend.current(0)

        labelTop = Label(self, text="Выберите устройство:")
        labelTop.place(x=10, y=5)

        label_vendor = Label(self, text="Фирма:")
        label_vendor.place(x=10, y=30)

        label_model = Label(self, text="Модель:")
        label_model.place(x=10, y=55)

        combo_main = ttk.Combobox(self,
                                  values=list(variants.keys()),
                                  state="readonly")
        combo_depend = ttk.Combobox(self, values=[], state="readonly")

        combo_main.place(x=80, y=30)
        combo_depend.place(x=80, y=55)

        combo_main.bind("<<ComboboxSelected>>",
                        lambda event: change_depend(combo_main.get()))

        label_ip_address = Label(self, text="ip-address:")  # ip-address:
        label_ip_address.place(x=290, y=30)

        ip_address = Entry(
            self,
            bg='white',
        )  # Поле для ввода "ip-адреса"
        ip_address.place(x=360, y=30)

        label_switch_name = Label(self, text="switch name:")  # switch name:
        label_switch_name.place(x=278, y=60)

        switch_name = Entry(self,
                            bg='white')  # Поле для ввода "имени коммутатора"
        switch_name.place(x=360, y=60)

        label_switch_name = Label(self, text="manager vlan:")  # manager vlan:
        label_switch_name.place(x=273, y=90)

        manager_vlan = Entry(self,
                             bg='white')  # Поле для ввода "менеджер влана"
        manager_vlan.place(x=360, y=90)

        label_switch_name = Label(self,
                                  text="untagged vlan:")  # untagged vlan:
        label_switch_name.place(x=269, y=120)

        untagged_vlan = Entry(self,
                              bg='white')  # Поле для ввода "влана в антагете"
        untagged_vlan.place(x=360, y=120)

        label_switch_name = Label(self, text="tagged vlan:")  # tagged vlan:
        label_switch_name.place(x=283, y=150)

        tagged_vlan = Entry(self,
                            bg='white')  # Поле для ввода "вланов в таггете"
        tagged_vlan.place(x=360, y=150)

        def save_config():
            if combo_depend.get() == 'DES 1100-06':
                import switch_config.des_1100_06
                switch_config.des_1100_06.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.des_1100_06.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DES 1100-10':
                import switch_config.des_1100_10
                switch_config.des_1100_10.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.des_1100_10.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DES 1210-28':
                import switch_config.des_1210_28
                switch_config.des_1210_28.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.des_1210_28.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DES 1210-52':
                import switch_config.des_1210_52
                switch_config.des_1210_52.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.des_1210_52.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DES 3528':
                import switch_config.des_3528
                switch_config.des_3528.conf(str(ip_address.get()),
                                            str(switch_name.get()),
                                            str(manager_vlan.get()),
                                            str(untagged_vlan.get()),
                                            str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.des_3528.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DES 3552':
                import switch_config.des_3552
                switch_config.des_3552.conf(str(ip_address.get()),
                                            str(switch_name.get()),
                                            str(manager_vlan.get()),
                                            str(untagged_vlan.get()),
                                            str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.des_3552.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DGS 1100-06':
                import switch_config.dgs_1100_06
                switch_config.dgs_1100_06.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.dgs_1100_06.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DGS 1100-10':
                import switch_config.dgs_1100_10
                switch_config.dgs_1100_10.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.dgs_1100_10.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DGS 1210-28':
                import switch_config.dgs_1210_28
                switch_config.dgs_1210_28.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.dgs_1210_28.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'DGS 1210-52':
                import switch_config.dgs_1210_52
                switch_config.dgs_1210_52.conf(str(ip_address.get()),
                                               str(switch_name.get()),
                                               str(manager_vlan.get()),
                                               str(untagged_vlan.get()),
                                               str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.dgs_1210_52.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 's2336tp':
                import switch_config.s2326tp
                switch_config.s2326tp.conf(str(ip_address.get()),
                                           str(switch_name.get()),
                                           str(manager_vlan.get()),
                                           str(untagged_vlan.get()),
                                           str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.s2326tp.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 's2352p':
                import switch_config.s2352p
                switch_config.s2352p.conf(str(ip_address.get()),
                                          str(switch_name.get()),
                                          str(manager_vlan.get()),
                                          str(untagged_vlan.get()),
                                          str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.s2352p.config2
                f.write(s)
                f.close()

            elif combo_depend.get() == 'c3750':
                import switch_config.c3750
                switch_config.c3750.conf(str(ip_address.get()),
                                         str(switch_name.get()),
                                         str(manager_vlan.get()),
                                         str(untagged_vlan.get()),
                                         str(tagged_vlan.get()))
                file_name = fd.asksaveasfilename()
                file_txt = str(file_name) + '.txt'
                f = open(file_txt, 'w')
                s = switch_config.c3750.config2
                f.write(s)
                f.close()

        # Кнопка Сбора конфига
        btn = Button(self,
                     width=18,
                     height=2,
                     text="Сохранить конфиг",
                     command=save_config,
                     relief=GROOVE)
        btn.place(x=180, y=195)
root.title("Hebrew Handwriting Recognition")

# window size is max
root.state('zoomed')
root.resizable(False, False)

#button style
s = Style()
s.configure('my.TButton', font=('Helvetica', 12))

#window canvas design
C = Canvas(root, bg="blue", height=250, width=300)
filename = Image.open("back_img.jpg")
filename = ImageTk.PhotoImage(filename)
background_label = Label(root, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

lbl_output = tk.Label(root, text=": פלט (טקסט מוקלד)", font=("Helvetica", 14))
lbl_output.place(x=700, y=68, anchor=NE)

# text area for the output text
area = Text(root,
            height=30.1,
            width=67,
            font='david',
            borderwidth=0.5,
            relief="solid")
area.tag_configure('tag-right', justify='right')
area.place(x=400, y=400, anchor="center")
Esempio n. 18
0
class Application(object):

    # name = tk.StringVar()
    # pwd = tk.StringVar()

    def __init__(self, master):
        self.master = master
        self.topFrame = Frame(master, height=200, bg="white")
        self.topFrame.pack(fill=X)
        self.bottomFrame = Frame(master, height=600, bg="#f0eec5")
        self.bottomFrame.pack(fill=X)
        self.label1 = Label(self.topFrame,
                            text=" TRAFFIC MANAGEMENT SYSTEM",
                            font="BodoniMTBlack 40 bold",
                            bg="white",
                            fg="blue")
        self.label1.place(x=350, y=70)

        self.name = Label(self.bottomFrame,
                          text="NAME: ",
                          font="arial 11 bold",
                          bg="#f0eec5",
                          fg="black")
        self.name.place(x=550, y=210)
        self.password = Label(self.bottomFrame,
                              text="PASSWORD:"******"arial 11 bold",
                              bg="#f0eec5",
                              fg="black")
        self.password.place(x=550, y=240)
        image = Image.open('picture.png')
        image = image.resize((150, 150), Image.ANTIALIAS)
        img_pro = ImageTk.PhotoImage(image)
        self.label_pic = Label(self.bottomFrame,
                               image=img_pro,
                               background="#f0eec5")
        self.label_pic.image = img_pro
        self.label_pic.place(x=630, y=10)
        self.name1 = tk.StringVar(master)
        self.pwd1 = tk.StringVar(master)
        self.entry_name = Entry(self.bottomFrame, textvariable=self.name1)

        self.entry_name.place(x=650, y=210, width=120, height=20)
        # print(self.entry_name.get())

        self.entry_pwd = Entry(self.bottomFrame,
                               show="*",
                               width=120,
                               textvariable=self.pwd1)
        self.entry_pwd.place(x=650, y=240, width=120, height=20)

        self.button_register = Button(self.bottomFrame,
                                      text="ENTER",
                                      font="arial 16 bold ",
                                      fg="red",
                                      command=self.getThere)
        self.button_register.place(x=660, y=300)

    def getThere(self):
        if self.name1.get() != userId or self.pwd1.get() != password:
            tkinter.messagebox.showinfo(
                "Window Title",
                "Wrong Username or Password Entered.Can't Proceed Further")
        else:
            there = Traffic()
Esempio n. 19
0
    def __init__(self, master, font_dict=None, text='AaBbYyZz', title='Font', **kwargs):

        Toplevel.__init__(self, master, **kwargs)
        self.title(title)

        try:
            self.wm_iconbitmap('transparent.ico')
        except TclError:
            pass

        self.resizable(False, False)
        self.protocol('WM_DELETE_WINDOW', self.quit)
        self._validate_family = self.register(self.validate_font_family)
        self._validate_size = self.register(self.validate_font_size)

        # --- variable storing the chosen font
        self.res = ''

        style = Style(self)
        style.configure('prev.TLabel')
        bg = style.lookup('TLabel', 'background')
        self.configure(bg=bg)

        # --- family list
        self.fonts = list(set(families()))
        self.fonts.append('TkDefaultFont')
        self.fonts.sort()
        for i in range(len(self.fonts)):
            self.fonts[i] = self.fonts[i].replace(' ', '\\ ')
        max_length = int(2.5 * max([len(font) for font in self.fonts])) // 3 - 2
        self.sizes = ['%i' % i for i in (list(range(6, 17)) + list(range(18, 32, 2)) + list(range(36, 48, 4)))]
        # --- font default
        font_dict['weight'] = font_dict.get('weight', 'normal')
        font_dict['slant'] = font_dict.get('slant', 'roman')
        font_dict['underline'] = font_dict.get('underline', False)
        font_dict['overstrike'] = font_dict.get('overstrike', False)
        font_dict['family'] = font_dict.get('family', self.fonts[0].replace('\\ ', ' '))
        font_dict['size'] = font_dict.get('size', 10)

        # --- format list
        self.formats = ['Regular', 'Italic', 'Bold', 'Bold Italic']

        # --- creation of the widgets
        self.font_family = StringVar(self, ' '.join(self.fonts))
        self.font_size = StringVar(self, ' '.join(self.sizes))
        self.format_type = StringVar(self, self.formats)
        self.var_bold = BooleanVar(self, font_dict['weight'] == 'bold')
        self.var_italic = BooleanVar(self, font_dict['slant'] == 'italic')

        # ------ Size and family
        self.var_size = StringVar(self)
        self.entry_family = Entry(self, width=max_length, validate='key',
                                  validatecommand=(self._validate_family, '%d', '%S',
                                                   '%i', '%s', '%V'))
        self.entry_size = Entry(self, width=8, validate='key',
                                textvariable=self.var_size,
                                validatecommand=(self._validate_size, '%d', '%P', '%V'))

        self.entry_format = Entry(self)

        self.list_family = Listbox(self, selectmode='browse',
                                   listvariable=self.font_family,
                                   highlightthickness=0,
                                   exportselection=False,
                                   width=max_length,
                                   height=6)
        self.list_size = Listbox(self, selectmode='browse',
                                 listvariable=self.font_size,
                                 highlightthickness=0,
                                 exportselection=False,
                                 width=6,
                                 height=6)
        self.list_format = Listbox(self, selectmode='browse',
                                   listvariable=self.format_type,
                                   highlightthickness=0,
                                   exportselection=False,
                                   width=12,
                                   height=6)
        self.scroll_family = Scrollbar(self, orient='vertical',
                                       command=self.list_family.yview)
        self.scroll_size = Scrollbar(self, orient='vertical',
                                     command=self.list_size.yview)
        self.scroll_format = Scrollbar(self, orient='vertical',
                                       command=self.list_format.yview)
        self.family_label = Label(self, text='Font:')
        self.style_label = Label(self, text='Font style:')
        self.size_label = Label(self, text='Size:')

        self.script_label = Label(self, text='Script:')
        self.script_box = Combobox(self, values=['Western'])

        self.more_fonts_label = Lbl(self, text='Show more fonts', underline=1, fg='blue', cursor='hand2')
        f = Font(self.more_fonts_label, self.more_fonts_label.cget("font"))
        f.configure(underline=True)
        self.more_fonts_label.configure(font=f)

        self.preview_font = Font(self, **font_dict)
        if len(text) > 30:
            text = text[:30]
        self.preview_window = LabelFrame(self, relief='groove', text='Sample', bd=1)

        # --- widget configuration
        self.list_family.configure(yscrollcommand=self.scroll_family.set)
        self.list_size.configure(yscrollcommand=self.scroll_size.set)
        self.list_format.configure(yscrollcommand=self.scroll_format.set)

        self.entry_family.insert(0, font_dict['family'])
        self.entry_family.selection_clear()
        self.entry_family.icursor('end')
        self.entry_format.insert(0, self.formats[1])
        self.entry_format.selection_clear()
        self.entry_format.icursor('end')
        self.entry_size.insert(0, font_dict['size'])

        try:
            i = self.fonts.index(self.entry_family.get().replace(' ', '\\ '))
        except ValueError:
            # unknown font
            i = 0
        self.list_family.selection_clear(0, 'end')
        self.list_family.selection_set(i)
        self.list_family.see(i)
        try:
            i = self.sizes.index(self.entry_size.get())
            self.list_size.selection_clear(0, 'end')
            self.list_size.selection_set(i)
            self.list_size.see(i)
        except ValueError:
            # size not in listtsg
            pass

        # font family location config
        self.family_label.grid(row=0, column=0, sticky='nsew', pady=(10, 1), padx=(10, 1))
        self.entry_family.grid(row=1, column=0, sticky='nsew', pady=(1, 1), padx=(10, 0), columnspan=2)
        self.list_family.grid(row=2, column=0, sticky='nsew', pady=(1, 10), padx=(10, 0))
        self.scroll_family.grid(row=2, column=1, sticky='ns', pady=(1, 10))

        # font style/format location config
        self.style_label.grid(row=0, column=2, sticky='nsew', pady=(10, 1), padx=(15, 1))
        self.entry_format.grid(row=1, column=2, sticky='nsew', pady=(1, 1), padx=(15, 0), columnspan=2)
        self.list_format.grid(row=2, column=2, sticky='nsew', pady=(1, 10), padx=(15, 0))
        self.scroll_format.grid(row=2, column=3, sticky='ns', pady=(1, 10))

        # font size location config
        self.size_label.grid(row=0, column=4, sticky='nsew', pady=(10, 1), padx=(15, 1))
        self.entry_size.grid(row=1, column=4, sticky='nsew', pady=(1, 1), padx=(15, 10), columnspan=2)
        self.list_size.grid(row=2, column=4, sticky='nsew', pady=(1, 10), padx=(15, 0))
        self.scroll_size.grid(row=2, column=5, sticky='nsew', pady=(1, 10), padx=(0, 10))

        # font preview location config
        self.preview_window.grid(row=4, column=2, columnspan=4, sticky='nsew', rowspan=2, padx=15, pady=(0, 10),
                                 ipadx=10, ipady=10)
        self.preview_window.config(height=75)
        preview = Label(self.preview_window, text=text, font=self.preview_font, anchor='center')
        preview.place(relx=0.5, rely=0.5, anchor='center')

        self.script_label.grid(row=6, column=2, sticky='nsw', padx=(15, 0))
        self.script_box.grid(row=7, column=2, sticky='nsw', pady=(1, 30), padx=(15, 0))
        self.script_box.current(0)

        self.more_fonts_label.grid(row=8, column=0, pady=(35, 20), padx=(15, 0), sticky='nsw')

        button_frame = Frame(self)
        button_frame.grid(row=9, column=2, columnspan=4, pady=(0, 10), padx=(10, 0))

        Button(button_frame, text='Ok', command=self.ok).grid(row=0, column=0, padx=4, sticky='ew')
        Button(button_frame, text='Cancel', command=self.quit).grid(row=0, column=1, padx=4, sticky='ew')

        self.list_family.bind('<<ListboxSelect>>', self.update_entry_family)
        self.list_format.bind('<<ListboxSelect>>', self.update_entry_format)
        self.list_size.bind('<<ListboxSelect>>', self.update_entry_size, add=True)
        self.list_family.bind('<KeyPress>', self.keypress)
        self.entry_family.bind('<Return>', self.change_font_family)
        self.entry_family.bind('<Tab>', self.tab)
        self.entry_size.bind('<Return>', self.change_font_size)
        self.more_fonts_label.bind('<Button-1>', search_fonts)

        self.entry_family.bind('<Down>', self.down_family)
        self.entry_size.bind('<Down>', self.down_size)
        self.entry_family.bind('<Up>', self.up_family)
        self.entry_size.bind('<Up>', self.up_size)
        self.bind_class('TEntry', '<Control-a>', self.select_all)

        self.wait_visibility(self)
        self.grab_set()
        self.entry_family.focus_set()
        self.lift()
Esempio n. 20
0
Frame1.configure(borderwidth="2")
Frame1.configure(relief=GROOVE)
Frame1.configure(width=285)

Checkbutton1 = Checkbutton(Frame1)
Checkbutton1.place(relx=0.07, rely=0.43, relheight=0.22, relwidth=0.34)
Checkbutton1.configure(text='''Profile photo''')
Checkbutton1.configure(variable=check1)

Checkbutton3 = Checkbutton(Frame1)
Checkbutton3.place(relx=0.07, rely=0.7, relheight=0.22, relwidth=0.35)
Checkbutton3.configure(text='''Header photo''')
Checkbutton3.configure(variable=check2)

Label1 = Label(Frame1)
Label1.place(relx=0.04, rely=-0.04)
Label1.configure(text='''Upload''')

Button1 = Button(Frame1)
Button1.place(relx=0.74, rely=0.7, height=25, width=60)
Button1.configure(padding=(2, 0, 0, 0))
Button1.configure(text='''Upload''')
Button1.configure(command=up)

TCombobox1 = Combobox(Frame1)
TCombobox1.place(relx=0.09, rely=0.22, relheight=0.18, relwidth=0.61)
TCombobox1.configure(textvariable=combobox1)
TCombobox1.configure(width=173)
TCombobox1.configure(takefocus="")
TCombobox1.configure(state="readonly")
TCombobox1['values'] = photos
Esempio n. 21
0
import tkinter.messagebox
from tkinter import *
from tkinter.ttk import Frame, Label, Entry
from sintactico import *
from funciones_extra import *
from lexico import *
from sintactico import errors_list as e_l
from lexico import errors_list_lex as e_l2
import time
root = Tk()
root.geometry("1200x750")
var = StringVar()
label1 = Label(root, textvariable=var, relief=RAISED)
var.set("PROGRAMA 1")
label1.place(x=60, y=40, height=30, width=400)
text1 = Text(root)
text1.pack(padx=10, side=LEFT)
text1.place(x=60, y=80, height=300, width=400)
var2 = StringVar()
label2 = Label(root, textvariable=var2, relief=RAISED)
var2.set("PROGRAMA 2")
label2.place(x=60, y=400, height=30, width=400)
text2 = Text(root)
text2.pack(padx=0, side=LEFT)
text2.place(x=60, y=440, height=300, width=400)
var3 = StringVar()
label3 = Label(root, textvariable=var3, relief=RAISED)
var3.set("ANALISIS")
label3.place(x=700, y=40, height=30, width=400)
resul = Text(root, state='disabled')
resul.pack(padx=10, side=LEFT)
Esempio n. 22
0
class Example(Frame):
    img = cv2.imread("1.jpg", cv2.IMREAD_UNCHANGED)

    def __init__(self, parent, **kw):
        Frame.__init__(self, parent)
        super().__init__(**kw)
        # size of window
        parent.minsize(width=700, height=650)
        # define theme as default
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        # use parent to save a window
        self.parent = parent
        self.parent.title("ĐỒ ÁN TỐT NGHIỆP")
        myFont = font.Font(family='Helvetica', size=9, weight='bold')
        # create Label
        self.Label = Label(
            self,
            text="NHẬN DẠNG KÝ TỰ VIẾT TAY DÙNG MẠNG NƠ-RON NHÂN TẠO",
            font=('TimesBold', 15))
        self.Label.place(x=60, y=10)
        self.Label = self.Label.config(fg='red')
        self.Label = Label(self, text="Ký tự nhận dạng", font=myFont)
        self.Label.place(x=410, y=80)
        self.Label = self.Label.config(fg='red')
        self.Label = Label(self,
                           text="Nguyễn Thanh Tuyết Hân",
                           font=('Times13'))
        self.Label.place(x=445, y=560)
        self.Label = Label(self, text="Cao Văn Cảnh", font='Times13')
        self.Label.place(x=445, y=585)
        # create Button
        self.Button = Button(self,
                             text="Chọn ảnh",
                             font=myFont,
                             command=self.open_img,
                             height=1,
                             width=10)
        self.Button.place(x=20, y=50)
        self.Button = Button(self,
                             text="Mở camera",
                             font=myFont,
                             command=self.video,
                             height=1,
                             width=10)
        self.Button.place(x=120, y=50)
        self.Button = Button(self,
                             text="Chụp ảnh",
                             font=myFont,
                             command=self.snapshot,
                             height=1,
                             width=10)
        self.Button.place(x=210, y=50)
        self.Button = Button(self,
                             text="Nhận dạng",
                             font=myFont,
                             command=self.reg,
                             height=1,
                             width=10)
        self.Button.place(x=310, y=50)
        self.Button = Button(self,
                             text="Lưu",
                             font=myFont,
                             command=self.save_as_file,
                             height=1,
                             width=10)
        self.Button.place(x=608, y=50)
        self.Button = Button(self,
                             text="Xóa",
                             font=myFont,
                             command=self.clear,
                             height=1,
                             width=10)
        self.Button.place(x=518, y=50)
        # create text to show result
        self.Text = Text(root, height=10, width=12, font=('TimesBold', 30))
        self.Text.place(x=410, y=100)

    def clear(self):
        textsave = self.Text.delete(1.0, END)

    def save_as_file(self):
        f = filedialog.asksaveasfile(mode='w',
                                     defaultextension=".txt",
                                     filetypes=[("Text files", ".txt"),
                                                ("Word files", ".doc")],
                                     initialdir="dir",
                                     title="ĐỒ ÁN TỐT NGHIỆP")
        if f is None:
            return
        textsave = self.Text.get(1.0, END)
        f.write(textsave)
        f.close()

    def open_img(self):
        global result
        # choose and save image path
        file = filedialog.askopenfile(parent=self,
                                      mode='rb',
                                      title='Choose a file')
        path = file.name
        # Resize image
        self.img = Image.open(path)
        self.img = self.img.resize((360, 270), Image.ANTIALIAS)  # Resize
        self.img = ImageTk.PhotoImage(self.img)
        # Create a label to show image
        self.label = Label(image=self.img)
        self.label.place(x=20, y=370)
        result = cv2.imread(path, 1)

    def video(self, video_source=0):
        self.video_source = video_source
        self.vid = MyVideoCapture(self.video_source)
        ret, frame = self.vid.get_frame()
        resized = cv2.resize(frame, (360, 270), interpolation=cv2.INTER_AREA)
        if ret:
            self.canvas = tkinter.Canvas(self, width=360, height=270)
            self.canvas.place(x=20, y=100)
            self.photo = PIL.ImageTk.PhotoImage(
                image=PIL.Image.fromarray(resized))
            self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
        self.delay = 25
        self.update()

    def snapshot(self):
        # Get a frame from the video source
        global result
        ret, frame = self.vid.get_frame()
        if ret:
            cv2.imwrite("frame.jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
            self.img = Image.open("frame.jpg")
            self.img = self.img.resize((360, 270), Image.ANTIALIAS)  # Resize
            self.img = ImageTk.PhotoImage(self.img)
            # Create a label to show image
            self.label = Label(image=self.img)
            self.label.place(x=20, y=370)
        result = cv2.imread("frame.jpg", 1)

    def reg(self):
        def prepare(filepath):
            IMG_SIZE = 28
            img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
            new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
            inverted_image = 255 - new_array
            inverted_image = inverted_image / 255
            return inverted_image.reshape(1, IMG_SIZE, IMG_SIZE,
                                          1)  # convolutional neural network

        # image detection
        gray = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        ret, threshFilled = cv2.threshold(
            blurred, 130, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
        # dilation
        kernel = np.ones((5, 1), np.uint8)
        img_dilation = cv2.dilate(threshFilled, kernel, iterations=1)
        # find contours
        ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL,
                                      cv2.CHAIN_APPROX_SIMPLE)
        # sort contours
        sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
        sentence = " "
        # self.Text.insert(1.0, '\n')
        for i, ctrs in enumerate(sorted_ctrs):
            # Get bounding box
            x, y, w, h = cv2.boundingRect(ctrs)
            # Getting ROI
            roi = img_dilation[y - 3:y + h + 3, x - 3:x + w + 3]
            # roi = img_dilation[y :y + h , x :x + w ]

            ret, thresh1 = cv2.threshold(
                roi, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
            if (w > 15 and h > 15) or (w > 28 and h > 28):
                resized = cv2.resize(thresh1, (28, 28),
                                     interpolation=cv2.INTER_NEAREST)
                cv2.imwrite('i.jpg'.format(i), resized)
                cv2.imwrite('result/{}.jpg'.format(i), resized)
                predictions = new_model.predict(prepare("i.jpg"))
                sentence = sentence + str(CATEGORIES[np.argmax(predictions)])
        self.Text.insert(END, sentence)

    def update(self):
        ret, frame = self.vid.get_frame()  # Get a frame from the video source
        resized = cv2.resize(frame, (360, 270), interpolation=cv2.INTER_AREA)
        if ret:
            self.canvas = tkinter.Canvas(self, width=360, height=270)
            self.canvas.place(x=20, y=100)
            self.photo = PIL.ImageTk.PhotoImage(
                image=PIL.Image.fromarray(resized))
            self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
        self.parent.after(self.delay, self.update)
Esempio n. 23
0
class Box(Frame): # pylint: disable=too-many-ancestors
    """Represents a single box (of 0-9) in the sudoku board."""
    _counter = 0

    def __init__(self, master):
        """Construct a Box frame with parent master.

        Args:
            master: The parent frame.
        """
        Frame.__init__(self, master, style=styles.BOX_FRAME)
        self.position = (0, 0)
        self.binding_tag = 'BoxFrame' + str(Box._counter)
        self.number_text = StringVar(self, '')
        Box._counter += 1

        self.borders = dict()
        for edge in 'nesw':
            self.borders[edge] = Border(self, edge)

        self.inner_frame = Frame(self, width=30, height=30, style=styles.BOX_FRAME)
        self.pencil_marks = _build_3x3_grid(self.inner_frame, Pencil)

        self.label = Label(self.inner_frame, textvariable=self.number_text, style=styles.NUMBER_LABEL)

        _tag_widget(self, self.binding_tag)
        _tag_widget(self.inner_frame, self.binding_tag)
        _tag_widget(self.label, self.binding_tag)
        for mark in self.pencil_marks:
            _tag_widget(mark, self.binding_tag)
            _tag_widget(mark.label, self.binding_tag)

    def place_at_position(self, position):
        """Places this frame in its parent at the given position.

        Args:
            position: Tuple of (x, y) for the position to place at.
            parent_position: Tuple of (x, y) for the position the parent is in relative to the grandparent.
        """
        row = position[0]
        col = position[1]

        parent_position = self.master.position  # master "ought to be" SubGrid
        self.position = (parent_position[0] * 3 + row, parent_position[1] * 3 + col)

        padx = (0, _BOX_PADDING) if col < 2 else 0
        pady = (0, _BOX_PADDING) if row < 2 else 0
        self.grid(row=row, column=col, padx=padx, pady=pady, sticky='nesw')

        self.inner_frame.pack(padx=_BORDER_WIDTH, pady=_BORDER_WIDTH, expand=True)
        self.number = 0

    @property
    def number(self):
        """The number the box contains. Setting this value may change the box's style."""
        try:
            return int(self.number_text.get())
        except ValueError:
            return 0

    @number.setter
    def number(self, value):
        for pencil_mark in self.pencil_marks:
            pencil_mark.grid_forget()
        self['style'] = styles.BOX_FRAME
        self.inner_frame['style'] = styles.BOX_FRAME
        self.label['style'] = styles.NUMBER_LABEL

        self.label.place(relx=0.5, rely=0.5, anchor='center')
        self.number_text.set(str(value or ' ')[0])

    @property
    def given(self):
        """The given value for this box. Setting this value may change the box's style."""
        if self['style'] != styles.GIVEN_FRAME:
            return 0
        else:
            return self.number

    @given.setter
    def given(self, value):
        for pencil_mark in self.pencil_marks:
            pencil_mark.grid_forget()
        self['style'] = styles.GIVEN_FRAME
        self.inner_frame['style'] = styles.GIVEN_FRAME
        self.label['style'] = styles.GIVEN_LABEL

        self.label.place(relx=0.5, rely=0.5, anchor='center')
        self.number_text.set(str(value or ' ')[0])

    def set_pencils(self, values=0b111111111):
        """Sets the box's pencils to showing.

        Args:
            values: Which pencil marks to display.
                Bit0 set means display the '1' pencil mark, bit1 set means display the '2' pencil mark, etc.
        """
        self.label.place_forget()
        self['style'] = styles.BOX_FRAME
        self.inner_frame['style'] = styles.BOX_FRAME

        for i in range(0, 9):
            pencil_mark = self.pencil_marks[i]
            pencil_mark.show(values & (1 << i))
            pencil_mark.grid(row=pencil_mark.position[0], column=pencil_mark.position[1], sticky='nesw')

    def set_borders(self, color, edges='nesw'):
        """Sets the borders on this box frame.

        Args:
            color: Color of borders to set, or `None` to hide the borders.
            edges: A subset of 'nesw' for which borders to show.
        """
        for edge in self.borders.keys():
            if edge in edges:
                self.borders[edge].set_color(color)
            else:
                self.borders[edge].set_color(None)
Esempio n. 24
0
def mouseEvtHandler(event):
    global x, y
    x, y = (event.x, event.y)
    print(f'{x}, {y}')
    lbl.place(x=x, y=y)


def scoll(event):
    global y
    if event.delta == -120:  #업스크롤
        y += 10
    if event.delta == 120:  #다운 스크롤
        y -= 10
    lbl.place(x=x, y=y)


win = Tk()

win.geometry("300x200+100+100")

lbl = Label(win, text="하이")
lbl.place(x=150, y=150)

# 왼쪽 마우스 B1 오른쪽 마우스 B2
win.bind("<B1-Motion>", mouseEvtHandler)
# 파이썬은 꺽새안에 태그처럼
win.bind("<MouseWheel>", scoll)

if __name__ == '__main__':
    win.mainloop()
Esempio n. 25
0
class App_test(object):
    def __init__(self, master, fuc, query, next, pre, query_all_chapters,
                 query_text):
        self.win = master
        self.win.title('shuyaya阅读_v2.0   by: 孤月')
        # self.win.iconbitmap('./ico/gui_text_proce.ico')  # 指定界面图标
        curWidth = self.win.winfo_width()
        curHeight = self.win.winfo_height()
        scnWidth, scnHeight = self.win.maxsize()
        tmpcnf = '1340x640+500+300'  # % ((scnWidth - curWidth) / 2, (scnHeight - curHeight) / 2)
        self.win.geometry(tmpcnf)
        self.creat_res()
        self.set_position()
        self.list_box(query_all_chapters, query_text)
        # self.add_train_info()
        self.res_config(fuc, query, next, pre)
        self.train_message = {}
        self.gettime()  # 系统时间

    def creat_res(self):
        # self.v = IntVar()  # 书籍查询
        # self.v.set(True)
        self.temp = StringVar()  # 书名/作者 录入
        self.temp2 = StringVar()  # 章节名录入
        self.sys_time = StringVar()  # 系统时间

        self.E_startstation = Entry(self.win, textvariable=self.temp)
        # self.E_endstation = Entry(self.win, textvariable=self.temp2)

        self.La_startstation = Label(self.win, text="根据书名/作者搜索:")
        self.La_endstation = Label(self.win, text="书籍目录:")
        self.La_directory = Label(self.win, text="目录")
        self.La_text = Label(self.win, text="正文")
        self.La_sys_time = Label(self.win,
                                 textvariable=self.sys_time,
                                 fg='blue',
                                 font=("黑体", 20))  # 设置字体大小颜色
        self.La_pic = Label(self.win, bg="#E6E6FA")
        self.La_anthor = Label(self.win, bg="#E6E6FA")
        self.La_type = Label(self.win, bg="#E6E6FA")
        self.La_update_time = Label(self.win, bg="#E6E6FA")
        self.La_latest_chapter = Label(self.win, bg="#E6E6FA")

        self.B_search = Button(self.win, text="搜索")
        self.B_buy_tick = Button(self.win, text="阅读")
        self.B_pre_chapter = Button(self.win, text="上一章")
        self.B_next_chapter = Button(self.win, text="下一章")

        # self.R_site = Radiobutton(self.win, text="书名查询", variable=self.v, value=True)
        # self.R_price = Radiobutton(self.win, text="章节查询", variable=self.v, value=False)

        self.init_data_Text = Text(self.win)  # 原始数据录入框
        self.S_move = Scrollbar(self.win)  # 目录滚动条
        self.S_text_move = Scrollbar(self.win)  # 创建文本框滚动条

    # 设置位置
    def set_position(self):
        self.init_data_Text.place(x=430, y=40, width=870, height=550)
        self.E_startstation.place(x=10, y=50, width=145, height=30)
        self.E_startstation.insert(10, "星辰变")
        # self.E_endstation.place(x=10, y=140, width=145, height=30)
        # self.E_endstation.insert(10, "第一章 秦羽")
        self.La_startstation.place(x=10, y=10, width=130, height=30)
        self.La_endstation.place(x=10, y=100, width=60, height=30)
        self.La_sys_time.place(x=1150, y=600, width=160, height=30)
        self.La_pic.place(x=10, y=350, width=170, height=180)  # 图片
        self.La_anthor.place(x=10, y=545, width=170, height=30)
        self.La_type.place(x=10, y=575, width=170, height=30)
        self.La_update_time.place(x=10, y=605, width=170, height=30)
        self.La_latest_chapter.place(x=10, y=635, width=170, height=30)

        self.B_search.place(x=10, y=300, width=80, height=40)
        self.B_buy_tick.place(x=90, y=300, width=80, height=40)
        self.B_pre_chapter.place(x=950, y=600, width=80, height=40)
        self.B_next_chapter.place(x=1050, y=600, width=80, height=40)
        self.S_move.place(x=380, y=40, width=30, height=550)
        self.S_text_move.place(x=1300, y=40, width=30, height=550)
        # self.R_site.place(x=10, y=180, width=90, height=30)
        # self.R_price.place(x=100, y=180, width=90, height=30)
        self.La_directory.place(x=180, y=7, width=90, height=30)
        self.La_text.place(x=420, y=7, width=70, height=30)

    # 为按钮绑定事件
    def res_config(self, fuc, query, next_, pre):
        self.B_search.config(command=fuc)  # 搜索
        self.B_buy_tick.config(command=query)  # 阅读
        self.B_pre_chapter.config(command=pre)  # 上一章
        self.B_next_chapter.config(command=next_)  # 下一章
        self.S_move.config(command=self.Ls_box_ct.yview)  # 目录滚动条
        self.Ls_box_ct.config(yscrollcommand=self.S_move.set)
        self.S_text_move.config(command=self.init_data_Text.yview)  # 文本框滚动条
        self.init_data_Text.config(yscrollcommand=self.S_text_move.set)

    # def printlist(self,event):
    #     print(self.Ls_box.get(self.Ls_box.curselection()))

    def list_box(self, query_all_chapters, query_text):
        self.Ls_box = Listbox(self.win, selectmode=EXTENDED, fg='blue')
        self.Ls_box.place(x=10, y=140, width=170, height=150)
        self.Ls_box.bind(
            '<Double-Button-1>', query_all_chapters
        )  # 鼠标双击  更多事件请看http://www.cnblogs.com/hackpig/p/8195678.html
        self.Ls_box.insert(END, "获取排行榜")  # 请输入书名&作者进行查询

        self.Ls_box_ct = Listbox(self.win, selectmode=EXTENDED, fg='blue')
        self.Ls_box_ct.place(x=200, y=40, width=180, height=550)
        self.Ls_box_ct.bind('<Double-Button-1>', query_text)

    def add_train_info(self):
        lis_train = ["C" + str(x) for x in range(0, 2)]
        tuple_train = tuple(lis_train)
        self.tree = Treeview(self.win,
                             columns=tuple_train,
                             height=30,
                             show="headings")
        self.tree.place(x=200, y=40, width=180, height=550)
        train_info = [' 书名 ', ' 作者 ']
        for i in range(0, len(lis_train)):
            self.tree.column(
                lis_train[i], width=len(train_info[i]) * 11,
                anchor='w')  # must be n, ne, e, se, s, sw, w, nw, or center
            self.tree.heading(lis_train[i], text=train_info[i])

    # 实时显示时钟
    def gettime(self):
        # 获取当前时间
        self.sys_time.set(time.strftime("%H:%M:%S"))
        # 每隔一秒调用函数自身获取时间
        self.win.after(1000, self.gettime)
Esempio n. 26
0
class setting_gui():
    def __init__(self, root):
        self.root = root
        self.root.title('Input wajah | SS Company 2019')
        self.root.resizable(
            False,
            False)  #mengatur agar windows tidak bisa diperbesar atau perkecil
        self.root.geometry("550x350")  #mengatur lebay layar
        self.root.protocol('WM_DELETE_WINDOW', self.quit)

        self.deklarasi_variable()
        self.atur_komponen()

        #menangkap gambar
        t = threading.Thread(target=self.tangkap_gambar, args=())
        t.start()

        self.get_id_user()

    def deklarasi_variable(self):
        self.berjalan = True  #deklarasi variable untuk menunjukan program masih berjalan
        self.simpan = False
        self.count = 0
        self.akhir = 100  #jumlah foto yang akan diambil
        self.proses = 0

    def atur_komponen(self):
        #tempat untuk menampilkan gambar
        self.image = Label(self.root)
        self.image.place(x=10, y=10)

        #textbox untuk gambar
        self.txt_gambar = Label(self.root)
        self.txt_gambar.place(x=80, y=315)

        #membuat form untuk memasukkan nama
        #entry nama
        Label(self.root, text="Masukkan Nama Anda : ").place(x=340, y=10)
        self.txt_nama = Entry(self.root)
        self.txt_nama.place(x=340, y=30)

        #button untuk daftar wajah
        self.btn_daftar = Button(self.root, text="daftar",
                                 command=self.daftar).place(x=340, y=60)

        #komponen progres bar untuk memberi tahu kapan proses selesai
        Label(self.root, text="Proses Sedang berjalan : ").place(x=340, y=100)
        self.proses_bar = Progressbar(self.root,
                                      orient='horizontal',
                                      length=180,
                                      mode='determinate')
        self.proses_bar.place(x=340, y=120)

    def tangkap_gambar(self):
        cp = cv2.VideoCapture(0)
        while self.berjalan:
            #membaca input dari webcam
            _, img = cp.read()

            #mengimport file pemindai wajah
            face = cv2.CascadeClassifier('xml/deteksi_wajah.xml')

            #merubah gambar menjadi gray
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

            muka = face.detectMultiScale(gray, 1.3, 5)
            for (x, y, w, h) in muka:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
                if len(
                        muka
                ) == 1 and self.simpan and self.proses <= self.akhir:  #jika perintah simpan telah diterima
                    self.simpan_wajah(gray, x, y, w,
                                      h)  #memanggil fungsi simpan wajah
                    self.update_proses_bar(
                        self.proses)  #memanggil fungsi update status bar
                    self.proses += 1
                if self.proses == self.akhir and self.simpan:  #jika proses penambilan gambar telah selesai
                    self.decode_gambar()
                    self.simpan = False

            #jika tidak ditemukan wajah pada gambar
            if len(muka) == 0:
                self.txt_gambar['text'] = "Wajah tidak ditemukan!"
            elif len(muka) == 1:
                self.txt_gambar['text'] = "Wajah ditemukan"
            elif len(muka) > 1:
                self.txt_gambar['text'] = "Ditemukan " + str(
                    len(muka)) + " wajah"

            cek_folder("log/")
            cv2.imwrite("log/input.png", img)
            pic = Image.open("log/input.png")
            pic = pic.resize((300, 300), Image.ANTIALIAS)
            pic.save("log/input.png")
            gambar = PhotoImage(file="log/input.png")
            self.image.config(image=gambar)
            self.image.image = gambar

    #fungsi untuk btn_daftar
    def daftar(self):
        #cek apakah folder image telah ada
        cek = tkinter.messagebox.askquestion(
            "Pemberitahuan",
            "Pengambilan gambar akan dimulai\nApakah kamu mau lanjut?")
        if cek == 'yes':
            cek_folder("image/")
            self.simpan = True
            self.count = 0
            self.proses = 0

    #fungsi untuk menyimpan gambar ke folder image
    def simpan_wajah(self, gray, x, y, w, h):
        id = self.get_id_user()  #id untuk user yang akan disimpan wajah nya
        self.count += 1
        cv2.imwrite("image/User." + str(id) + '.' + str(self.count) + ".png",
                    gray[y:y + h, x:x + w])
        print("gambar ke " + str(self.proses) + " disimpan")

    #fungsi untuk mengurai gambar
    def decode_gambar(self):
        cek_folder('training/')
        tkinter.messagebox.showinfo(
            "Pemberitahuan", "Proses Pengambilan Gambar telah Selesai\n"
            "Dilanjutkan proses training\n"
            "Jangan melakukan aksi apapun")
        recognizer = cv2.face.LBPHFaceRecognizer_create(
        )  #deklarasi untuk pengenalan wajah
        deteksi = cv2.CascadeClassifier(
            'xml/deteksi_wajah.xml')  #import file untuk deteksi wajah

        #mendapatkan gambar dan id user
        muka, id = get_image("image", deteksi)

        #decode semua gambar
        recognizer.train(muka, np.array(id))

        #menyimpan hasil proses
        recognizer.save("training/hasil.yml")

        # membuat database nama dan id gambar
        self.simpan_user_id()

        tkinter.messagebox.showinfo(
            "Berhasil", "Wajah telah ditambahkan"
        )  #menampilkan pesan pemberitahuan bahwa proses te;ah berhasil
        self.proses_bar['value'] = 0  #update status proses bar

    #menampilkan presentasi proses yang sedang berjalan
    def update_proses_bar(self, proses):
        presentase = int((proses / 100) * 100)
        self.proses_bar['value'] = presentase

    #fungsi untuk menyimpan nama user dan id gambar yang terhubung
    def simpan_user_id(self):
        #cek apakah file telah ada
        if os.path.isfile('training/data_user.txt'):
            #jika file sudah ada
            file = open('training/data_user.txt', 'a')
            text = "\n"
        else:
            #jika file belum ada
            file = open("training/data_user.txt", 'w')
            text = ""

        #mendapatkan id terakhir yang telah tersimpan
        id = self.get_id_user()
        nama = self.txt_nama.get()

        #menuliskan nama ke data_user.txt
        text = text + str(id) + ":" + nama
        file.write(text)

    def get_id_user(self):
        # cek apakah file telah ada
        if os.path.isfile('training/data_user.txt'):
            #jika file sudah ada
            file = open('training/data_user.txt', 'r')
        else:
            #jika file belum ada
            return 0

        #membaca file perbaris
        baris = file.readlines()
        if len(baris) > 0:
            baris = baris[len(baris) - 1]
            baris = baris.split("\n")
            baris = baris[0]
            id = baris.split(":")
            id = int(id[0]) + 1
        else:
            id = 0
        return id

    def hentikan_proses(self):
        self.berjalan = False
        cek = tkinter.messagebox.askquestion(
            "pemberitahuan", "Apakah Kamu akan mengakhiri proses ini?")
        if cek == "yes":
            self.root.quit()
        else:
            self.berjalan = True
            t = threading.Thread(target=self.tangkap_gambar, args=())
            t.start()

    def quit(self):
        self.berjalan = False
        cek = tkinter.messagebox.askquestion(
            "pemberitahuan", "Apakah Kamu akan mengakhiri proses ini?")
        if cek == "yes":
            self.root.destroy()
        else:
            self.berjalan = True
            t = threading.Thread(target=self.tangkap_gambar, args=())
            t.start()
Esempio n. 27
0
    def initialize_settings_ui(self):
        # Initializes resamples field
        resamples_label = Label(self, text="Resamples (affects recognition accuracy)")
        resamples_label.place(y=12.5, x=12.5)
        resamples_text = tk.StringVar()
        resamples_text.set(self.settings["resamples"])
        resamples_spin = Spinbox(self, from_=1, to=10, textvariable=resamples_text)
        resamples_spin.config(command=partial(self.save_settings, "resamples", lambda: int(resamples_text.get())))
        resamples_spin.place(y=37.5, x=12.5)
        separator1 = Separator(self, orient='horizontal')
        separator1.place(y=62.5, x=12.5, width=375, height=1)

        # Initializes tolerance field
        tolerance_label = Label(self, text="Face matching tolerance (lower is more strict)")
        tolerance_label.place(y=68.75, x=12.5)
        tolerance_text = tk.StringVar()
        tolerance_text.set(self.settings["tolerance"])
        tolerance_spin = Spinbox(self, from_=0, to=1, increment=0.1, textvariable=tolerance_text)
        tolerance_spin.config(command=partial(self.save_settings, "tolerance", lambda: float(tolerance_text.get())))
        tolerance_spin.place(y=93.75, x=12.5)
        separator2 = Separator(self, orient='horizontal')
        separator2.place(y=118.75, x=12.5, width=375, height=1)

        # Initializes track period field
        track_period_label = Label(self, text="Track period (the number of frames between each recognition)")
        track_period_label.place(y=125, x=12.5)
        track_period_text = tk.StringVar()
        track_period_text.set(self.settings["track_period"])
        track_period_spin = Spinbox(self, from_=1, to=30, textvariable=track_period_text)
        track_period_spin.config(command=partial(self.save_settings, "track_period", lambda: int(track_period_text.get())))
        track_period_spin.place(y=150, x=12.5)
        separator3 = Separator(self, orient='horizontal')
        separator3.place(y=175, x=12.5, width=375, height=1)

        # Initializes blur method field
        blur_method_label = Label(self, text="Blur method")
        blur_method_label.place(y=181.25, x=12.5)
        blur_method_text = tk.StringVar()
        blur_method_text.set(self.settings["blur_method"])
        blur_method_menu = Combobox(self, textvariable=blur_method_text, values=("pixelate", "blur", "blacken"))
        blur_method_text.trace('w', partial(self.save_settings, "blur_method", lambda: blur_method_text.get()))
        blur_method_menu.place(y=206.25, x=12.5)
        separator4 = Separator(self, orient='horizontal')
        separator4.place(y=231.25, x=12.5, width=375, height=1)

        # Initializes blur intensity field
        blur_intensity_label = Label(self, text="Blur intensity (filter size)")
        blur_intensity_label.place(y=237.5, x=12.5)
        blur_intensity_text = tk.StringVar()
        blur_intensity_text.set(self.settings["blur_intensity"])
        blur_intensity_spin = Spinbox(self, from_=1, to=30, textvariable=blur_intensity_text)
        blur_intensity_spin.config(command=partial(self.save_settings, "blur_intensity", lambda: int(blur_intensity_text.get())))
        blur_intensity_spin.place(y=262.5, x=12.5)
        separator5 = Separator(self, orient='horizontal')
        separator5.place(y=287.5, x=12.5, width=375, height=1)

        # Initializes display output field
        display_output_flag = tk.IntVar()
        display_output_flag.set(self.settings["display_output"])
        display_output_checkbox = tk.Checkbutton(self, text='Display output', variable=display_output_flag, onvalue=1, offvalue=0)
        display_output_checkbox.config(command=partial(self.save_settings, "display_output", lambda: display_output_flag.get()))
        display_output_checkbox.place(y=293.75, x=12.5)
Esempio n. 28
0
class Application_ui(Frame):
    #这个类仅实现界面生成功能,具体事件处理代码在子类Application中。

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title('Excel转化Rpy工具')
        self.master.geometry('600x343')
        self.createWidgets()

    def createWidgets(self):
        self.top = self.winfo_toplevel()

        self.style = Style()
        self.bkg_gif = PhotoImage(data=base64.b64decode(back_ground_gif_data))
        self.background_label = Label(self.top, image=self.bkg_gif)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)

        self.Text = Text(self.top, font=('宋体', 9))
        self.Text.place(relx=0.066, rely=0.07, relwidth=0.869, relheight=0.563)

        self.saveAddr = Entry(self.top, font=('宋体', 9))
        self.saveAddr.place(relx=0.355,
                            rely=0.84,
                            relwidth=0.409,
                            relheight=0.052)

        self.ComboList = ['源文件目录', '自定义目录']
        self.Combo = Combobox(self.top,
                              values=self.ComboList,
                              font=('宋体', 9),
                              state='readonly')
        self.Combo.place(relx=0.184,
                         rely=0.84,
                         relwidth=0.146,
                         relheight=0.058)
        self.Combo.set(self.ComboList[0])
        self.Combo.bind('<<ComboboxSelected>>', self.comboEvent)

        self.style.configure('InputButton.TButton', font=('宋体', 9))
        self.InputButton = Button(self.top,
                                  text='浏览',
                                  command=self.InputButton_Cmd,
                                  style='InputButton.TButton')
        self.InputButton.place(relx=0.184,
                               rely=0.7,
                               relwidth=0.133,
                               relheight=0.073)

        self.Haruhi_gif = PhotoImage(data=base64.b64decode(haruhi_gif_data))
        self.style.configure('ConvertButton.TButton', font=('宋体', 9))
        self.ConvertButton = Button(self.top,
                                    image=self.Haruhi_gif,
                                    command=self.ConvertButton_Cmd,
                                    style='ConvertButton.TButton')
        self.ConvertButton.place(relx=0.788,
                                 rely=0.7,
                                 relwidth=0.146,
                                 relheight=0.236)

        self.style.configure('OutputLabel.TLabel', anchor='w', font=('宋体', 9))
        self.OutputLabel = Label(self.top,
                                 text='保存目录:',
                                 style='OutputLabel.TLabel')
        self.OutputLabel.place(relx=0.066,
                               rely=0.84,
                               relwidth=0.107,
                               relheight=0.05)

        self.style.configure('InputLabel.TLabel', anchor='w', font=('宋体', 9))
        self.InputLabel = Label(self.top,
                                text='输入设置:',
                                style='InputLabel.TLabel')
        self.InputLabel.place(relx=0.066,
                              rely=0.723,
                              relwidth=0.107,
                              relheight=0.05)
Esempio n. 29
0
class Window(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("IOTHOOK")
        self.pack(fill=BOTH, expand=True)

        self.master.protocol("WM_DELETE_WINDOW", self.on_closing)

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

        self.is_connect = False

        self.row = 0
        self.column = 0

        self.api_label = Label(self, text="API KEY")
        self.api_label.place(x=10, y=10)

        self.row = 0
        self.column += 1

        self.api_entry = Entry(self)
        self.api_entry.place(x=70, y=10)
        #
        # self.row = 0
        # self.column += 1
        #
        self.connect = Button(self, text="Connect", command=self.connect_command)
        self.connect.place(x=270, y=10)

        # self.row += 1
        # self.column = 0

        self.field_1_label = Label(self, text="Field 1")
        self.field_1_label.place(x=10, y=40)

        self.row += 0
        self.column += 1

        self.field_1 = Checkbutton(self, width=5)
        self.field_1.place(x=110, y=40)
        #
        # self.row += 1
        # self.column = 0
        #
        self.field_2_label = Label(self, text="Field 2")
        self.field_2_label.place(x=10, y=60)

        self.row += 0
        self.column += 1

        self.field_2 = Checkbutton(self, width=5)
        self.field_2.place(x=110, y=60)
        #
        # self.row += 1
        # self.column = 0
        #
        self.field_3_label = Label(self, text="Field 3")
        self.field_3_label.place(x=10, y=80)

        self.row += 0
        self.column += 1

        self.field_3 = Checkbutton(self, width=5)
        self.field_3.place(x=110, y=80)
        #
        # self.row += 1
        # self.column = 0
        #
        self.field_4_label = Label(self, text="Field 4")
        self.field_4_label.place(x=10, y=100)

        self.row += 0
        self.column += 1

        self.field_4 = Checkbutton(self, width=5)
        self.field_4.place(x=110, y=100)
        #
        # self.row += 1
        # self.column = 0
        #
        self.received_graph_label = Label(self, text="Received Data Graph")
        self.received_graph_label.place(x=10, y=140)

        self.row += 1
        self.column = 0

        self.fig = Figure(figsize=(6, 5), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.ax.grid()

        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.get_tk_widget().place(x=10, y=180)

    def thread_function(self):
        while True:
            API_KEY = 'ceb0024b84ff6fb7527d5506'  # demo hesap #17 random test
            url = 'http://iothook.com/api/device/?api_key=' + API_KEY + "&results=1"

            response = requests.get(url)
            data = response.json()
            print(data)
            print(len(data))
            print(data[0]['id'])

            # self.ax.cla()
            # self.ax.grid()
            # dpts = [random.randint(1, 100), random.randint(1, 100), random.randint(1, 10), random.randint(1, 10),
            #         random.randint(1, 10), random.randint(1, 10), random.randint(1, 10), random.randint(1, 10),
            #         random.randint(1, 10), random.randint(1, 10), ]
            # self.ax.plot(range(10), dpts, marker='o', color='orange')
            # self.canvas.draw()
            print("t")
            time.sleep(2)

    def connect_command(self):
        self.x = threading.Thread(target=self.thread_function, daemon=True)
        self.x.start()



    def on_closing(self):
        self.master.destroy()
Esempio n. 30
0
class TtkScale(Scale):
    """ Enhanced ttk Scale

    Parameters
    ----------
    parent : str
                The parent tk widget, normally a Frame.
    length : int
                The Scale length in pixels.
    from_ : int
                The minimum extent of the range.
    to : int
                the maximum extent of slider movement.
    orient : str
                Either 'horizontal' or 'vertical'
    variable : var
                Name of a tkinter variable.
    digits : int
                Number of decimal places displayed on actual value.
    tickinterval : int or float
                Spacing between range values.
    sliderlength : int
                Length used to set range position.
    command : var
                Method that is called whenever the slider moves.
    style : str
                Used to set the Scale's appearance.
    showvalue : bool
                True turns on the actual display value.
    resolution : int
                Amount slider moves when the trough is clicked, in pixels.

    """
    def __init__(self,
                 parent,
                 length=0,
                 from_=0,
                 to=255,
                 orient='horizontal',
                 variable=0,
                 digits=0,
                 tickinterval=None,
                 sliderlength=32,
                 command=None,
                 style=None,
                 showvalue=True,
                 resolution=1):

        self.from_ = from_
        self.to = to
        self.variable = variable
        self.length = length
        self.command = command
        self.parent = parent
        self.orient = orient

        super().__init__(parent,
                         length=length,
                         from_=from_,
                         to=to,
                         orient=orient,
                         variable=variable,
                         command=command,
                         style=style)

        self.digits = digits
        self.tickinterval = tickinterval
        self.showvalue = showvalue
        self.resolution = resolution
        self.sliderlength = sliderlength  # = 32

        theme_sl = {
            'alt': 9,
            'clam': 30,
            'classic': 30,
            'default': 30,
            'lime': 9,
            'winnative': 9
        }

        theme_bw = {
            'alt': 0,
            'clam': 1,
            'classic': 2,
            'default': 1,
            'lime': 6,
            'winnative': 0
        }

        # set trough borderwidth
        st = Style(self)
        theme_used = st.theme_use()
        if theme_used in ('alt', 'clam', 'classic', 'default', 'lime',
                          'winnative'):
            self.bw_val = bw_val = theme_bw[theme_used]
            self.sliderlength = sliderlength = theme_sl[theme_used]
        else:
            self.bw_val = bw_val = 1

        if showvalue:
            self.configure(command=self.display_value)

        if showvalue:
            self.configure(command=self.display_value)

        def_font = font.nametofont('TkDefaultFont')

        data = np.arange(from_,
                         (to + 1 if tickinterval >= 1 else to + tickinterval),
                         tickinterval)
        self.data = data = np.round(data, 1)
        range_vals = tuple(data)
        len_rvs = len(range_vals)
        if self.orient == 'horizontal':
            vals_size = [def_font.measure(str(i)) for i in range_vals]
            data_size = sum(vals_size)
            space_size = len_rvs * def_font.measure('0')
        else:
            lspace = def_font.metrics('linespace')
            data_size = len_rvs * lspace
            space_size = len_rvs * 3
        sizes = data_size + space_size
        min_len = (sizes if sizes % 50 == 0 else sizes + 50 - sizes % 50)
        self.len_val = len_val = min_len if length < min_len else length
        self.configure(length=len_val)

        self.rel_min = rel_min = (sliderlength // 2 + bw_val) / len_val
        self.rel_max = rel_max = 1 - (sliderlength // 2 - bw_val) / len_val

        if range_vals[-1] == to:
            pass
        else:
            max_rv = range_vals[-1]
            self.mult_l = ((max_rv - from_) * rel_max / (to - from_))

        self.bind("<Button-1>", self.resolve)

        self.build(to, rel_min, rel_max, range_vals, len_rvs)

    def build(self, to, rel_min, rel_max, range_vals, len_rvs):
        """Creates the Labels used to show the range and the first actual value.

        Parameters
        ----------
        to : int
                The maximum extent of slider movement.
        rel_min : float
                The range's minimum position as a relative size of the Scale.
        rel_max : float
                The range's maximum position as a relative size of the Scale.
        range_vals : tuple of int or floats
                The values shown in the range.
        len_rvs : int
                Size of the range values.

        """

        if self.orient == 'horizontal':
            for i, rv in enumerate(range_vals):
                item = Label(self.parent, text=rv)
                item.place(
                    in_=self,
                    bordermode='outside',
                    relx=(rel_min + i / (len_rvs - 1) *
                          ((rel_max if range_vals[-1] == to else self.mult_l) -
                           rel_min)),
                    rely=1,
                    anchor='n')
        else:
            for i, rv in enumerate(range_vals):
                item = Label(self.parent, text=rv)
                item.place(
                    in_=self,
                    bordermode='outside',
                    rely=(rel_min + i / (len_rvs - 1) *
                          ((rel_max if range_vals[-1] == to else self.mult_l) -
                           rel_min)),
                    relx=1,
                    anchor='w')

        if self.showvalue:
            self.disp_lab = Label(self.parent, text=self.get())
            rel_l = self.convert_to_rel(float(self.get()))
            if self.orient == 'horizontal':
                self.disp_lab.place(in_=self,
                                    bordermode='outside',
                                    relx=rel_l,
                                    rely=0,
                                    anchor='s')
            else:
                self.disp_lab.place(in_=self,
                                    bordermode='outside',
                                    rely=rel_l,
                                    relx=0,
                                    anchor='e')

    def convert_to_rel(self, curr_val):
        """Method to convert the actual value to a relative position.

        Parameters
        ----------
        curr_val : float
                    Actual value of the Scale.

        Returns
        -------
        float

        """
        return ((curr_val - self.from_) * (self.rel_max - self.rel_min) /
                (self.to - self.from_) + self.rel_min)

    def convert_to_act(self, curr_val):
        """Method to convert the actual value to an actual position.

        Parameters
        ----------
        curr_val : float
                    Actual value of the Scale.

        Returns
        -------
        float

        """

        l_max = self.rel_max * self.len_val
        l_min = self.rel_min * self.len_val
        return ((curr_val - self.from_) * (l_max - l_min) /
                (self.to - self.from_) + l_min)

    def display_value(self, value):
        """Position (in pixel) of the centre of the slider.

        Parameters
        ----------
        value : float
                    Actual value of the Scale.

        Returns
        -------
        float

        """

        rel_l = self.convert_to_rel(float(value))
        self.disp_lab.config(text=value)  # text=""
        if self.orient == 'horizontal':
            self.disp_lab.place_configure(relx=rel_l)
        else:
            self.disp_lab.place_configure(rely=rel_l)
        digits = self.digits
        self.disp_lab.configure(text=f'{float(value):.{digits}f}')
        # if your python is not 3.6 or above use the following 2 lines
        #   instead of the line above
        #my_precision = '{:.{}f}'.format
        #self.disp_lab.configure(text=my_precision(float(value), digits))

    def resolve(self, evt):
        """Enables mouse click in trough to move slider selected pixel
            amount

        Parameters
        ----------
        evt : str
                    Actual position of the cursor.

        """

        resolution = self.resolution
        if resolution < 1 or self.tickinterval < 1:
            pass
        else:
            value = self.get()
            curr_l = self.convert_to_act(value)
            if self.orient == 'horizontal':
                if evt.x < curr_l - self.sliderlength / 2:
                    self.set(value - resolution + 1)
                elif evt.x > curr_l + self.sliderlength / 2:
                    self.set(value + resolution - 1)
            else:
                if evt.y < curr_l - self.sliderlength / 2:
                    self.set(value - resolution + 1)
                elif evt.y > curr_l + self.sliderlength / 2:
                    self.set(value + resolution - 1)
Esempio n. 31
0
    def __init__(self):
        ThemedTk.__init__(self, theme='black')
        self.title('Установщик F_Reference_H')
        self.geometry('500x200')
        x = (self.winfo_screenwidth() -
             self.winfo_reqwidth()) / 2
        y = (self.winfo_screenheight() -
             self.winfo_reqheight()) / 2
        self.wm_geometry("+%d+%d" % (x - 150, y - 20))
        self.resizable(width=False, height=False)
        self.iconphoto(
            True,
            PhotoImage(file='bin/ico/ico_main.png')
        )
        flow_hack_png = Image.open(f'bin/ico/max_flowhack.png')
        flow_hack_png = ImageTk.PhotoImage(flow_hack_png)
        browse_png = Image.open(f'bin/ico/browse.png')
        browse_png = ImageTk.PhotoImage(browse_png)
        self.frame = Frame(self)
        self.frame.place(relwidth=1, relheight=1)
        self.url = ''
        self._path = getcwd()

        flow_hack_label = Label(
            self.frame,
            image=flow_hack_png,
            cursor='heart'
        )
        flow_hack_label.bind('<Button-1>', open_web)
        flow_hack_label.place(anchor='c', relx=.5, rely=.1)
        self.check_icon = BooleanVar()
        self.check_icon.set(bool(True))
        Checkbutton(
            self.frame,
            text='Создать ярлык на рабочем столе',
            var=self.check_icon,
            cursor='cross'
        ).place(relx=.5, y=60, anchor='c')
        Label(
            self.frame,
            text='Выберите папку для установки',
            font=('Times New Roman', 10, 'bold italic')
        ).place(relx=.5, rely=.485, anchor='c')
        self.input_url = Entry(
            self.frame,
            state=DISABLED,
            font=('Times New Roman', 9, 'bold italic'),
            foreground='black'
        )
        self.input_url.place(
            rely=.6,
            relx=.5,
            height=20,
            relwidth=.7,
            anchor='c'
        )
        Button(
            self.frame,
            image=browse_png,
            cursor='hand1',
            command=self.directory
        ).place(relx=.86, rely=.455)
        Button(
            self.frame,
            image=browse_png,
            cursor='hand1',
            command=self.directory
        ).place(relx=.045, rely=.455)
        Button(
            self.frame,
            text='Установить',
            cursor='hand1',
            command=self.install
        ).place(relx=.5, rely=.75, anchor='c')
        self.license = Label(
            self.frame,
            text='Для подтверждения согласия с лицензионным '
                 'соглашением\nНажмите на "Установить" правой кнопкой мыши',
            font=('Times New Roman', 9, 'bold italic'),
            foreground='black',
            cursor='hand1',
            justify='center'
        )
        self.license.bind(
            '<Button-1>',
            lambda no_matter: webopen('https://flowhack.github.io/')
        )
        self.license.place(relx=.5, rely=.93, anchor='c')

        self.mainloop()
Esempio n. 32
0
    def initUI(self):
        # define dialog box properties
        self.parent.title("Duokan Footnote Linker")
        self.pack(fill=BOTH, expand=1)

        # get preferences
        prefs = self.bk.getPrefs()

        # info
        infoLabel = Label(self, text="Additional compatibility: ")
        infoLabel.place(x=25, y=10)

        # compatibility check
        self.kindle = IntVar()
        # if 'kindle' in prefs:
        #     self.kindle.set(prefs['kindle'])
        # else:
        #     self.kindle.set(1)
        self.kindle.set(1)
        kindleCheck = Checkbutton(self, text="Kindle", variable=self.kindle)
        kindleCheck.place(x=40, y=30)

        self.ibooks = IntVar()
        # if 'ibooks' in prefs:
        #     self.ibooks.set(prefs['ibooks'])
        # else:
        #     self.ibooks.set(1)
        self.ibooks.set(1)
        ibooksCheck = Checkbutton(self,
                                  text="iBooks(macOS only)",
                                  variable=self.ibooks)
        ibooksCheck.place(x=150, y=30)

        # disable compatibility check temporarily
        # kindleCheck.config(state=tk.DISABLED)
        # ibooksCheck.config(state=tk.DISABLED)

        # footnote id prefix
        anchorIDLabel = Label(self, text="Anchor ID prefix: ")
        anchorIDLabel.place(x=25, y=60)
        self.anchorid = StringVar(None)
        if 'anchorid' in prefs:
            self.anchorid.set(prefs['anchorid'])
        else:
            self.anchorid.set('fnanchor-')
        anchorIDEntry = Entry(self, textvariable=self.anchorid)
        anchorIDEntry.place(x=150, y=60, width=85)

        # footnote definition id
        fndefIDLabel = Label(self, text="Definition ID prefix: ")
        fndefIDLabel.place(x=25, y=85)
        self.fndefid = StringVar(None)
        if 'fndefid' in prefs:
            self.fndefid.set(prefs['fndefid'])
        else:
            self.fndefid.set('fndef-')
        fndefIDEntry = Entry(self, textvariable=self.fndefid)
        fndefIDEntry.place(x=150, y=85, width=85)

        # backlink class
        backlinkLabel = Label(self, text="Backlink class: ")
        backlinkLabel.place(x=25, y=110)
        self.backlink = StringVar(None)
        if 'backlink' in prefs:
            self.backlink.set(prefs['backlink'])
        else:
            self.backlink.set('fnsymbol')
        backlinkEntry = Entry(self, textvariable=self.backlink)
        backlinkEntry.place(x=150, y=110, width=85)

        # Notes source location
        self.separate = IntVar()
        separateSourceCheck = Checkbutton(self,
                                          text="Footnote file: ",
                                          variable=self.separate)
        separateSourceCheck.place(x=5, y=135)

        self.notesource = StringVar()
        opf_guide_items = {}
        for ref_type, title, href in self.bk.getguide():
            opf_guide_items[ref_type] = href
        # look for notes guide item
        if 'notes' in opf_guide_items:
            print(
                'Separate note source found from OPF guide according to semantics.'
            )
            self.notesource.set(opf_guide_items['notes'])
            self.separate.set(1)
        noteSourceEntry = Entry(self, textvariable=self.notesource)
        noteSourceEntry.place(x=150, y=135, width=150)

        # OK and Cancel buttons
        cancelButton = Button(self, text="Cancel", command=self.quit)
        cancelButton.place(x=25, y=165)
        okButton = Button(self, text="OK", command=self.savevalues)
        okButton.place(x=150, y=165)
Esempio n. 33
0
    def Start_Win(
        self
    ):  #мой стартовый метод, который и вызывается. тут производится создание и размещение всех эллементов программы
        self.win = Tk()
        self.win.title(
            "Lab")  # название программы отображается в верхнем левом углу
        self.win.geometry("720x720")  #размер программы
        self.win.resizable(False, False)

        canvas = Canvas()
        canvas.create_line(0, 25, 400, 25)
        canvas.place(x=0, y=250)

        lbl_ID = Label(self.win, text="Enter student ID", justify=CENTER)
        lbl_ID.grid(row=0)
        lbl_Fn = Label(self.win, text="Enter Firstname", justify=CENTER)
        lbl_Fn.grid(row=2)
        lbl_Sn = Label(self.win, text="Enter Surname", justify=CENTER)
        lbl_Sn.grid(row=4)
        lbl_Age = Label(self.win, text="Choose student's age", justify=CENTER)
        lbl_Age.grid(row=6)
        lbl_Info = Label(
            self.win,
            text=
            "The program can check bd and show all results - Check Bd\n If you need, you can choose one note and delete it ->\nCreate your choose from list and press Delete\nThe Add to Database button use all elements upper.\n If user dont write there anything - in database create note\nwith empty cells",
            justify=CENTER)
        lbl_Info.place(x=10, y=280)

        self.login_ID = Entry(self.win, width=30, name='txt')
        self.login_ID.grid(column=0, row=1)
        self.login_Fn = Entry(self.win, width=30, name='txt_1')
        self.login_Fn.grid(column=0, row=3)
        self.login_Sn = Entry(self.win, width=30, name='txt_2')
        self.login_Sn.grid(column=0, row=5)

        self.age = Scale(self.win,
                         orient=HORIZONTAL,
                         length=300,
                         from_=15,
                         to=60,
                         resolution=1)
        self.age.grid(column=0, row=7)

        self.Degree = BooleanVar()
        self.cb = Checkbutton(self.win,
                              text="Undergraduate\Graduate",
                              variable=self.Degree)
        self.cb.grid(column=0, row=8)

        Add_in_list = Button(self.win,
                             text="Add to Database",
                             name="add to database",
                             command=self.Add_to_list)
        Add_in_list.grid(column=0, row=9)
        Check_bd = Button(self.win,
                          text="Check bd",
                          name="check bd",
                          command=self.Check_bd)
        Check_bd.place(x=580, y=660)
        Quit = Button(self.win,
                      text="Quit",
                      name="quit",
                      command=self.Quit_From_Prog,
                      background="#FF0000")
        Quit.place(x=660, y=660)
        Del = Button(self.win,
                     text="Delete",
                     name="del",
                     command=self.delete,
                     background="#FA8072")
        Del.place(x=158, y=230)
        Find = Button(self.win, text="Find", name="find", command=self.find)
        Find.place(x=103, y=230)

        scrollbar = Scrollbar(self.win)
        scrollbar.place(x=694, y=10)

        self.lb = Listbox(yscrollcommand=scrollbar.set,
                          height=40,
                          width=60,
                          selectmode=SINGLE)
        self.lb.bind("<<ListboxSelect>>", self.onSelect)
        self.lb.place(x=330, y=10)
        scrollbar.config(command=self.lb.yview)

        self.win.mainloop()
Esempio n. 34
0
]


tree = ttk.Treeview(rightFrame, columns=header_list, show="headings")
tree.pack()

for i, col in enumerate(header_list):
    tree.heading(col, text=col.title())
for i, item in enumerate(data_list):
    tree.insert('', 'end', iid='IID%d' %(i), values=item)

# TreeView의 각 필드 너비 설정
tree.column(0, width=50)
tree.column(1, width=80)
tree.column(2, width=150)
tree.column(3, width=250)

# TreeView의 높이 설정
tree.config(height=22)

# 앱 타이틀 라벨 추가
fontStyle = tkFont.Font(family="궁서체", size=28)
lbl_title = Label(topFrame, text="고객 관리 시스템", font=fontStyle)
#lbl_title.pack(side="bottom", anchor="center")
lbl_title.place(relx=0.5, rely=0.5, anchor='center')
#lbl_title.config(background="red")



if __name__ == '__main__':
    win.mainloop()
Esempio n. 35
0
root.title('tkinter mp3 player')
root.geometry(f"{width}x{height}")
# root.config(bg="gray")
#----------background image--------------
if height <= 650 and width <= 800:
    image = Image.open('images/music_player.jpg')
    image = image.resize((800, 680), Image.ANTIALIAS)
    background_image = ImageTk.PhotoImage(image=image)
else:
    image = Image.open('images/music_player.jpg')
    image = image.resize((1200, 700), Image.ANTIALIAS)
    background_image = ImageTk.PhotoImage(image=image)
    root.configure(width=1200, height=980)

background_label = Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1, anchor='nw')

#----------background image--------------
fm1 = Frame(root, bg='#000000', padx=12)
fm1.pack(side='left')
fm2 = Frame(root, width=90)
fm2.pack(side='bottom', ipadx=20, pady=20)

image = Image.open('images.jpg')
# image = image.resize((200, 150), Image.ANTIALIAS)
b_image = ImageTk.PhotoImage(image=image)

b_label = Label(fm2, image=b_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

pygame.mixer.init()
Esempio n. 36
0
class Config(Toplevel):
    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.title(_("Preferences"))
        self.grab_set()
        self.resizable(False, False)
        self.protocol("WM_DELETE_WINDOW", self.quit)
        self.changes = {}, {}

        # --- style
        style = Style(self)
        style.theme_use("clam")
        style.configure("TScale", sliderlength=20)
        style.map("TCombobox",
                  fieldbackground=[('readonly', 'white')],
                  selectbackground=[('readonly', 'white')],
                  selectforeground=[('readonly', 'black')])
        style.configure("prev.TLabel", background="white")
        style.map("prev.TLabel", background=[("active", "white")])
        color = CONFIG.get("Categories",
                           CONFIG.get("General", "default_category"))
        style.configure("titlebar.TFrame", background=color)
        style.configure("titlebar.TLabel", background=color)
        style.configure("text.TFrame", background="white")

        # --- body
        self.notebook = Notebook(self)
        okcancel_frame = Frame(self)
        okcancel_frame.columnconfigure(0, weight=1)
        okcancel_frame.columnconfigure(1, weight=1)
        self.notebook.pack(expand=True, fill="both")
        okcancel_frame.pack(fill="x", expand=True)

        # --- * General settings
        general_settings = Frame(self.notebook)
        general_settings.columnconfigure(0, weight=1)
        self.notebook.add(general_settings,
                          text=_("General"),
                          sticky="ewsn",
                          padding=4)

        # --- *-- language
        lang = {"fr": "Français", "en": "English"}
        self.lang = StringVar(self, lang[CONFIG.get("General", "language")])
        lang_frame = Frame(general_settings)
        Label(lang_frame, text=_("Language")).grid(row=0,
                                                   sticky="w",
                                                   padx=4,
                                                   pady=4)
        menu_lang = Menu(lang_frame, tearoff=False)
        Menubutton(lang_frame, menu=menu_lang, width=9,
                   textvariable=self.lang).grid(row=0,
                                                column=1,
                                                padx=8,
                                                pady=4)
        menu_lang.add_radiobutton(label="English",
                                  value="English",
                                  variable=self.lang,
                                  command=self.translate)
        menu_lang.add_radiobutton(label="Français",
                                  value="Français",
                                  variable=self.lang,
                                  command=self.translate)
        # --- *-- opacity
        self.opacity_scale = Scale(general_settings,
                                   orient="horizontal",
                                   length=200,
                                   from_=0,
                                   to=100,
                                   value=CONFIG.get("General", "opacity"),
                                   command=self.display_label)
        self.opacity_label = Label(
            general_settings,
            text="{val}%".format(val=self.opacity_scale.get()))
        # --- *-- position
        frame_position = Frame(general_settings)
        self.position = StringVar(self, CONFIG.get("General", "position"))
        Label(frame_position,
              text=_("Default position of the notes")).grid(row=0,
                                                            columnspan=3,
                                                            sticky="w",
                                                            padx=4,
                                                            pady=4)
        Radiobutton(frame_position,
                    text=_("Always above"),
                    value="above",
                    variable=self.position).grid(row=1, column=0)
        Radiobutton(frame_position,
                    text=_("Always below"),
                    value="below",
                    variable=self.position).grid(row=1, column=1)
        Radiobutton(frame_position,
                    text=_("Normal"),
                    value="normal",
                    variable=self.position).grid(row=1, column=2)
        # --- *-- titlebar
        self.titlebar_disposition = StringVar(
            self, CONFIG.get("General", "buttons_position"))
        font_title = "%s %s" % (CONFIG.get("Font", "title_family").replace(
            " ", "\ "), CONFIG.get("Font", "title_size"))
        style = CONFIG.get("Font", "title_style").split(",")
        if style:
            font_title += " "
            font_title += " ".join(style)

        frame_titlebar = Frame(general_settings)
        frame_titlebar.columnconfigure(1, weight=1)
        frame_titlebar.columnconfigure(3, weight=1)
        Label(frame_titlebar,
              text=_("Title bar disposition")).grid(row=0,
                                                    columnspan=4,
                                                    sticky="w",
                                                    padx=4,
                                                    pady=4)
        Radiobutton(frame_titlebar,
                    value="right",
                    variable=self.titlebar_disposition).grid(row=1, column=0)
        right = Frame(frame_titlebar, style="titlebar.TFrame")
        right.grid(row=1, column=1, sticky="ew")

        def select_right(event):
            self.titlebar_disposition.set("right")

        Label(right,
              text=_("Title"),
              style="titlebar.TLabel",
              anchor="center",
              font=font_title).pack(side="left", fill="x", expand=True)
        Label(right, image="img_close",
              style="titlebar.TLabel").pack(side="right")
        Label(right, image="img_roll",
              style="titlebar.TLabel").pack(side="right")
        for ch in right.children.values():
            ch.bind("<Button-1>", select_right)
        Radiobutton(frame_titlebar,
                    value="left",
                    variable=self.titlebar_disposition).grid(row=1, column=2)
        left = Frame(frame_titlebar, style="titlebar.TFrame")
        left.grid(row=1, column=3, sticky="ew")

        def select_left(event):
            self.titlebar_disposition.set("left")

        Label(left, image="img_close",
              style="titlebar.TLabel").pack(side="left")
        Label(left, image="img_roll",
              style="titlebar.TLabel").pack(side="left")
        Label(left,
              text=_("Title"),
              style="titlebar.TLabel",
              anchor="center",
              font=font_title).pack(side="right", fill="x", expand=True)
        for ch in left.children.values():
            ch.bind("<Button-1>", select_left)
        # --- *-- placement
        lang_frame.grid(sticky="w")
        Separator(general_settings, orient="horizontal").grid(sticky="ew",
                                                              pady=10)
        Label(general_settings, text=_("Opacity")).grid(sticky="w",
                                                        padx=4,
                                                        pady=4)
        self.opacity_scale.grid(padx=4, pady=(4, 10))
        self.opacity_label.place(in_=self.opacity_scale,
                                 relx=1,
                                 rely=0.5,
                                 anchor="w",
                                 bordermode="outside")
        Separator(general_settings, orient="horizontal").grid(sticky="ew",
                                                              pady=10)
        frame_position.grid(sticky="ew")
        Separator(general_settings, orient="horizontal").grid(sticky="ew",
                                                              pady=10)
        frame_titlebar.grid(sticky="ew", pady=4)
        if LATEX:
            Separator(general_settings, orient="horizontal").grid(sticky="ew",
                                                                  pady=10)
            Button(general_settings,
                   text=_('Delete unused LaTex data'),
                   command=self.cleanup).grid(padx=4, pady=4, sticky='w')

        # --- * Font settings
        font_settings = Frame(self.notebook)
        font_settings.columnconfigure(0, weight=1)
        self.notebook.add(font_settings,
                          text=_("Font"),
                          sticky="ewsn",
                          padding=4)

        # --- *-- title
        fonttitle_frame = Frame(font_settings)

        title_size = CONFIG.get("Font", "title_size")
        title_family = CONFIG.get("Font", "title_family")

        self.sampletitle = Label(fonttitle_frame,
                                 text=_("Sample text"),
                                 anchor="center",
                                 style="prev.TLabel",
                                 relief="groove")

        self.sampletitle.grid(row=2,
                              columnspan=2,
                              padx=4,
                              pady=6,
                              ipadx=4,
                              ipady=4,
                              sticky="eswn")
        self.fonts = list(set(font.families()))
        self.fonts.append("TkDefaultFont")
        self.fonts.sort()
        w = max([len(f) for f in self.fonts])
        self.sizes = [
            "%i" % i for i in (list(range(6, 17)) + list(range(18, 32, 2)))
        ]

        self.fonttitle_family = Combobox(fonttitle_frame,
                                         values=self.fonts,
                                         width=(w * 2) // 3,
                                         exportselection=False,
                                         validate="key")
        self._validate_title_size = self.register(
            lambda *args: self.validate_font_size(self.fonttitle_size, *args))
        self._validate_title_family = self.register(
            lambda *args: self.validate_font_family(self.fonttitle_family, *
                                                    args))
        self.fonttitle_family.configure(
            validatecommand=(self._validate_title_family, "%d", "%S", "%i",
                             "%s", "%V"))
        self.fonttitle_family.current(self.fonts.index(title_family))
        self.fonttitle_family.grid(row=0, column=0, padx=4, pady=4)
        self.fonttitle_size = Combobox(
            fonttitle_frame,
            values=self.sizes,
            width=5,
            exportselection=False,
            validate="key",
            validatecommand=(self._validate_title_size, "%d", "%P", "%V"))
        self.fonttitle_size.current(self.sizes.index(title_size))
        self.fonttitle_size.grid(row=0, column=1, padx=4, pady=4)

        frame_title_style = Frame(fonttitle_frame)
        frame_title_style.grid(row=1, columnspan=2, padx=4, pady=6)
        self.is_bold = Checkbutton(frame_title_style,
                                   text=_("Bold"),
                                   command=self.update_preview_title)
        self.is_italic = Checkbutton(frame_title_style,
                                     text=_("Italic"),
                                     command=self.update_preview_title)
        self.is_underlined = Checkbutton(frame_title_style,
                                         text=_("Underline"),
                                         command=self.update_preview_title)
        style = CONFIG.get("Font", "title_style")
        if "bold" in style:
            self.is_bold.state(("selected", ))
        if "italic" in style:
            self.is_italic.state(("selected", ))
        if "underline" in style:
            self.is_underlined.state(("selected", ))
        self.is_bold.pack(side="left")
        self.is_italic.pack(side="left")
        self.is_underlined.pack(side="left")

        self.update_preview_title()
        # --- *-- text
        size = CONFIG.get("Font", "text_size")
        family = CONFIG.get("Font", "text_family")

        font_frame = Frame(font_settings)
        self.sample = Label(font_frame,
                            text=_("Sample text"),
                            anchor="center",
                            style="prev.TLabel",
                            relief="groove")
        self.sample.grid(row=1,
                         columnspan=2,
                         padx=4,
                         pady=6,
                         ipadx=4,
                         ipady=4,
                         sticky="eswn")

        self.font_family = Combobox(font_frame,
                                    values=self.fonts,
                                    width=(w * 2) // 3,
                                    exportselection=False,
                                    validate="key")
        self._validate_family = self.register(
            lambda *args: self.validate_font_family(self.font_family, *args))
        self._validate_size = self.register(
            lambda *args: self.validate_font_size(self.font_size, *args))
        self.font_family.configure(validatecommand=(self._validate_family,
                                                    "%d", "%S", "%i", "%s",
                                                    "%V"))
        self.font_family.current(self.fonts.index(family))
        self.font_family.grid(row=0, column=0, padx=4, pady=4)
        self.font_size = Combobox(font_frame,
                                  values=self.sizes,
                                  width=5,
                                  exportselection=False,
                                  validate="key",
                                  validatecommand=(self._validate_size, "%d",
                                                   "%P", "%V"))
        self.font_size.current(self.sizes.index(size))
        self.font_size.grid(row=0, column=1, padx=4, pady=4)

        self.update_preview()

        # --- *-- placement
        Label(font_settings, text=_("Title")).grid(row=0,
                                                   padx=4,
                                                   pady=4,
                                                   sticky="w")
        fonttitle_frame.grid(row=1)
        Separator(font_settings, orient="horizontal").grid(row=2,
                                                           sticky="ew",
                                                           pady=10)
        Label(font_settings, text=_("Text")).grid(row=3,
                                                  padx=4,
                                                  pady=4,
                                                  sticky="w")
        font_frame.grid(row=4)

        # --- * Categories
        self.category_settings = CategoryManager(self.notebook, master)
        self.notebook.add(self.category_settings,
                          text=_("Categories"),
                          sticky="ewsn",
                          padding=4)
        # --- * Symbols
        symbols_settings = Frame(self.notebook)
        self.notebook.add(symbols_settings,
                          text=_("Symbols"),
                          sticky="ewsn",
                          padding=4)
        txt_frame = Frame(symbols_settings,
                          relief="sunken",
                          borderwidth=1,
                          style="text.TFrame")
        self.symbols = Text(txt_frame,
                            width=1,
                            height=1,
                            highlightthickness=0,
                            spacing2=5,
                            spacing1=5,
                            relief="flat",
                            padx=4,
                            pady=4,
                            font="%s %s" % (family.replace(" ", "\ "), size))
        self.symbols.insert("1.0", CONFIG.get("General", "symbols"))
        Label(symbols_settings, text=_("Available symbols")).pack(padx=4,
                                                                  pady=4)
        txt_frame.pack(fill="both", expand=True, padx=4, pady=4)
        self.symbols.pack(fill="both", expand=True)
        Button(symbols_settings, text=_('Reset'),
               command=self.reset_symbols).pack(padx=4, pady=4)

        # --- Ok/Cancel buttons
        Button(okcancel_frame, text="Ok", command=self.ok).grid(row=1,
                                                                column=0,
                                                                padx=4,
                                                                pady=10,
                                                                sticky="e")
        Button(okcancel_frame, text=_("Cancel"),
               command=self.destroy).grid(row=1,
                                          column=1,
                                          padx=4,
                                          pady=10,
                                          sticky="w")
        # --- bindings
        self.font_family.bind('<<ComboboxSelected>>', self.update_preview)
        self.font_family.bind('<Return>', self.update_preview)
        self.font_size.bind('<<ComboboxSelected>>',
                            self.update_preview,
                            add=True)
        self.font_size.bind('<Return>', self.update_preview, add=True)
        self.fonttitle_family.bind('<<ComboboxSelected>>',
                                   self.update_preview_title)
        self.fonttitle_size.bind('<<ComboboxSelected>>',
                                 self.update_preview_title,
                                 add=True)
        self.fonttitle_family.bind('<Return>', self.update_preview_title)
        self.fonttitle_size.bind('<Return>',
                                 self.update_preview_title,
                                 add=True)

    def reset_symbols(self):
        self.symbols.delete('1.0', 'end')
        self.symbols.insert('1.0', SYMBOLS)

    def cleanup(self):
        ''' Remove unused latex images '''
        self.master.cleanup()

    def validate_font_size(self, combo, d, ch, V):
        ''' Validation of the size entry content '''
        if d == '1':
            l = [i for i in self.sizes if i[:len(ch)] == ch]
            if l:
                i = self.sizes.index(l[0])
                combo.current(i)
                index = combo.index("insert")
                combo.selection_range(index + 1, "end")
                combo.icursor(index + 1)
            return ch.isdigit()
        else:
            return True

    def validate_font_family(self, combo, action, modif, pos, prev_txt, V):
        """ completion of the text in the path entry with existing
            folder/file names """
        try:
            sel = combo.selection_get()
            txt = prev_txt.replace(sel, '')
        except TclError:
            txt = prev_txt
        if action == "0":
            txt = txt[:int(pos)] + txt[int(pos) + 1:]
            return True
        else:
            txt = txt[:int(pos)] + modif + txt[int(pos):]
            l = [i for i in self.fonts if i[:len(txt)] == txt]
            if l:
                i = self.fonts.index(l[0])
                combo.current(i)
                index = combo.index("insert")
                combo.delete(0, "end")
                combo.insert(0, l[0].replace("\ ", " "))
                combo.selection_range(index + 1, "end")
                combo.icursor(index + 1)
                return True
            else:
                return False

    def ok(self):
        family = self.font_family.get()
        if family not in self.fonts:
            l = [i for i in self.fonts if i[:len(family)] == family]
            if l:
                family = l[0]
            else:
                family = 'TkDefaultFont'
        size = self.font_size.get()
        familytitle = self.fonttitle_family.get()
        if familytitle not in self.fonts:
            l = [i for i in self.fonts if i[:len(familytitle)] == familytitle]
            if l:
                familytitle = l[0]
            else:
                familytitle = 'TkDefaultFont'
        sizetitle = self.fonttitle_size.get()
        opacity = "%i" % float(self.opacity_scale.get())
        language = self.lang.get().lower()[:2]
        style = ""
        if self.is_bold.instate(("selected", )):
            style += "bold,"
        if self.is_italic.instate(("selected", )):
            style += "italic,"
        if self.is_underlined.instate(("selected", )):
            style += "underline,"
        if style:
            style = style[:-1]

        symbols = [
            l.strip() for l in self.symbols.get("1.0", "end").splitlines()
        ]

        CONFIG.set("General", "default_category",
                   self.category_settings.default_category.get().lower())
        CONFIG.set("General", "language", language)
        CONFIG.set("General", "opacity", opacity)
        CONFIG.set("General", "position", self.position.get())
        CONFIG.set("General", "buttons_position",
                   self.titlebar_disposition.get())
        CONFIG.set("General", "symbols", "".join(symbols))
        CONFIG.set("Font", "text_size", size)
        CONFIG.set("Font", "text_family", family)
        CONFIG.set("Font", "title_family", familytitle)
        CONFIG.set("Font", "title_size", sizetitle)
        CONFIG.set("Font", "title_style", style)

        col_changes = {}
        name_changes = {}
        for cat in self.category_settings.categories:
            new_name = self.category_settings.get_name(cat)
            if cat in CONFIG.options("Categories"):
                old_color = CONFIG.get("Categories", cat)
                new_color = COLORS[self.category_settings.get_color(cat)]
                if new_name != cat:
                    name_changes[cat] = new_name
                    CONFIG.remove_option("Categories", cat)
                    CONFIG.set("Categories", new_name, new_color)
                if old_color != new_color:
                    col_changes[new_name] = (old_color, new_color)
                    CONFIG.set("Categories", new_name, new_color)

            else:
                CONFIG.set("Categories", new_name,
                           COLORS[self.category_settings.get_color(cat)])
        save_config()
        self.changes = col_changes, name_changes
        self.destroy()

    def get_changes(self):
        return self.changes

    def translate(self):
        showinfo(
            "Information",
            _("The language setting will take effect after restarting the application"
              ),
            parent=self)

    def update_preview(self, event=None):
        family = self.font_family.get()
        size = self.font_size.get()
        self.sample.configure(font="%s %s" % (family.replace(" ", "\ "), size))

    def update_preview_title(self, event=None):
        family = self.fonttitle_family.get()
        size = self.fonttitle_size.get()
        config = "%s %s" % (family.replace(" ", "\ "), size)
        if self.is_bold.instate(("selected", )):
            config += " bold"
        if self.is_italic.instate(("selected", )):
            config += " italic"
        if self.is_underlined.instate(("selected", )):
            config += " underline"
        self.sampletitle.configure(font=config)

    def display_label(self, value):
        self.opacity_label.configure(text=" {val} %".format(
            val=int(float(value))))

    def quit(self):
        self.destroy()