예제 #1
0
 def agregar_treeview(self, parent):
     """
     Metodo para agregar Treeview y cargarlo con sqlite
     Argumento:
     Parent: Objeto de TK
     """
     self.my_tree = ttk.Treeview(parent, selectmode='browse')
     self.my_tree.grid(row=1, column=4, rowspan=10, pady=20, padx=20)
     vsb = Scrollbar(parent, orient="vertical", command=self.my_tree.yview)
     vsb.place(relx=0.978, rely=0.150, relheight=0.650, relwidth=0.020)
     self.my_tree.configure(yscrollcommand=vsb.set)
     self.my_tree['columns'] = ('ID', 'Titulo', 'Autor', 'Genero')
     # CreandoColumnas
     self.my_tree.column('#0', width=0, minwidth=1)
     self.my_tree.column('ID', anchor=W, width=20)
     self.my_tree.column('Titulo', anchor=W, width=200)
     self.my_tree.column('Autor', anchor=W, width=120)
     self.my_tree.column('Genero', anchor=W, width=120)
     # Creado Headings
     self.my_tree.heading('#0', text=' ', anchor=W)
     self.my_tree.heading('ID', text='ID', anchor=W)
     self.my_tree.heading('Titulo', text='Tirulo', anchor=W)
     self.my_tree.heading('Autor', text='Autor', anchor=W)
     self.my_tree.heading('Genero', text='Genero', anchor=W)
     self.my_tree.bind('<ButtonRelease-1>', self.cargar_item)
     self.refrescar_lista()
     self.my_tree.pack
예제 #2
0
class MsgWindow(Frame):
    def __init__(self, parent, **kwargs):
        self.parent = parent
        self.canvas = Canvas(self.parent, borderwidth=0, width=500, height=500)
        super().__init__(self.canvas, **kwargs)
        scroll_frame = Frame(self.parent, height=504, width=20)
        scroll_frame.pack(side="right", anchor="ne", fill="y")
        self._scrollbar = Scrollbar(scroll_frame,
                                    command=self.canvas.yview,
                                    orient="vertical")
        self._scrollbar.place(x=1, y=0, height=504)
        self.canvas.config(yscrollcommand=self._scrollbar.set)
        self.canvas.pack(fill="both")
        self.frame_id = self.canvas.create_window((2, 4),
                                                  window=self,
                                                  anchor="nw",
                                                  tags="self")
        self.canvas.bind("<Configure>", self.onConfig)

    def onConfig(self, event=None):
        """
            update scroll region, keep the bottom text in view
        """
        self.canvas.update_idletasks()
        self.canvas.config(scrollregion=self.canvas.bbox("all"))
        if event is not None:
            self.canvas.itemconfig(self.frame_id, width=event.width)
            # if called and not event bound, no scrolling
            self.canvas.yview_moveto(1.0)
예제 #3
0
class Chatbot:
    def __init__(self, window):
        window.title('Iris Assitant')
        window.geometry('405x400')
        window.resizable(0, 0)
        self.message_session = Text(window,
                                    bd=3,
                                    relief="flat",
                                    font=("Times", 10),
                                    undo=True,
                                    wrap="word")
        self.message_session.config(width=45,
                                    height=15,
                                    bg="#596",
                                    fg="white",
                                    state='disabled')
        self.overscroll = Scrollbar(window, command=self.message_session.yview)
        self.overscroll.config(width=20)
        self.message_session["yscrollcommand"] = self.overscroll.set
        self.message_position = 1.5
        self.send_button = Button(window,
                                  text='send',
                                  fg='white',
                                  bg='blue',
                                  width=9,
                                  font=('Times', 12),
                                  relief='flat',
                                  command=self.reply_to_you)
        self.Message_Entry = Entry(window, width=40, font=('Times', 12))
        self.Message_Entry.bind('<Return>', self.reply_to_you)
        self.message_session.place(x=20, y=20)
        self.overscroll.place(x=370, y=50)
        self.send_button.place(x=0, y=360)
        self.Message_Entry.place(x=135, y=365)
        self.Brain = json.load(open('knowledge.json'))

    def add_chat(self, message):
        self.message_position += 1.5
        print(self.message_position)
        self.Message_Entry.delete(0, 'end')
        self.message_session.config(state='normal')
        self.message_session.insert(self.message_position, message)
        self.message_session.see('end')
        self.message_session.config(state='disabled')

    def reply_to_you(self, event=None):
        message = self.Message_Entry.get().lower()
        message = 'you: ' + message + '\n'
        close_match = get_close_matches(message, self.Brain.keys())
        if close_match:
            reply = 'Iris: ' + self.Brain[close_match[0]][0] + '\n'
        else:
            reply = 'Iris: ' + 'Cant it in my knowledge base\n'
        self.add_chat(message)
        self.add_chat(reply)
예제 #4
0
  def _add_variable(self, name, default):
    if name != "":
      self.variable[name] = default
    print(self.variable)
    variablelist = Listbox(self._master, width =15, height=5)
    variablelist.place(x=20,y=420)
    scrollbar = Scrollbar(self._master)
    scrollbar.config(command=variablelist.yview)
    scrollbar.place(x=145,y=421, height=90)

    variablelist.config(yscrollcommand=scrollbar.set)
    for x in self.variable:
      variablelist.insert("end", x+" : "+self.variable[x])
예제 #5
0
    def _setup_main_window(self):
        self.window.title(bot_name)
        self.window.resizable(width=True, height=True)
        self.window.configure(width=450, height=600, bg=clr_bg)

        #head
        head_label = Label(self.window,
                           bg=clr_bg,
                           fg=clr_txt,
                           text=header_txt,
                           font=font_bold,
                           pady=10)
        head_label.place(relwidth=1)
        #divider
        line = Label(self.window, width=500, bg=clr_panel)
        line.place(relwidth=1, rely=0.7, relheight=0.015)
        #text
        self.text_widget = Text(self.window,
                                width=20,
                                height=2,
                                bg=clr_bg,
                                fg=clr_txt,
                                font=font,
                                padx=5,
                                pady=5)
        self.text_widget.place(relheight=0.745, relwidth=1, rely=0.08)
        self.text_widget.configure(cursor='arrow', state=DISABLED)
        #scroll
        scroller = Scrollbar(self.text_widget)
        scroller.place(relheight=1, relx=0.974)
        scroller.configure(command=self.text_widget.yview)
        #foot
        footer = Label(self.window, bg=clr_panel, height=80)
        footer.place(relwidth=1, rely=0.825)
        #message_box
        self.mbox = Entry(footer, bg=clr_mbox, font=font, fg=clr_txt)
        self.mbox.place(relwidth=0.74, relheight=0.06, relx=0.011, rely=0.008)
        self.mbox.focus()
        self.mbox.bind('<Return>', self._on_enter_pressed)
        #send_button
        self.send = Button(footer,
                           text='Send',
                           font=font_bold,
                           width=20,
                           bg=clr_send,
                           command=lambda: self._on_enter_pressed(None))
        self.send.place(relwidth=0.22, relx=0.77, rely=0.008, relheight=0.06)
예제 #6
0
def listbox():
    global parameters, lb
    wd = Tk()
    wd.title('selected stock list')
    wd.geometry('350x300')
    lb = Listbox(wd, bg='white', selectmode='multiple')
    scrollbar = Scrollbar(wd)
    for i in parameters:
        lb.insert('end', i)
    lb.place(x=30, y=10, height=220, width=250)
    scrollbar.place(x=275, y=10, height=220, width=15)
    lb.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=lb.yview)
    wd.resizable(0, 0)
    btn = Button(wd, text='STOP!', bg='#e2d1d0', command=Delete)
    btn.place(x=140, y=250, height=35, width=50)
    wd.mainloop()
예제 #7
0
파일: tklib.py 프로젝트: hahaplus/pyxllib
    def listbox_init(self):
        from tkinter import Listbox, Scrollbar
        from tkinter.constants import END

        # 1、创建listbox
        listbox = Listbox(self.frame, width=35)
        for t in self.ls:
            listbox.insert(END, t)
        listbox.place(relx=0.1, rely=0.3)
        listbox.bind('<<ListboxSelect>>', self.onselect)

        # 2、为列表添加滚动条
        s = Scrollbar(listbox)
        s.place(relx=0.94, relheight=1)
        s.config(command=listbox.yview)
        listbox.config(yscrollcommand=s.set)

        return listbox
예제 #8
0
    def initListbox(self):
        label = Label(self.root, text='手动选择周数查看:')
        label.place(x=500, y=450)

        self.listbox = Listbox(self.root, width=5, height=4, background='yellow')
        self.listbox.place(x=630, y=420)
        self.listbox.insert(1, '自动')

        for i in range(1, 18):
            self.listbox.insert(17, i)
        self.listbox.selection_set(0)

        scroll = Scrollbar(self.root, relief='ridge', command=self.listbox.yview)
        scroll.place(x=670, y=420, height=65)
        self.listbox.configure(yscrollcommand=scroll.set)

        button = Button(self.root, text='确定', width=6, command=self.confirmBtn)
        button.place(x=720, y=450)
예제 #9
0
class LB( Listbox ):
    def __init__(self, parent):
        Listbox.__init__(self, parent, background = "#ffffff", selectbackground = "#363636", selectforeground = "#fafafa" )
        self.scbar = Scrollbar( parent )
        self.config( yscrollcommand = self.scbar.set )
        self.scbar.config( command = self.yview )
    def insertList(self, list):
        for item in list:
            self.insert( END, item["email"] )
    def deleteList(self):
        self.delete(0, END)
    def savePlaceData(self):
        self.placeData = self.place_info()
    def show(self):
        self.place( self.placeData )
        self.scbar.place( self.scbar.pi )
    def hide(self):
        self.place_forget()
        self.scbar.place_forget()
예제 #10
0
    def __init__(self, _trade_list):
        self.trade_list = deepcopy(_trade_list)

        # initialize the tkinter GUI
        root = tk.Tk()

        root.geometry("700x500")
        root.pack_propagate(0)
        root.resizable(0, 0)
        root.title('Portfolio manager for cTrader')

        # This is the frame for the Treeview
        frame1 = tk.LabelFrame(root, text="Portfolio Trades")
        frame1.place(height=500, width=700)

        self.tv1 = ttk.Treeview(frame1)  # This is the Treeview Widget
        tss = TradingSystemSchema()
        column_list_account = tss.__colums_checkList__  # These are our headings
        self.tv1[
            'columns'] = column_list_account  # We assign the column list to the widgets columns
        self.tv1["show"] = "headings"  # this hides the default column..

        self.load_to_TreeView()

        for column in column_list_account:  # foreach column
            self.tv1.heading(
                column, text=column)  # let the column heading = column name
            self.tv1.column(column, width=100)  # set the columns size to 50px
        self.tv1.place(
            relheight=0.9, relwidth=0.95
        )  # set the height and width of the widget to 100% of its container (frame1).
        treescroll = tk.Scrollbar(frame1)  # create a scrollbar
        treescroll.configure(command=self.tv1.yview)  # make it vertical
        self.tv1.configure(yscrollcommand=treescroll.set
                           )  # assign the scrollbar to the Treeview Widget
        hsb = Scrollbar(frame1, orient="horizontal", command=self.tv1.xview)
        hsb.place(relx=0.001, rely=0.9, relheight=0.1, relwidth=0.95)
        self.tv1.configure(xscrollcommand=treescroll.set
                           )  # assign the scrollbar to the Treeview Widget
        treescroll.pack(
            side="right", fill="y"
        )  # make the scrollbar fill the yaxis of the Treeview widget
        root.mainloop()  # The mainloop for our tkinter Gui
예제 #11
0
	def __addTextbox(self,dx=85,dy=24,x1=27,y=47,x2=624,sdy=430):
		scrolly=Scrollbar(self,activebackground="#171212",bg="#343838",orient=VERTICAL,troughcolor="#171212")
		listbox=Listbox(self,
						height=dy, 
						width=dx ,
						background="#343838",
						borderwidth=0,
						highlightcolor="#4d86a1",
						selectbackground="#4d86a1",
						activestyle=NONE,
						highlightbackground="#4a4a4a",
						yscrollcommand=scrolly.set)

		listbox.config(font=("", 10),fg="#FFFFFF")
		listbox.place(x=x1,y=y+21)
		scrolly.place(x=x2,y=y,height=sdy)	
		self.__list_listbox.append(listbox)
		self.__list_scrollbar.append(scrolly)
		
		listbox.configure(yscrollcommand=scrolly.set)
		scrolly.configure(command=listbox.yview)
예제 #12
0
    def __create_table(self) -> None:
        self.__student_list_table: ttk.Treeview = ttk.Treeview(self.__window)
        self.__student_list_table['show'] = 'headings'
        self.__student_list_table["columns"] = ("id", "name", "age", "sex", "major", "phone", "qq")
        self.__student_list_table["displaycolumns"] = ("name", "age", "sex", "major", "phone", "qq")
        self.__student_list_table.column("name", width=85)
        self.__student_list_table.column("age", width=40)
        self.__student_list_table.column("sex", width=40)
        self.__student_list_table.column("major", width=90)
        self.__student_list_table.column("phone", width=110)
        self.__student_list_table.column("qq", width=110)
        self.__student_list_table.heading("name", text="姓名")
        self.__student_list_table.heading("age", text="年龄")
        self.__student_list_table.heading("sex", text="性别")
        self.__student_list_table.heading("major", text="专业")
        self.__student_list_table.heading("phone", text="电话")
        self.__student_list_table.heading("qq", text="QQ")
        self.__student_list_table.place(x=10, y=180, height=400)

        table_scroll = Scrollbar(self.__window,
                                 orient='vertical',
                                 command=self.__student_list_table.yview)
        table_scroll.place(x=475, y=180, width=15, height=400)
        self.__student_list_table.configure(yscrollcommand=table_scroll.set)
class Lapchat:
    def __init__(self, master):
        master.title("Lapchat")
        master.resizable(False, False)
        master.geometry("400x450")
        #master.iconbitmap("4.ico")
        master.configure(bg="#3D9970")

        #==============Initializing communication==============
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = socket.gethostname()
        self.port = 12345
        self.client = (self.host, self.port)

        self.top_frame = Frame(master, width=400, height=45, bg="#6666ff")
        self.top_frame.place(x=0, y=0)

        self.message_count = 1.5
        self.filename = None

        self.message_session = Text(master,
                                    bd=3,
                                    relief="flat",
                                    font=("consolas", 12, "italic"),
                                    undo=True,
                                    wrap="word")
        self.message_session.config(width=35,
                                    height=15,
                                    bg="#AAAAAA",
                                    fg="blue")
        self.overscroll = Scrollbar(master, command=self.message_session.yview)
        self.overscroll.config(width=20)
        self.message_session["yscrollcommand"] = self.overscroll.set

        self.message = Entry(bg="#ffffff", width=30, bd=5, relief="flat")
        self.message.bind("<Return>", self.send_msg)

        self.send_message = Button(master,
                                   text="send",
                                   fg="blue",
                                   width=10,
                                   height=1,
                                   relief="flat")
        self.send_message.configure(command=self.send_msg)

        self.attachment = Button(master,
                                 text="File",
                                 fg="red",
                                 width=5,
                                 height=1,
                                 relief="flat")
        self.attachment.configure(command=self.select_file)

        self.file_label = Label(master,
                                fg="#008080",
                                font=("verdana", 7),
                                width=50)

        self.message_session.place(x=40, y=50)
        self.overscroll.place(x=360, y=50)
        self.message.place(x=40, y=345)
        self.send_message.place(x=240, y=345)
        self.attachment.place(x=325, y=345)

    def get_filename(self, folder):
        self.temp_filename = folder.split("/")
        self.temp_filename = self.temp_filename[-1]
        return self.temp_filename

    def select_file(self, event=None):
        self.select_file = filedialog.askopenfilename()
        self.filename = self.select_file
        self.temp_filename = self.get_filename(self.select_file)
        self.file_label.config(text=self.temp_filename)
        self.file_label.place(x=40, y=380)

    def receive_sms_txt(self, receive_txt=None):
        print("Receiving sms again")
        print(self.received_message)
        if receive_txt:
            self.sm = receive_txt
        else:
            self.sm = self.received_message
            self.message.delete(0, "end")
        self.sm = "client:" + self.sm + "\n"
        self.message_session.insert(self.message_count, self.sm)
        self.message_count += 1.5
        self.received_message = None

    def receive_file(self, size, name):
        with open(name, "wb") as rec_file:
            print(size)
            print(name)
            while size > 0:
                received_buffer = self.server.recv(1024)
                rec_file.write(received_buffer)
                size = size - len(received_buffer)
                print(size)

        print("File received successful")
        self.server.send(("ready_received").encode())
        self.received_message = None

    def try_sample1(self):
        self.receive_sms_thread = threading.Thread(target=self.receive_file,
                                                   args=(self.received_size,
                                                         self.received_name))
        self.receive_sms_thread.start()
        self.receive_sms_thread.join()

    def receive_sms(self):
        while True:
            try:
                self.server.connect(self.client)
                while True:
                    try:
                        print("receiving messages")
                        self.received_message = self.server.recv(1024).decode()
                        print(self.received_message)
                        if "&&&" in self.received_message:
                            self.received_message = self.received_message.split(
                                "&&&")
                            self.received_size = self.received_message[0]
                            self.received_name = self.received_message[1]
                            self.received_size = int(self.received_size)
                            self.receive_sms_txt(receive_txt="File Received")
                            self.try_sample1()

                        else:
                            if self.received_message:
                                self.receive_sms_txt()
                    except:
                        continue
            except:
                continue

    def send_sms_txt(self, file_message=None):
        if file_message:
            self.sms = file_message
        else:
            self.sms = self.message.get()
            self.server.send(self.sms.encode())
            self.message.delete(0, "end")

        self.sms = "you:" + self.sms + "\n"
        self.message_session.insert(self.message_count, self.sms)
        self.message_count += 1.5
        print("Message sent succeful")

    def send_file(self, size):
        print(size)
        with open(self.filename, "rb") as file:
            size = int(size)
            while size > 0:
                buffer = file.read()
                self.server.send(buffer)
                buffer_size = len(buffer)
                break
        print("File successful sent")

    def receive_sms_txt(self, receive_txt=None):
        print("Receiving sms again")
        print(self.received_message)
        if receive_txt:
            self.sm = receive_txt
        else:
            self.sm = self.received_message
            self.message.delete(0, "end")
        self.sm = "client:" + self.sm + "\n"
        self.message_session.insert(self.message_count, self.sm)
        self.message_count += 1.5
        self.received_message = None

    def try_sample(self):
        sendfile_thread = threading.Thread(target=self.send_file,
                                           args=(self.filesize, ))
        sendfile_thread.start()
        sendfile_thread.join()
        self.filename = None
        self.file_label.place_forget()
        print("Thread stopped")

    def send_msg(self, event=None):
        try:
            if self.filename:
                self.ask_send = messagebox.askyesno(
                    "Confirm", "Do want to send message with file")
                print(self.ask_send)
                if self.ask_send:
                    self.file_name = self.get_filename(self.filename)
                    self.filesize = str(os.stat(self.filename).st_size)
                    print("file size is : {}".format(self.filesize))
                    self.embedded_filename = self.filesize + "&&&" + self.file_name
                    self.send_sms_txt()
                    self.send_sms_txt(file_message="File has been sent")
                    self.server.send(self.embedded_filename.encode())
                    self.try_sample()
                else:
                    self.filename = None
                    self.file_label.place_forget()
                    self.send_sms_txt()

            else:
                self.send_sms_txt()

        except:
            self.show_error = messagebox.showerror(
                "No connection", "Time out , no connection found")
예제 #14
0
class main(Frame):
    def savePreviousValues(self):
        length = self.previousMatrixSize

        prevValues = [None for i in range(length**2)]

        # Сохраним в список предыдущие значения полей ввода
        for i in range(length):
            for j in range(length):
                prevValues[i * length + j] = self.inputsList[i * length +
                                                             j].get()

        return prevValues

    def savePreviousBValues(self):
        length = self.previousMatrixSize
        prevBValues = [None for i in range(length)]

        #print('prevMS: {}'.format(length))

        # Сохраним в список предыдущие значения полей ввода свободных членов
        for i in range(length):
            prevBValues[i] = self.inputsBList[i].get()

        return prevBValues

    def redrawInputs(self):
        # Сохраним значение старых инпутов
        self.prevValues = self.savePreviousValues()

        # Удалим старые инпуты
        for i in range(len(self.inputsList)):
            #self.inputsList[i].place_forget()
            self.inputsList[i].destroy()

        # Обнулим список инпутов
        self.inputsList = [None for i in range(self.currentMatrixSize**2)]

        # Отрисуем новые инпуты с сохранением значения старых, если есть
        for i in range(0, self.currentMatrixSize):
            self.currentY = 100 + 60 * i

            for j in range(0, self.currentMatrixSize):
                self.currentX = 100 + 100 * j

                obj = self.addInput(self.currentX, self.currentY)

                self.inputsList[i * self.currentMatrixSize + j] = obj

                valueOfCell = 0
                if (i < self.previousMatrixSize
                        and j < self.previousMatrixSize):
                    valueOfCell = self.prevValues[i * self.previousMatrixSize +
                                                  j]

                else:
                    valueOfCell = 0  #i * self.currentMatrixSize + j

                obj.insert(0, valueOfCell)

        # Повторим процедуру с инпутами свободных членов
        # Сохраним значение старых инпутов
        self.prevBValues = self.savePreviousBValues()

        # Удалим старые инпуты
        for i in range(len(self.inputsBList)):
            #self.inputsBList[i].place_forget()
            self.inputsBList[i].destroy()

        # Обнулим список инпутов
        self.inputsBList = [None for i in range(self.currentMatrixSize)]

        self.currentBX = 200 + self.currentMatrixSize * 100
        # Отрисуем новые инпуты с сохранением значения старых, если есть
        for i in range(0, self.currentMatrixSize):
            self.currentBY = 100 + 60 * i

            obj = self.addInput(self.currentBX, self.currentBY)

            self.inputsBList[i] = obj

            valueOfCell = 0
            if (i < self.previousMatrixSize):
                valueOfCell = self.prevBValues[i]

            obj.insert(0, valueOfCell)

        # Запомним текущий размер матрицы
        self.previousMatrixSize = self.currentMatrixSize

        self.scrollRegionWidth = 1000 + 100 * self.currentMatrixSize
        self.scrollRegionHeight = 1000 + 20 * self.currentMatrixSize

        self.canvas.configure(scrollregion=(0, 0, self.scrollRegionWidth,
                                            self.scrollRegionHeight))

        #self.scrolling_window.configure(width = self.scrollRegionWidth, height = self.scrollRegionHeight)

    def addInput(self, px, py):
        res_e = None

        res_e = Entry(self.scrolling_area, width=5, bd=3, font='times 15')
        res_e.place(x=px, y=py)

        return res_e

    def validateMatrixSize(self, event):
        text = self.n_input.get()
        res = ''
        length = len(text)
        for i in range(length):
            c = text[i]
            if (ord(c) >= 48 and ord(c) <= 57):
                res += c
        self.n_input.delete(0, length)
        self.n_input.insert(0, res)

        try:
            if (int(text) != self.currentMatrixSize):
                self.currentMatrixSize = int(text)

                self.redrawInputs()
        except (ValueError):
            pass

    def solveButtonClicked(self, event):
        m = self.currentMatrixSize

        delimiter = 0
        delimiter_i = 0
        matrix = []
        subMatrix = []

        # Сформируем матрицу для последующей отправки в модуль решения
        for i in range(len(self.inputsList)):
            try:
                subMatrix.append(float(self.inputsList[i].get()))
            except ValueError:
                print('Ошибка в заполнении ячейки [{},{}]'.format(
                    delimiter_i, delimiter))
                exit(1)
            delimiter += 1

            if (delimiter == m):
                try:
                    subMatrix.append(float(
                        self.inputsBList[delimiter_i].get()))
                except ValueError:
                    print(
                        'Ошибка в заполнении ячейки коэффициентов [{}]'.format(
                            delimiter_i))

                matrix.append(subMatrix)
                subMatrix = []
                delimiter = 0
                delimiter_i += 1

        s = solve.solve(matrix)

        messagebox.showwarning('Решение системы',
                               'Решение системы записано в файл "Ответ.txt".')

        out = open('Ответ.txt', encoding='utf-8', mode='w')

        for x in s:
            out.write(str(x) + '\n')
        out.close()

    def fileButtonClicked(self, event):

        try:
            file = open('src.txt', encoding='utf-8')
        except FileNotFoundError:
            messagebox.showerror('Ошибка', 'Файл "src.txt" не найден.')
        else:
            n = None
            matrix = []
            for line in file:
                mRow = line.split(',')
                if (n == None):
                    n = len(mRow)
                matrix.append(mRow)

            self.currentMatrixSize = n - 1
            self.redrawInputs()

            for i in range(self.currentMatrixSize):
                for j in range(self.currentMatrixSize):
                    ind = i * self.currentMatrixSize + j
                    self.inputsList[ind].delete(0,
                                                len(self.inputsList[i].get()))
                    self.inputsList[ind].insert(0, matrix[i][j])

                self.inputsBList[i].delete(0, len(self.inputsBList[i].get()))
                self.inputsBList[i].insert(0, matrix[i][n - 1])

            file.close()

    def __init__(self, master):
        self.master = master
        self.master.title('Решение СЛАУ')
        self.master.geometry('1245x510+70+70')
        self.master.minsize(width=1245, height=510)
        self.master.maxsize(width=1245, height=510)

        # Скроллбар для холста по вертикали
        self.scrollbar = Scrollbar(self.master, width=16)
        self.scrollbar.place(x=0, y=10, height=490)

        # Скроллбар для холста по горизонтали
        self.scrollbar_x = Scrollbar(self.master,
                                     width=16,
                                     orient='horizontal')
        self.scrollbar_x.place(x=16, y=0, width=1230)

        # Холст
        self.scrollRegionWidth = 1000
        self.scrollRegionHeight = 1000

        self.canvas = Canvas(self.master,
                             height=510,
                             width=1245,
                             yscrollcommand=self.scrollbar.set,
                             xscrollcommand=self.scrollbar_x.set,
                             scrollregion=(0, 0, self.scrollRegionWidth,
                                           self.scrollRegionHeight))
        self.canvas.place(x=16, y=100)

        # Скроллируемая область
        self.scrolling_area = Frame(self.canvas)
        self.canvas.create_window(0,
                                  0,
                                  window=self.scrolling_area,
                                  width=5000,
                                  height=5000,
                                  anchor='nw')

        # Связывание компонентов
        self.scrollbar.config(command=self.canvas.yview)
        self.scrollbar_x.config(command=self.canvas.xview)

        self.currentMatrixSize = 3
        self.previousMatrixSize = 0

        self.prevValues = []

        self.currentX = 0
        self.currentY = 0

        self.inputsList = []
        self.inputsBList = []

        self.test = 0

        # Поле для ввода n-параметра матрицы
        self.n_input = Entry(self.master, width=20, bd=3, font='times 15')
        self.n_input.place(x=500, y=50)
        self.n_input.bind('<KeyRelease>', self.validateMatrixSize)

        self.n_input_label = Label(self.master, text='Размер матрицы')
        self.n_input_label.place(x=500, y=25)

        # Кнопка "решить"
        self.solve_button = Button(self.master,
                                   width=20,
                                   bd=3,
                                   font='times 15',
                                   text="Решить систему")
        self.solve_button.place(x=100, y=50)
        self.solve_button.bind('<Button-1>', self.solveButtonClicked)

        # Кнопка "заполнить из файла"
        self.file_button = Button(self.master,
                                  width=20,
                                  bd=3,
                                  font='times 15',
                                  text="Взять данные из файла")
        self.file_button.place(x=900, y=50)
        self.file_button.bind('<Button-1>', self.fileButtonClicked)

        self.redrawInputs()
예제 #15
0
class CadastroVeiculo:
    '''Classe interface cadastrar veiculo'''
    def __init__(self, master=''):
        self.master = master
        self.veiculo = Veiculo()
        self.dao = VeiculoDAO()
        '''
       self.window = Tk()
       self.window.geometry('1350x850+0+0')
       self.window.title('Cadastro de veículo')
       self.window.resizable(0, 0)  # impede de maximizar
       self.window['bg'] = '#c9c9ff'
       '''
        self.heading = Label(self.master,
                             text="Cadastro de Veiculos",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=650, y=0)

        # marca =========================================================================
        self.marca = Label(self.master,
                           text="Marca do veículo :",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.marca.place(x=10, y=70)
        self.marca_entry = Entry(self.master,
                                 width=35,
                                 font=('Verdana 15 bold'))
        self.marca_entry.place(x=300, y=70)

        # modelo =========================================================================
        self.modelo = Label(self.master,
                            text="Modelo:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.modelo.place(x=10, y=120)
        self.modelo_entry = Entry(self.master,
                                  width=35,
                                  font=('Verdana 15 bold'))
        self.modelo_entry.place(x=300, y=120)

        # ano =========================================================================
        self.ano = Label(self.master,
                         text="Ano:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.ano.place(x=10, y=170)
        self.ano_entry = Entry(self.master, width=35, font=('Verdana 15 bold'))
        self.ano_entry.place(x=300, y=170)

        # cor =========================================================================
        self.cor = Label(self.master,
                         text="Cor:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cor.place(x=10, y=220)
        self.cor_entry = Entry(self.master, width=35, font=('Verdana 15 bold'))
        self.cor_entry.place(x=300, y=220)
        # self.cor_entry.insert(END, datetime.date.today())

        # tanque =========================================================================
        self.tanque = Label(self.master,
                            text="Capacidade do tanque:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.tanque.place(x=10, y=270)
        self.tanque_entry = Entry(self.master,
                                  width=35,
                                  font=('Verdana 15 bold'))
        self.tanque_entry.place(x=300, y=270)
        self.tanque_entry.insert(END, "litros")

        # combustivel =========================================================================
        self.combustivel = Label(self.master,
                                 text="Tipo de Combustível:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.combustivel.place(x=10, y=320)
        self.combustivel_entry = Entry(self.master,
                                       width=35,
                                       font=('Verdana 15 bold'))
        self.combustivel_entry.place(x=300, y=320)

        # consumo cidade =========================================================================
        self.consumo_cidade = Label(self.master,
                                    text="Consumo na cidade:",
                                    bg='#c9c9ff',
                                    fg='white',
                                    font=('Verdana 15 bold'))
        self.consumo_cidade.place(x=10, y=370)
        self.consumo_cidade_entry = Entry(self.master,
                                          width=35,
                                          font=('Verdana 15 bold'))
        self.consumo_cidade_entry.place(x=300, y=370)

        self.consumo_cidade_entry.insert(END, "l/km")

        self.consumo_estrada = Label(self.master,
                                     text="Consumo na estrada:",
                                     bg='#c9c9ff',
                                     fg='white',
                                     font=('Verdana 15 bold'))
        self.consumo_estrada.place(x=10, y=420)
        self.consumo_estrada_entry = Entry(self.master,
                                           width=35,
                                           font=('Verdana 15 bold'))
        self.consumo_estrada_entry.place(x=300, y=420)
        self.consumo_estrada_entry.insert(END, "l/km")

        self.tempo_0_100 = Label(self.master,
                                 text="Tempo de 0km/h a 100km/h:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.tempo_0_100.place(x=10, y=470)
        self.tempo_0_100_entry = Entry(self.master,
                                       width=35,
                                       font=('Verdana 15 bold'))
        self.tempo_0_100_entry.place(x=300, y=470)

        self.chassi = Label(self.master,
                            text="Chassi:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.chassi.place(x=10, y=520)
        self.chassi_entry = Entry(self.master,
                                  width=35,
                                  font=('Verdana 15 bold'))
        self.chassi_entry.place(x=300, y=520)

        self.placa = Label(self.master,
                           text="Placa:",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.placa.place(x=10, y=570)
        self.placa_entry = Entry(self.master,
                                 width=35,
                                 font=('Verdana 15 bold'))
        self.placa_entry.place(x=300, y=570)

        self.tamanho_pneu = Label(self.master,
                                  text="Tamanho do pneu:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.tamanho_pneu.place(x=10, y=620)
        self.tamanho_pneu_entry = Entry(self.master,
                                        width=35,
                                        font=('Verdana 15 bold'))
        self.tamanho_pneu_entry.place(x=300, y=620)

        self.som = Label(self.master,
                         text="Som:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.som.place(x=10, y=670)
        self.som_entry = Entry(self.master, width=35, font=('Verdana 15 bold'))
        self.som_entry.place(x=300, y=670)

        self.valor_diaria = Label(self.master,
                                  text="valor da diária:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.valor_diaria.place(x=10, y=720)
        self.valor_diaria_entry = Entry(self.master,
                                        width=35,
                                        font=('Verdana 15 bold'))
        self.valor_diaria_entry.place(x=300, y=720)
        self.valor_diaria_entry.insert(END, 'R$ ')

        # BOTAO LIMPAR  =========================================================================
        self.botao_limpar = Button(self.master,
                                   text="Limpar",
                                   width=18,
                                   height=1,
                                   bg='#ffdfba',
                                   fg='black',
                                   font=('Verdana 15 bold'),
                                   command=self.clear_all)
        self.botao_limpar.place(x=800, y=700)

        self.botao_cadastrar = Button(self.master,
                                      text="Cadastrar",
                                      width=37,
                                      height=1,
                                      bg='#baffc9',
                                      fg='black',
                                      font=('Verdana 15 bold'),
                                      command=self.get_items)
        self.botao_cadastrar.place(x=800, y=650)

        self.botao_sair = Button(self.master,
                                 text="Sair",
                                 width=18,
                                 height=1,
                                 bg='#ffb3ba',
                                 fg='black',
                                 font=('Verdana 15 bold'),
                                 command=self.close)
        self.botao_sair.place(x=1070, y=700)

        self.veiculo_box = Listbox(self.master,
                                   width=38,
                                   height=20,
                                   font=('Verdana 15 bold'))
        self.veiculo_box.place(x=800, y=120)

        self.scrollbar_veiculo = Scrollbar(self.master)
        self.veiculo_box.configure(yscrollcommand=self.scrollbar_veiculo.set)
        self.scrollbar_veiculo.configure(command=self.veiculo_box.yview)
        self.scrollbar_veiculo.place(x=1340,
                                     y=120,
                                     relheight=0.62,
                                     anchor='ne')

        self.pesquisar_veiculo = Label(self.master,
                                       text="Lista de veiculos Cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_veiculo.place(x=900, y=75)
        self.update_list()

    def update_list(self):
        try:
            self.veiculo_box.delete(0, END)
            for item in self.dao.view():
                self.veiculo_box.insert(END, item)
        except Exception:
            print('Erro na lista veiculos.')

    def get_items(self):
        self.veiculo.marca = self.marca_entry.get()
        self.veiculo.modelo = self.modelo_entry.get()
        self.veiculo.ano = self.ano_entry.get()
        self.veiculo.cor = self.cor_entry.get()
        self.veiculo.tanque = self.tanque_entry.get()
        self.veiculo.combustivel = self.combustivel_entry.get()
        self.veiculo.consumo_cidade = self.consumo_cidade_entry.get()
        self.veiculo.consumo_estrada = self.consumo_estrada_entry.get()
        self.veiculo.tempo_0_100 = self.tempo_0_100_entry.get()
        self.veiculo.chassi = self.chassi_entry.get()
        self.veiculo.placa = self.placa_entry.get()
        self.veiculo.tamanho_pneu = self.tamanho_pneu_entry.get()
        self.veiculo.som = self.som_entry.get()
        self.veiculo.valor_diaria = self.valor_diaria_entry.get()

        if (self.veiculo.marca == '' or self.veiculo.modelo == ''
                or self.veiculo.ano == '' or self.veiculo.cor == ''
                or self.veiculo.tanque == '' or self.veiculo.combustivel == ''
                or self.veiculo.consumo_cidade == ''
                or self.veiculo.consumo_estrada == ''
                or self.veiculo.tempo_0_100 == '' or self.veiculo.chassi == ''
                or self.veiculo.placa == '' or self.veiculo.tamanho_pneu == ''
                or self.veiculo.som == '' or self.veiculo.valor_diaria == ''):
            tkinter.messagebox.showinfo(
                "Aviso:", "POR FAVOR PREENCHER TODOS OS CAMPOS!")
        else:
            try:
                self.veiculo.tanque = float(self.veiculo.tanque)
                self.veiculo.consumo_cidade = float(
                    self.veiculo.consumo_cidade)
                self.veiculo.consumo_estrada = float(
                    self.veiculo.consumo_estrada)
                self.veiculo.tempo_0_100 = float(self.veiculo.tempo_0_100)
                self.veiculo.valor_diaria = float(self.veiculo.valor_diaria)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'Os campos tamanho do tanque, Consumo na cidade, consumo ma estrada, tempo_0_100 e valor da diária devem ser preenchidos com números!'
                )
            else:
                try:
                    self.dao.insert(self.veiculo)
                except Exception as e:
                    print(e)
                else:
                    tkinter.messagebox.showinfo(
                        'Aviso!', 'Cadastro Realizado com Sucesso!')
                    self.clear_all()
                    self.update_list()

    def clear_all(self):
        self.marca_entry.delete(0, END)
        self.modelo_entry.delete(0, END)
        self.ano_entry.delete(0, END)
        self.cor_entry.delete(0, END)
        self.tanque_entry.delete(0, END)
        self.tanque_entry.insert(END, "litros")

        self.combustivel_entry.delete(0, END)

        self.consumo_cidade_entry.delete(0, END)
        self.consumo_cidade_entry.insert(END, "l/km")

        self.consumo_estrada_entry.delete(0, END)
        self.consumo_estrada_entry.insert(END, "l/km")

        self.tempo_0_100_entry.delete(0, END)
        self.tempo_0_100_entry.insert(END, "segundos")

        self.chassi_entry.delete(0, END)
        self.placa.delete(0, END)
        self.tamanho_pneu.delete(0, END)
        self.som.delete(0, END)
        self.valor_diaria.delete(0, END)
        self.valor_diaria_entry.insert(END, 'R$ ')

    def close(self):
        self.dao.close()
        self.window.destroy()

    def run(self):
        self.window.mainloop()
예제 #16
0
class Terminal:
    def __init__(self, window):

        window.title('Unlock MS Files')
        window.geometry('400x500')
        window.resizable(0, 0)

        self.message_position = 1.5

        self.message_window = Entry(window, width=30, font=('Times', 12))
        self.message_window.bind('<Return>', self.submit_update)
        self.message_window.place(x=128, y=400, height=88, width=260)

        self.chat_window = Text(window,
                                bd=3,
                                relief="flat",
                                font=("Times", 10),
                                undo=True,
                                wrap="word")
        self.chat_window.place(x=6, y=6, height=385, width=370)
        self.overscroll = Scrollbar(window, command=self.chat_window.yview)
        self.overscroll.place(x=375, y=5, height=385)

        self.chat_window["yscrollcommand"] = self.overscroll.set

        self.send_button = Button(window,
                                  text='Unlock->',
                                  fg='white',
                                  bg='grey',
                                  width=12,
                                  height=5,
                                  font=('Times', 12),
                                  relief='flat',
                                  command=self.submit_update)
        self.send_button.place(x=6, y=400, height=88)

        # Instructions Here
        self.update_text_screen('Steps:\n')
        self.update_text_screen(
            '1. Enter the path/filename.xlsx or path/filelist.txt\n')
        self.update_text_screen(
            '2. Press Unlock and see unlocked folder in root directory.\n')

    def update_text_screen(self, message):
        self.message_position += 1.5
        print(self.message_position)
        self.message_window.delete(0, 'end')
        self.chat_window.config(state='normal')
        self.chat_window.insert(self.message_position, message)
        self.chat_window.see('end')
        self.chat_window.config(state='disabled')

    def submit_update(self, event=None):
        """
        Creates the directory structure if it doesn't already exist.
        """
        if not os.path.exists(APP_SAVE_DIR):
            os.mkdir(APP_SAVE_DIR)

        if not os.path.exists(APP_TEMP_DIR):
            os.mkdir(APP_TEMP_DIR)

        filepath = [self.message_window.get()]
        filepath_check = filepath
        message = self.message_window.get()
        message = f'You: {message} \n'
        reply = 'Bot: MS Unlocker started\n'

        self.update_text_screen(message)
        self.update_text_screen(reply)
        for fp in filepath_check:
            ext = os.path.splitext(fp)[-1].lower()
            if ext == '.txt':
                reply = 'Bot: .txt submitted - assuming List mode...\n'
                self.update_text_screen(reply)
                filepaths = [line.rstrip() for line in open(fp, 'r')]

                reply = f'Bot: {len(filepaths)} files detected\n'
                self.update_text_screen(reply)
            else:
                filepaths = filepath

        files_unlocked = 0
        for locked_filepath in filepaths:
            reply = f'Bot: Checking file {locked_filepath}...\n'
            self.update_text_screen(reply)

            if os.path.isfile(locked_filepath):
                file_info = FileInfo(locked_filepath)

                # Checks the extension of the file against the dictionary of
                # supported applications, returning the application name.
                try:
                    detected_application = SUPPORTED_EXTENSIONS[
                        file_info.extension]
                except:
                    detected_application = 'Bot: unsupported file type\n'

                # Uses the deteted application to create the correct instance.
                if detected_application == MICROSOFT_EXCEL:
                    cxl = MicrosoftExcel(locked_filepath)
                elif detected_application == MICROSOFT_WORD:
                    cxl = MicrosoftWord(locked_filepath)
                elif detected_application == MICROSOFT_POWERPOINT:
                    cxl = MicrosoftPowerpoint(locked_filepath)
                elif file_info.extension == '.txt':
                    reply = 'Bot: File rejected. Did you mean to upload a list.txt?\n'
                    self.update_text_screen(reply)
                    break
                else:
                    reply = 'Bot: File rejected. Unsupported file extension.\n'
                    self.update_text_screen(reply)
                    break

                reply = 'Bot: File accepted...\n'
                self.update_text_screen(reply)

                try:
                    cxl.unlock()
                    reply = 'Completed unlocking file!\n'
                    self.update_text_screen(reply)

                    files_unlocked += 1
                except Exception:
                    reply = f'Bot: An error occured while unlocking {locked_filepath}\n'
                    self.update_text_screen(reply)
            else:
                reply = '\nBot: File not found...'
                self.update_text_screen(reply)

            if locked_filepath.endswith('.xlsm'):
                reply = 'Bot: Macro identified...\n'
                self.update_text_screen(reply)
                reply = 'When opening these types of files in MS-Office:\n'
                self.update_text_screen(reply)
                reply = '1. If popup comes up - select Yes\n'
                self.update_text_screen(reply)
                reply = '2. Click Enable Macros if prompted\n'
                self.update_text_screen(reply)
                reply = '3. Go to Dev tab-Visual Basic\n'
                self.update_text_screen(reply)
                reply = '4. On new screen click Tools\n'
                self.update_text_screen(reply)
                reply = '5. Select VBA Project Properties\n'
                self.update_text_screen(reply)
                reply = '6. Enter a new password and save\n'
                self.update_text_screen(reply)
                reply = '7. You should be able to access the macro code now\n'
                self.update_text_screen(reply)

        reply = f'\nBot: Summary: {files_unlocked}/{len(filepaths)} files unlocked\n'
        self.update_text_screen(reply)
        reply = '\nBot: MS Unlocker finished'
        self.update_text_screen(reply)
예제 #17
0
class TkMainMenu(Frame):
    def __init__(self, _master_: Frame, _editor_: bool = False):
        super().__init__(master=_master_,
                         bg='darkgray',
                         borderwidth=2,
                         relief="groove")
        self._master = _master_
        self._scenarios_path = 'scenarios/'
        self._open_function = functions['new_game']
        self._editor_mode = _editor_

        self._build()
        self._get_scenarios()
        self.place()
        self.resize()
        pass

    def place(self):
        self._master.update()
        super().place(in_=self._master, anchor=N, relx=0.5, y=50)
        pass

    def resize(self):
        self.config(width=700, height=600)

    def _build(self):
        if self._editor_mode:
            self._new_button = Button(master=self,
                                      text='Nowy scenariusz',
                                      command=self._on_new)
            self._new_button.place(in_=self,
                                   width=450,
                                   height=40,
                                   anchor=N,
                                   relx=0.5,
                                   y=10)
            pass

        self._open_button = Button(master=self,
                                   text='Otwórz scenariusz',
                                   command=self._on_open,
                                   state=DISABLED)
        self._open_button.place(in_=self,
                                width=450,
                                height=40,
                                anchor=N,
                                relx=0.5,
                                y=60)

        self._listbox_frame = Frame(master=self, width=170, height=300)
        self._listbox_frame.place(in_=self,
                                  width=550,
                                  height=480,
                                  anchor=N,
                                  relx=0.5,
                                  y=110)
        self._listbox = Listbox(self)
        self._listbox.bind("<<ListboxSelect>>", self._on_select)
        self._listbox.place(in_=self._listbox_frame,
                            width=530,
                            height=480,
                            anchor=NW,
                            relx=0)
        self._scrollbar = Scrollbar(self,
                                    orient='vertical',
                                    command=self._listbox.yview)
        self._scrollbar.place(in_=self._listbox_frame,
                              height=480,
                              anchor=NE,
                              relx=1)
        self._listbox.config(yscrollcommand=self._scrollbar.set)
        pass

    def _get_scenarios(self):
        self._scenarios = list()
        if not isdir(self._scenarios_path):
            makedirs(self._scenarios_path)
        for file_name in listdir(self._scenarios_path):
            if not isfile(self._scenarios_path + file_name):
                continue
            with open(self._scenarios_path + file_name, 'r') as file:
                line = file.readline(100)
                found = re.search(r'name="(.*?)"', line)
                if found:
                    self._scenarios.append(file_name[0:len(file_name) - 4])
                    self._listbox.insert('end',
                                         f'{found.group(1)} ({file_name})')
                pass
            pass
        pass

    def _on_new(self, _event_=None):
        self._open_function(None)
        pass

    def _on_open(self, _event_=None):
        if self._listbox.curselection():
            file_path = self._scenarios[self._listbox.curselection()[0]]
            if isfile(f'{self._scenarios_path}{file_path}.xml'):
                self._open_function(file_path)
                pass
            else:
                self._open_button.config(state=DISABLED)
                self._listbox.delete(self._listbox.curselection())
            pass
        pass

    def _on_select(self, _event_=None):
        if self._listbox.curselection():
            self._open_button.config(state=NORMAL)
            pass
        else:
            self._open_button.config(state=DISABLED)
            pass
        pass

    pass
예제 #18
0
class customer(Frame):
    def __init__(self, master, **kwarks):
        Frame.__init__(self, master, **kwarks)
        self.font = font.Font(family="Roboto", size=33)

    def customerPage(self, event=None):
        self.CustomerFrame = Frame(self,
                                   width=1286,
                                   height=841,
                                   background="#FDFEFE")
        self.CustomerFrame.pack()
        self.distributor_txt = ttk.Label(self.CustomerFrame,
                                         text="ADD CUSTOMER",
                                         background="#FDFEFE",
                                         foreground="#0077FF",
                                         font=self.font)
        self.distributor_txt.place(x=35, y=5)

        self.CustomerName = StringVar()
        self.ShopName = StringVar()
        self.PhoneName = StringVar()

        self.NameEntry = ttk.Entry(self.CustomerFrame,
                                   textvar=self.CustomerName,
                                   foreground="#7f8c8d",
                                   width=23,
                                   font=("Helvetica", 20))
        self.NameEntry.place(x=60, y=100, height=50)
        self.NameEntry.insert(0, " Customer Name")

        self.CompanyEntry = ttk.Entry(self.CustomerFrame,
                                      textvar=self.ShopName,
                                      foreground="#7f8c8d",
                                      width=23,
                                      font=("Helvetica", 20))
        self.CompanyEntry.place(x=60, y=175, height=50)
        self.CompanyEntry.insert(0, " Company Name")

        self.AddressEntry = Text(self.CustomerFrame,
                                 foreground="#7f8c8d",
                                 width=23,
                                 font=("Helvetica", 20),
                                 relief="ridge")
        self.AddressEntry.place(x=60, y=250, height=100)
        self.AddressEntry.insert(END, " Address")

        self.PhoneEntry = ttk.Entry(self.CustomerFrame,
                                    textvar=self.PhoneName,
                                    foreground="#7f8c8d",
                                    width=23,
                                    font=("Helvetica", 20))
        self.PhoneEntry.place(x=60, y=370, height=50)
        self.PhoneEntry.insert(0, " Phone Number")

        self.distributor_con = ttk.Label(self.CustomerFrame,
                                         text="CUSTOMER",
                                         background="#FDFEFE",
                                         foreground="#0077FF",
                                         font=self.font)
        self.distributor_con.place(x=530, y=8)
        #self.showFrame = Text(self.CustomerFrame, height = 37, width = 69, background = "white", state = DISABLED)
        self.showFrame = Canvas(self.CustomerFrame,
                                height=595,
                                width=550,
                                background="white")
        self.showFrame.place(x=530, y=99)
        self.Scrollshow = Scrollbar(self.CustomerFrame)
        self.Scrollshow.place(x=1075, y=99, height=600)

        self.NameEntry.bind("<FocusIn>", lambda idc: self.RemovePlace("Name"))
        self.NameEntry.bind("<FocusOut>", lambda idc: self.InsertPlace("Name"))
        self.NameEntry.bind("<Return>",
                            lambda idc: self.FocusEntryForCus("Name"))

        self.CompanyEntry.bind("<FocusIn>",
                               lambda idc: self.RemovePlace("Company"))
        self.CompanyEntry.bind("<FocusOut>",
                               lambda idc: self.InsertPlace("Company"))
        self.CompanyEntry.bind("<Return>",
                               lambda idc: self.FocusEntryForCus("Company"))

        self.PhoneEntry.bind("<FocusIn>",
                             lambda idc: self.RemovePlace("Phone"))
        self.PhoneEntry.bind("<FocusOut>",
                             lambda idc: self.InsertPlace("Phone"))

        self.AddressEntry.bind("<FocusIn>",
                               lambda idc: self.RemovePlace("Address"))
        self.AddressEntry.bind("<FocusOut>",
                               lambda idc: self.InsertPlace("Address"))
        self.AddressEntry.bind("<Return>",
                               lambda idc: self.FocusEntryForCus("Address"))

        with sql.connect(position + "/Pass/" +
                         "Customer-data.db") as CustomerData:
            CD = CustomerData.cursor()
            CD.execute(
                ''' CREATE TABLE IF NOT EXISTS Customer(NUM INT, CUSTOMERNAME TEXT NOT NULL PRIMARY KEY, COMPANYNAME TEXT, COMPANYADDRESS TEXT, PHONENUMBER TEXT) '''
            )
            CustomerData.commit()

        MemberShow(self).ShowThat(name="Customer")

        def updateChange(event):
            if str(event)[1:6] == "Enter":
                ImageName = "/Requirements/UpdateUp.png"
            elif str(event)[1:6] == "Leave":
                ImageName = "/Requirements/UpdateUp.png"
                ImageName = "/Requirements/Update.png"
            self.CustomerImageChange = PhotoImage(file=position + ImageName)
            self.updateCustomer.configure(image=self.CustomerImageChange)
            self.updateCustomer.image = self.CustomerImageChange

        self.CustomerImage = PhotoImage(file=position +
                                        "/Requirements/Update.png")
        self.updateCustomer = ttk.Label(self.CustomerFrame,
                                        image=self.CustomerImage,
                                        background="white")
        self.updateCustomer.image = self.CustomerImage
        self.updateCustomer.place(x=60, y=470)

        self.updateCustomer.bind("<Enter>", updateChange)
        self.updateCustomer.bind("<Leave>", updateChange)
        self.updateCustomer.bind("<Button-1>", self.CustomerUpdate)

        def TotDeb(event):
            if str(event)[1:6] == "Enter":
                ImageName = "/Requirements/TotDebUp.png"
            elif str(event)[1:6] == "Leave":
                ImageName = "/Requirements/TotDeb.png"
            self.CustomerImageChange = PhotoImage(file=position + ImageName)
            self.TotDebCustomer.configure(image=self.CustomerImageChange)
            self.TotDebCustomer.image = self.CustomerImageChange

        self.CustomerImage = PhotoImage(file=position +
                                        "/Requirements/TotDeb.png")
        self.TotDebCustomer = ttk.Label(self.CustomerFrame,
                                        image=self.CustomerImage,
                                        background="white")
        self.TotDebCustomer.image = self.CustomerImage
        self.TotDebCustomer.place(x=60, y=570)

        self.TotDebCustomer.bind("<Enter>", TotDeb)
        self.TotDebCustomer.bind("<Leave>", TotDeb)
        self.TotDebCustomer.bind("<Button-1>", self.CustomerTotDeb)

    def FocusEntryForCus(self, EntryBox):
        if EntryBox == "Company":
            self.AddressEntry.focus()
        elif EntryBox == "Name":
            self.CompanyEntry.focus()
        elif EntryBox == "Address":
            self.PhoneEntry.focus()

    def RemovePlace(self, IdCheck):
        self.NamePer = self.CustomerName.get()
        self.NameSh = self.ShopName.get()
        self.NamePho = self.PhoneName.get()
        self.NameAddress = self.AddressEntry.get("1.0", "end-1c")

        if IdCheck == "Name":
            if self.NamePer == " Customer Name":
                self.NameEntry.delete(0, END)
                self.NameEntry.config(foreground="black")
        elif IdCheck == "Company":
            if self.NameSh == " Company Name":
                self.CompanyEntry.delete(0, END)
                self.CompanyEntry.config(foreground="black")
        elif IdCheck == "Phone":
            if self.NamePho == " Phone Number":
                self.PhoneEntry.delete(0, END)
                self.PhoneEntry.config(foreground="black")
        elif IdCheck == "Address":
            if self.NameAddress == " Address":
                self.AddressEntry.delete("1.0", END)
                self.AddressEntry.config(foreground="black")

    def InsertPlace(self, IdCheck):
        self.NamePer = self.CustomerName.get()
        self.NameSh = self.ShopName.get()
        self.NamePho = self.PhoneName.get()
        self.NameAddress = self.AddressEntry.get("1.0", "end-1c")

        if IdCheck == "Name":
            if self.NamePer == '':
                self.NameEntry.config(foreground="#7f8c8d")
                self.NameEntry.insert(0, " Customer Name")
        elif IdCheck == "Company":
            if self.NameSh == '':
                self.CompanyEntry.config(foreground="#7f8c8d")
                self.CompanyEntry.insert(0, " Company Name")
        elif IdCheck == "Phone":
            if self.NamePho == '':
                self.PhoneEntry.config(foreground="#7f8c8d")
                self.PhoneEntry.insert(0, " Phone Number")
        elif IdCheck == "Address":
            if self.NameAddress == "":
                self.AddressEntry.config(foreground="#7f8c8d")
                self.AddressEntry.insert(END, " Address")

    def CustomerUpdate(self, event):
        self.NamePer = self.CustomerName.get()
        if self.NamePer == " Customer Name":
            self.NamePer = ' '
        self.NameSh = self.ShopName.get()
        if self.NameSh == " Company Name":
            self.NameSh = ' '
        self.AddressNameForCus = self.AddressEntry.get("1.0", "end-1c")
        if self.AddressNameForCus == " Address":
            self.AddressNameForCus = ' '
        self.NamePho = self.PhoneName.get()
        if self.NamePho == " Phone Number":
            self.NamePho = ' '
        with sql.connect(position + "/Pass/" +
                         "Customer-data.db") as CustomerData:
            try:
                CD = CustomerData.cursor()
                CD.execute(
                    ''' CREATE TABLE IF NOT EXISTS %s(NUM INT, DateData DATE, RS TEXT, PRODUCT TEXT, NOM TEXT, NET TEXT, TOTAL TEXT)'''
                    % self.NamePer)
                CD.execute(
                    ''' CREATE TABLE IF NOT EXISTS %s(NUM INT, DateData DATE, TOTAL TEXT, DEBIT TEXT, CREDITED TEXT)'''
                    % (self.NamePer + "MONEY"))
                CD.execute('''SELECT * FROM Customer''')
                CustomerNumdata = len(CD.fetchall())

                CD.execute(
                    ''' INSERT INTO Customer(NUM, CUSTOMERNAME, COMPANYNAME, COMPANYADDRESS, PHONENUMBER)
                            VALUES(?, ?, ?, ?, ?)''',
                    (CustomerNumdata + 1, self.NamePer, self.NameSh,
                     self.AddressNameForCus, self.NamePho))
                CustomerData.commit()
                self.NameEntry.delete(0, END)
                self.CompanyEntry.delete(0, END)
                self.AddressEntry.delete("1.0", END)
                self.PhoneEntry.delete(0, END)
                self.CompanyEntry.config(foreground="#7f8c8d")
                self.PhoneEntry.config(foreground="#7f8c8d")
                self.AddressEntry.config(foreground="#7f8c8d")
                self.CompanyEntry.insert(0, " Company Name")
                self.PhoneEntry.insert(0, " Phone Number")
                self.AddressEntry.insert(END, " Address")
                self.NameEntry.focus()
                MemberShow(self).ShowThat(name="Customer")

            except:
                self.bell()

    def CustomerTotDeb(self, event):
        Debit.TotDeb("Customer")

    def ChangeWindow(self):
        if self.ChangingDict["Pos"] == "Pro":
            self.InsideOfShowCustomer(self.Name)
        elif self.ChangingDict["Pos"] == "Money":
            self.CustomerMoney(self.Name)

    def ChangeUpdateRound(self):
        if self.ChangingDict["Pos"] == "Pro":
            self.UpdateMoneyFirst(self.Name)
        elif self.ChangingDict["Pos"] == "Money":
            self.UpdateFirst(self.Name)
예제 #19
0
class CadastroCliente:
    '''Classe interface cadastrar cliente'''
    def __init__(self, master=''):
        self.master = master
        self.cliente = Cliente()
        self.dao = ClienteDAO()
        '''
        self.window = Tk()
        self.window.geometry('1500x850+0+0')
        self.window.title('Cadastro de cliente')
        self.window.resizable(0, 0)  # impede de maximizar
        self.window['bg'] = '#c9c9ff'
        '''
        self.heading = Label(self.master,
                             text="Cadastro de Clientes",
                             bg='#c9c9ff',
                             fg='white',
                             font=('Verdana 20 bold'))
        self.heading.place(x=650, y=0)

        # nome =========================================================================
        self.nome = Label(self.master,
                          text="Nome:",
                          bg='#c9c9ff',
                          fg='white',
                          font=('Verdana 15 bold'))
        self.nome.place(x=30, y=70)
        self.nome_entry = Entry(self.master,
                                width=15,
                                font=('Verdana 15 bold'))
        self.nome_entry.place(x=175, y=70)

        # rg =========================================================================
        self.rg = Label(self.master,
                        text="rg:",
                        bg='#c9c9ff',
                        fg='white',
                        font=('Verdana 15 bold'))
        self.rg.place(x=30, y=120)
        self.rg_entry = Entry(self.master, width=15, font=('Verdana 15 bold'))
        self.rg_entry.place(x=175, y=120)

        # cpf =========================================================================
        self.cpf = Label(self.master,
                         text="cpf:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cpf.place(x=30, y=170)
        self.cpf_entry = Entry(self.master, width=15, font=('Verdana 15 bold'))
        self.cpf_entry.place(x=175, y=170)

        # email =========================================================================
        self.email = Label(self.master,
                           text="email:",
                           bg='#c9c9ff',
                           fg='white',
                           font=('Verdana 15 bold'))
        self.email.place(x=30, y=220)
        self.email_entry = Entry(self.master,
                                 width=15,
                                 font=('Verdana 15 bold'))
        self.email_entry.place(x=175, y=220)
        # self.email_entry.insert(END, datetime.date.today())

        # telefone =========================================================================
        self.telefone = Label(self.master,
                              text="Telefone:",
                              bg='#c9c9ff',
                              fg='white',
                              font=('Verdana 15 bold'))
        self.telefone.place(x=30, y=270)
        self.telefone_entry = Entry(self.master,
                                    width=15,
                                    font=('Verdana 15 bold'))
        self.telefone_entry.place(x=175, y=270)
        self.telefone_entry.insert(END, "litros")

        # nascimento =========================================================================
        self.nascimento = Label(self.master,
                                text="Nascimento:",
                                bg='#c9c9ff',
                                fg='white',
                                font=('Verdana 15 bold'))
        self.nascimento.place(x=30, y=320)
        self.nascimento_entry = Entry(self.master,
                                      width=15,
                                      font=('Verdana 15 bold'))
        self.nascimento_entry.place(x=175, y=320)

        # consumo cidade =========================================================================
        self.estado_civil = Label(self.master,
                                  text="Estado civil:",
                                  bg='#c9c9ff',
                                  fg='white',
                                  font=('Verdana 15 bold'))
        self.estado_civil.place(x=30, y=370)
        self.estado_civil_entry = Entry(self.master,
                                        width=15,
                                        font=('Verdana 15 bold'))
        self.estado_civil_entry.place(x=175, y=370)

        self.estado_civil_entry.insert(END, "l/km")

        self.genero = Label(self.master,
                            text="Gênero:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.genero.place(x=30, y=420)
        self.genero_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.genero_entry.place(x=175, y=420)
        self.genero_entry.insert(END, "l/km")

        # direito ==============================
        self.cep = Label(self.master,
                         text="CEP:",
                         bg='#c9c9ff',
                         fg='white',
                         font=('Verdana 15 bold'))
        self.cep.place(x=550, y=70)
        self.cep_entry = Entry(self.master, width=15, font=('Verdana 15 bold'))
        self.cep_entry.place(x=730, y=70)

        self.estado = Label(self.master,
                            text="Estado:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.estado.place(x=550, y=120)
        self.estado_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.estado_entry.place(x=730, y=120)

        self.logradouro = Label(self.master,
                                text="Logradouro:",
                                bg='#c9c9ff',
                                fg='white',
                                font=('Verdana 15 bold'))
        self.logradouro.place(x=550, y=170)
        self.logradouro_entry = Entry(self.master,
                                      width=15,
                                      font=('Verdana 15 bold'))
        self.logradouro_entry.place(x=730, y=170)

        self.bairro = Label(self.master,
                            text="Bairro:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.bairro.place(x=550, y=220)
        self.bairro_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.bairro_entry.place(x=730, y=220)

        self.numero_logradouro = Label(self.master,
                                       text="Número:",
                                       bg='#c9c9ff',
                                       fg='white',
                                       font=('Verdana 15 bold'))
        self.numero_logradouro.place(x=550, y=270)
        self.numero_logradouro_entry = Entry(self.master,
                                             width=15,
                                             font=('Verdana 15 bold'))
        self.numero_logradouro_entry.place(x=730, y=270)

        self.cidade = Label(self.master,
                            text="Cidade:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.cidade.place(x=550, y=320)
        self.cidade_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.cidade_entry.place(x=730, y=320)

        self.complemento = Label(self.master,
                                 text="Complemento:",
                                 bg='#c9c9ff',
                                 fg='white',
                                 font=('Verdana 15 bold'))
        self.complemento.place(x=550, y=370)
        self.complemento_entry = Entry(self.master,
                                       width=15,
                                       font=('Verdana 15 bold'))
        self.complemento_entry.place(x=730, y=370)

        # TERCEIRO FRAME =============================================
        self.numero_cnh = Label(self.master,
                                text="Numero CNH:",
                                bg='#c9c9ff',
                                fg='white',
                                font=('Verdana 15 bold'))
        self.numero_cnh.place(x=1050, y=70)
        self.numero_cnh_entry = Entry(self.master,
                                      width=15,
                                      font=('Verdana 15 bold'))
        self.numero_cnh_entry.place(x=1250, y=70)

        self.numero_registro_cnh = Label(self.master,
                                         text="RG CNH:",
                                         bg='#c9c9ff',
                                         fg='white',
                                         font=('Verdana 15 bold'))
        self.numero_registro_cnh.place(x=1050, y=120)
        self.numero_registro_cnh_entry = Entry(self.master,
                                               width=15,
                                               font=('Verdana 15 bold'))
        self.numero_registro_cnh_entry.place(x=1250, y=120)

        self.data_validade_cnh = Label(self.master,
                                       text="Validade CNH:",
                                       bg='#c9c9ff',
                                       fg='white',
                                       font=('Verdana 15 bold'))
        self.data_validade_cnh.place(x=1050, y=170)
        self.data_validade_cnh_entry = Entry(self.master,
                                             width=15,
                                             font=('Verdana 15 bold'))
        self.data_validade_cnh_entry.place(x=1250, y=170)

        self.uf_cnh = Label(self.master,
                            text="UF CNH:",
                            bg='#c9c9ff',
                            fg='white',
                            font=('Verdana 15 bold'))
        self.uf_cnh.place(x=1050, y=220)
        self.uf_cnh_entry = Entry(self.master,
                                  width=15,
                                  font=('Verdana 15 bold'))
        self.uf_cnh_entry.place(x=1250, y=220)

        self.contato_emergencial = Label(self.master,
                                         text="Contato 2:",
                                         bg='#c9c9ff',
                                         fg='white',
                                         font=('Verdana 15 bold'))
        self.contato_emergencial.place(x=1050, y=270)
        self.contato_emergencial_entry = Entry(self.master,
                                               width=15,
                                               font=('Verdana 15 bold'))
        self.contato_emergencial_entry.place(x=1250, y=270)

        self.nome_contato_emergencial = Label(self.master,
                                              text="Nome contato:",
                                              bg='#c9c9ff',
                                              fg='white',
                                              font=('Verdana 15 bold'))
        self.nome_contato_emergencial.place(x=1050, y=320)
        self.nome_contato_emergencial_entry = Entry(self.master,
                                                    width=15,
                                                    font=('Verdana 15 bold'))
        self.nome_contato_emergencial_entry.place(x=1250, y=320)

        # BOTAO LIMPAR  =========================================================================
        self.botao_limpar = Button(self.master,
                                   text="Limpar",
                                   width=22,
                                   height=2,
                                   bg='#ffdfba',
                                   fg='black',
                                   font=('Verdana 15 bold'),
                                   command=self.view_command)
        self.botao_limpar.place(x=1170, y=550)

        self.botao_cadastrar = Button(self.master,
                                      text="Cadastrar",
                                      width=22,
                                      height=2,
                                      bg='#baffc9',
                                      fg='black',
                                      font=('Verdana 15 bold'),
                                      command=self.get_items)
        self.botao_cadastrar.place(x=1170, y=650)
        '''
        self.botao_sair = Button(self.master, text="Sair", width=22, height=2, bg='#ffb3ba', fg='black', font=(
        'Verdana 15 bold'), command=self.close)
        self.botao_sair.place(x=1170, y=740)
        '''
        self.lista_clientes = Listbox(self.master,
                                      width=80,
                                      height=10,
                                      font=('Verdana 15 bold'))
        self.lista_clientes.place(x=30, y=550)

        #Associando a Scrollbar com a Listbox...
        self.scrollbar_cliente = Scrollbar(self.master)
        self.lista_clientes.configure(
            yscrollcommand=self.scrollbar_cliente.set)
        self.scrollbar_cliente.configure(command=self.lista_clientes.yview)
        self.scrollbar_cliente.place(x=1155,
                                     y=550,
                                     relheight=0.31,
                                     anchor='ne')

        self.pesquisar_cliente = Label(self.master,
                                       text="Lista de clientes Cadastrados:",
                                       bg='#c9c9ff',
                                       font=('Verdana 15 bold'))
        self.pesquisar_cliente.place(x=30, y=500)
        self.update_list()

    def update_list(self):
        try:
            self.lista_clientes.delete(0, END)
            for item in self.clienteDAO.view():
                self.lista_clientes.insert(END, item)
        except Exception:
            print('Erro na lista clientes.')

    def get_items(self):
        self.cliente.nome = self.nome_entry.get()
        self.cliente.rg = self.rg_entry.get()
        self.cliente.cpf = self.cpf_entry.get()
        self.cliente.email = self.email_entry.get()
        self.cliente.telefone = self.telefone_entry.get()
        self.cliente.nascimento = self.nascimento_entry.get()
        self.cliente.estado_civil = self.estado_civil_entry.get()
        self.cliente.genero = self.genero_entry.get()
        self.cliente.cep = self.cep_entry.get()
        self.cliente.logradouro = self.logradouro_entry.get()
        self.cliente.bairro = self.bairro_entry.get()
        self.cliente.numero_logradouro = self.numero_logradouro_entry.get()
        self.cliente.cidade = self.cidade_entry.get()
        self.cliente.estado = self.estado_entry.get()
        self.cliente.complemento = self.complemento_entry.get()
        self.cliente.numero_cnh = self.numero_cnh_entry.get()
        self.cliente.numero_registro_cnh = self.numero_registro_cnh_entry.get()
        self.cliente.data_validade_cnh = self.data_validade_cnh_entry.get()
        self.cliente.uf_cnh = self.uf_cnh_entry.get()
        self.cliente.contato_emergencial = self.contato_emergencial_entry.get()
        self.cliente.nome_contato_emergencial = self.nome_contato_emergencial_entry.get(
        )

        if (self.cliente.nome == '' or self.cliente.rg == ''
                or self.cliente.cpf == '' or self.cliente.email == ''
                or self.cliente.telefone == '' or self.cliente.nascimento == ''
                or self.cliente.estado_civil == '' or self.cliente.genero == ''
                or self.cliente.cep == '' or self.cliente.logradouro == ''
                or self.cliente.bairro == ''
                or self.cliente.numero_logradouro == ''
                or self.cliente.cidade == '' or self.cliente.estado == ''
                or self.cliente.complemento == ''
                or self.cliente.numero_cnh == ''
                or self.cliente.numero_registro_cnh == ''
                or self.cliente.data_validade_cnh == ''
                or self.cliente.uf_cnh == ''
                or self.cliente.contato_emergencial == ''
                or self.cliente.nome_contato_emergencial == ''):
            tkinter.messagebox.showinfo("Aviso:", "Preencha todos os campos!")
        else:
            try:
                self.cliente.telefone = int(self.cliente.telefone)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo telefone deve ser preenchido com número!')
            try:
                self.cliente.contato_emergencial = int(
                    self.cliente.contato_emergencial)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo contato emergencial deve ser preenchidos com número!'
                )
            try:
                self.cliente.cep = int(self.cliente.cep)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!', 'O campo cep deve ser preenchido com números!')
            try:
                self.cliente.numero_cnh = int(self.cliente.numero_cnh)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo numero cnh deve ser preenchido com números!')
            try:
                self.cliente.numero_registro_cnh = int(
                    self.cliente.numero_registro_cnh)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo rg cnh deve ser preenchido com números!')
            try:
                self.cliente.uf_cnh = int(self.cliente.uf_cnh)
            except ValueError:
                tkinter.messagebox.showinfo(
                    'Aviso!',
                    'O campo uf cnh deve ser preenchido com números!!')
            else:
                try:
                    self.dao.insert(self.cliente)
                except Exception as e:
                    print("erro ao inserir no banco de dados")
                else:
                    tkinter.messagebox.showinfo(
                        'Aviso!', 'Cadastro Realizado com Sucesso!')
                    self.clear_all()
                    self.update_list()

    def clear_all(self):
        self.nome_entry.delete(0, END)
        self.rg_entry.delete(0, END)
        self.cpf_entry.delete(0, END)
        self.email_entry.delete(0, END)
        self.telefone_entry.delete(0, END)
        self.nascimento_entry.delete(0, END)
        self.estado_civil_entry.delete(0, END)
        self.genero_entry.delete(0, END)
        self.cep_entry.delete(0, END)
        self.logradouro_entry.delete(0, END)
        self.bairro.delete(0, END)
        self.numero_logradouro.delete(0, END)
        self.cidade.delete(0, END)
        self.estado.delete(0, END)
        self.complemento.delete(0, END)
        self.numero_cnh.delete(0, END)
        self.numero_registro_cnh.delete(0, END)
        self.data_validade_cnh.delete(0, END)
        self.uf_cnh.delete(0, END)
        self.contato_emergencial.delete(0, END)
        self.nome_contato_emergencial.delete(0, END)

    def view_command(self):
        "método para visualização dos resultados"
        try:
            rows = self.clienteDAO.view()
            self.window.lista_clientes.delete(0, END)
            for r in rows:
                self.window.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)

    def search_command(self):
        "método para buscar registros"
        self.gui.lista_clientes.delete(0, END)
        self.__fill_current_client()
        try:
            rows = self.dao.search(self.currentClient)
            for r in rows:
                self.gui.lista_clientes.insert(END, r)
        except Exception as e:
            print(e)

    def close(self):
        self.dao.close()
        self.tela_inicial.destroy()
        self.executar.abrir()
예제 #20
0
class Player:
    def __init__(self, master):
        self.master = master
        pygame.init()
        pygame.mixer.init()

        #===Empty thread list=====#
        self.threads = []

        #=====show an icon for the player===#
        def get_icon():
            self.winicon = PhotoImage(file="best (2).png")
            master.iconphoto(False, self.winicon)

        #=====run the get_icon on a different thread from the gui=====#

        def icon():
            mythreads = threading.Thread(target=get_icon)
            self.threads.append(mythreads)
            mythreads.start()

        icon()

        #=======all Button symbols and variables======#

        PLAY = "►"
        PAUSE = "║║"
        RWD = "⏮"
        FWD = "⏭"
        STOP = "■"
        UNPAUSE = "||"
        mute = "🔇"
        unmute = u"\U0001F50A"
        vol_mute = 0.0
        vol_unmute = 1

        #==========music playlist listbox=========#
        self.scroll = Scrollbar(master)
        self.play_list = Listbox(master,
                                 font="Sansarif 12 bold",
                                 bd=5,
                                 bg="white",
                                 width=37,
                                 height=19,
                                 selectbackground="black")
        self.play_list.place(x=600, y=77)
        self.scroll.place(x=946, y=80, height=389, width=15)
        self.scroll.config(command=self.play_list.yview)
        self.play_list.config(yscrollcommand=self.scroll.set)

        files = 'best (2).png'
        self.img1 = Image.open(files)
        self.img1 = self.img1.resize((600, 470), Image.ANTIALIAS)
        self.img = ImageTk.PhotoImage(self.img1)
        self.lab = Label(master)
        self.lab.grid(row=0, column=0)
        self.lab["compound"] = LEFT
        self.lab["image"] = self.img

        #=====show the song playing==========#
        self.var = StringVar()
        self.var.set(
            ".............................................................................."
        )
        self.song_title = Label(master,
                                font="Helvetica 12 bold",
                                bg="black",
                                fg="white",
                                width=60,
                                textvariable=self.var)
        self.song_title.place(x=3, y=0)

        # =====add a music list to the listbox======"

        def append_listbox():
            global song_list
            try:
                directory = askdirectory()
                os.chdir(directory)  # it permits to change the current dir
                song_list = os.listdir()
                song_list.reverse()
                for item in song_list:  # it returns the list of files song
                    pos = 0
                    self.play_list.insert(pos, item)
                    pos += 1

                global size
                index = 0
                size = len(song_list)
                self.play_list.selection_set(index)
                self.play_list.see(index)
                self.play_list.activate(index)
                self.play_list.selection_anchor(index)

            except:
                showerror("File selected error",
                          "Please choose a file correctly")

        # =====run the append_listbox function on separate thread====== #

        def add_songs_playlist():
            mythreads = threading.Thread(target=append_listbox)
            self.threads.append(mythreads)
            mythreads.start()

        #=====show music time=========#

        def get_time():
            current_time = pygame.mixer.music.get_pos() / 1000
            formated_time = time.strftime("%H:%M:%S",
                                          time.gmtime(current_time))
            next_one = self.play_list.curselection()
            song = self.play_list.get(next_one)
            song_timer = MP3(song)
            song_length = int(song_timer.info.length)
            format_for_length = time.strftime("%H:%M:%S",
                                              time.gmtime(song_length))
            self.label_time.config(
                text=f"{ format_for_length} / {formated_time}")
            self.progress["maximum"] = song_length
            self.progress["value"] = int(current_time)
            master.after(100, get_time)

        #=====play the music====#

        def Play_music():
            try:
                track = self.play_list.get(ACTIVE)
                pygame.mixer.music.load(track)
                self.var.set(track)
                pygame.mixer.music.play()
                get_time()

                # iterate through all the songs in the playlist
                # there is a bug when closing the window

            except:
                showerror("No Music", "Please load the music you want to play")

        def playAll():
            try:
                index = 0
                for i in range(size):
                    self.play_list.select_clear(0, END)
                    self.play_list.selection_set(index, last=None)
                    self.play_list.see(index)
                    self.play_list.activate(index)
                    self.play_list.selection_anchor(index)
                    track = self.play_list.get(index)
                    pygame.mixer.music.load(track)
                    self.var.set(track)
                    pygame.mixer.music.play()
                    current_song = self.play_list.curselection()
                    song = self.play_list.get(current_song)
                    song_timer = MP3(song)
                    song_length = int(song_timer.info.length) * 1000
                    get_time()
                    index += 1
            except:
                showerror("No songs in playlist", "Please add music")

        def play_all():
            mythreads = threading.Thread(target=playAll)
            self.threads.append(mythreads)
            mythreads.start()

        # ===pause and unpause == #

        def pause_unpause():
            if self.button_pause['text'] == PAUSE:
                pygame.mixer.music.pause()
                self.button_pause['text'] = UNPAUSE

            elif self.button_pause['text'] == UNPAUSE:
                pygame.mixer.music.unpause()
                self.button_pause['text'] = PAUSE

        # ==play the music on a diffent thread from the gui == #

        def play_thread():
            mythreads = threading.Thread(target=Play_music)
            self.threads.append(mythreads)
            mythreads.start()

        master.bind("<space>", lambda x: play_thread())

        # ===stop===

        def stop():
            pygame.mixer.music.stop()

        #====increase and decrease volume when slider is moved()==#

        def volume(x):
            pygame.mixer.music.set_volume(self.volume_slider.get())

        # ====mute and unmute the song while the song plays== #

        def muted():
            if self.button_mute['text'] == unmute:
                pygame.mixer.music.set_volume(vol_mute)
                self.volume_slider.set(vol_mute)
                self.button_mute['fg'] = "red"
                self.button_mute['text'] = mute
            elif self.button_mute['text'] == mute:
                pygame.mixer.music.set_volume(vol_unmute)
                self.volume_slider.set(vol_unmute)
                self.button_mute['fg'] = "white"
                self.button_mute['text'] = unmute

        #===move to the next song===#

        def nextSong():
            try:
                next_one = self.play_list.curselection()
                next_one = next_one[0] + 1
                song = self.play_list.get(next_one)
                pygame.mixer.music.load(song)
                pygame.mixer.music.play()
                self.play_list.select_clear(0, END)
                self.play_list.activate(next_one)
                self.play_list.selection_set(next_one, last=None)
                self.var.set(song)
                get_time()
                self.play_list.see(next_one)
            except:
                showerror("No Next Song", "Please press the previous button")

        def next():
            mythreads = threading.Thread(target=nextSong)
            self.threads.append(mythreads)
            mythreads.start()

        #===move to the previous song===#

        def prevSong():
            try:
                next_one = self.play_list.curselection()
                next_one = next_one[0] - 1
                song = self.play_list.get(next_one)
                pygame.mixer.music.load(song)
                pygame.mixer.music.play()
                self.play_list.select_clear(0, END)
                self.play_list.activate(next_one)
                self.play_list.selection_set(next_one, last=None)
                self.var.set(song)
                get_time()
                self.play_list.see(next_one)
            except:
                showerror("No previous Song", "Please press the Next button")

        def prev():
            mythreads = threading.Thread(target=prevSong)
            self.threads.append(mythreads)
            mythreads.start()

        self.master.bind('<Left>', lambda x: prev())
        self.master.bind('<Right>', lambda x: next())

        #=====exit the application=====#

        def exit():
            MsgBox = askquestion(
                'Exit Application',
                'Are you sure you want to exit the music player.',
                icon='warning')
            if MsgBox == 'yes':
                master.quit()
                master.after(100, exit)
            else:
                showinfo('Return', 'Continue playing your awesome music')
            return

        #=====Help window=====#

        def help():
            top = Toplevel()
            top.title("Help")
            top.geometry("350x554+500+80")
            top.resizable(width=0, height=0)
            user_manual = [
                " MUSIC PLAYER USER MANUAL: \n", "1. play button =  ( ► )",
                "2. pause button = ║║ ", "3. unpause symbol = ||",
                "4. next button = ⏭ ", "5. previous button = ⏮",
                "6. mute button = '\U0001F50A' ", "7. unmute symbol = 🔇",
                "8. stop button = ■ ",
                "\n\n| Made by manucho | Copyright @ 2021 |\n"
            ]
            for i in user_manual:
                manual = Label(top,
                               text=i,
                               width=50,
                               height=3,
                               font="Helvetica, 11",
                               bg="black",
                               fg="white")
                manual.pack(side=TOP, fill=BOTH)

        #==============================================================================================#
        #   THis part contains the menu, volume slider , music playlist label and the volume slider  #
        #===============================================================================================#

        self.menu = Menu(
            self.lab,
            font="helvetica, 3",
        )
        master.config(menu=self.menu)
        self.menu.add_command(label="HELP", command=help)
        self.menu.add_command(label="EXIT", command=exit)

        self.separator = ttk.Separator(self.lab, orient='horizontal')
        self.separator.place(relx=0, rely=0.87, relwidth=1, relheight=1)
        self.button_play = Button(master,
                                  text=PLAY,
                                  width=5,
                                  bd=5,
                                  bg="black",
                                  fg="white",
                                  font="Helvetica, 15",
                                  command=play_thread)
        self.button_play.place(x=150, y=415)
        self.button_stop = Button(master,
                                  text=STOP,
                                  width=5,
                                  bd=5,
                                  font="Helvetica, 15",
                                  bg="black",
                                  fg="white",
                                  command=stop)
        self.button_stop.place(x=225, y=415)
        self.button_prev = Button(master,
                                  text=FWD,
                                  width=5,
                                  bd=5,
                                  font="Helvetica, 15",
                                  bg="black",
                                  fg="white",
                                  command=next)
        self.button_prev.place(x=300, y=415)

        self.buttonPlayall = Button(self.master,
                                    text='\U0001F500',
                                    bg='black',
                                    fg='white',
                                    font='Helvetica, 15',
                                    bd=5,
                                    width=3,
                                    command=play_all)
        self.buttonPlayall.place(x=375, y=415)

        self.button_next = Button(master,
                                  text=RWD,
                                  width=5,
                                  bd=5,
                                  bg="black",
                                  fg="white",
                                  font="Helvetica, 15",
                                  command=prev)
        self.button_next.place(x=10, y=415)
        self.button_pause = Button(master,
                                   text=PAUSE,
                                   width=4,
                                   bd=5,
                                   font="Helvetica, 15",
                                   bg="black",
                                   fg="white",
                                   command=pause_unpause)
        self.button_pause.place(x=85, y=415)

        self.button_mute = Button(master,
                                  text=unmute,
                                  width=2,
                                  bd=5,
                                  font="Helvetica, 15",
                                  bg="black",
                                  fg="white",
                                  command=muted)
        self.button_mute.place(x=430, y=415)

        self.label_playlist = Label(master,
                                    text=u"♫ Music Playlist ♫ ",
                                    width=31,
                                    font="Helvetica, 15")
        self.label_playlist.place(x=610, y=5)

        self.button_load_music = Button(
            master,
            text="♫ Click Here To Load The Music ♫",
            width=43,
            bd=5,
            font="Helvetica, 10",
            bg="black",
            fg="white",
            command=add_songs_playlist)
        self.button_load_music.place(x=605, y=45)

        self.style = ttk.Style()

        self.style.configure("myStyle.Horizontal.TScale", background="#505050")

        self.volume_slider = ttk.Scale(self.lab,
                                       from_=0,
                                       to=1,
                                       orient=HORIZONTAL,
                                       value=1,
                                       length=120,
                                       command=volume,
                                       style="myStyle.Horizontal.TScale")
        self.volume_slider.place(x=475, y=424)

        self.progress = ttk.Progressbar(self.lab,
                                        orient=HORIZONTAL,
                                        value=0,
                                        length=453,
                                        mode='determinate')
        self.progress.place(x=0, y=385)

        self.label_time = Label(master,
                                text="00:00:00 / 00:00:00",
                                width=17,
                                font="Helvetica, 10",
                                bg="black",
                                fg="white")
        self.label_time.place(x=460, y=387)
예제 #21
0
class DeleteVeiculo(Toplevel):
    '''Classe interface deletar veiculo'''
    def __init__(self, master=None):
        '''Inicializa uma nova tela para deletar os veiculos.'''
        Toplevel.__init__(self, master=master)
        self.veiculo = Veiculo()
        self.dao = VeiculoDAO()
        self.geometry('1350x850+0+0')
        self.title('Deletar Veiculos')
        self.resizable(0, 0)
        self.configure(background='#c9c9ff')

        self.id = None
        self.nome_tela = Label(self,
                               text="Deletar Veiculos",
                               bg='#c9c9ff',
                               fg='white',
                               font=('Verdana 40 bold'))
        self.nome_tela.place(x=500, y=50)

        # BOTOES =================================================================
        self.botao_deletar = Button(self,
                                    text="Deletar veiculo do banco de dados",
                                    width=43,
                                    height=1,
                                    bg='#baffc9',
                                    fg='black',
                                    font=('Verdana  15 bold'),
                                    command=self.delete)
        self.botao_deletar.place(x=40, y=600)

        self.botao_sair = Button(self,
                                 text="Sair",
                                 width=43,
                                 height=1,
                                 bg='#ffb3ba',
                                 fg='black',
                                 font=('Verdana  15 bold'),
                                 command=self.close)
        self.botao_sair.place(x=690, y=600)

        self.listbox_veiculos = Listbox(self,
                                        width=90,
                                        height=10,
                                        font=('Verdana  15 bold'))
        self.listbox_veiculos.place(x=40, y=300)

        # SCROLLBAR =========================================================
        self.scrollbar_veiculo = Scrollbar(self, )
        self.listbox_veiculos.configure(
            yscrollcommand=self.scrollbar_veiculo.set)
        self.scrollbar_veiculo.configure(command=self.listbox_veiculos.yview)
        self.scrollbar_veiculo.place(x=1340,
                                     y=120,
                                     relheight=0.62,
                                     anchor='ne')

        # AREA PESQUISAR =======================================================
        self.pesquisar_veiculo = Label(self,
                                       text="Pesquisar pela marca:",
                                       bg='#c9c9ff',
                                       font=('Verdana  15 bold'))
        self.pesquisar_veiculo.place(x=40, y=200)

        self.search_var = StringVar()
        self.search_var.trace("w",
                              lambda name, index, mode: self.view_command())
        self.search_entry = Entry(self,
                                  textvariable=self.search_var,
                                  width=20,
                                  font=('Verdana  15 bold'))
        self.search_entry.place(x=300, y=200)

        # self.botao_pesquisar = Button(self, text="Pesquisar", width= 20, height=1, bg='#ffdfba', fg='black', font=(
        #     'Verdana  15 bold'), command=self.close)
        # self.botao_pesquisar.place(x=620, y=190)

        self.view_command()

        self.listbox_veiculos.bind('<<ListboxSelect>>',
                                   self.selecionar_list_box)

    def view_command(self):
        "método para visualização dos resultados"
        try:
            rows = self.dao.view()
            self.listbox_veiculos.delete(0, END)
            for r in rows:
                if str(self.search_var.get()).lower() in str(r).lower():
                    self.listbox_veiculos.insert(END, r)
        except Exception as e:
            print(e)

    def selecionar_list_box(self, event):
        if self.listbox_veiculos.curselection():
            indice = self.listbox_veiculos.curselection()[0]
            self.selecionado = self.listbox_veiculos.get(indice)

            self.id = self.selecionado[0]

    def delete(self):
        '''Função para deletar o veiculo do banco de dados'''
        try:
            self.dao.delete(self.id)
        except Exception:
            tkinter.messagebox.showinfo('Aviso!',
                                        'Erro ao acessar o banco de dados.')
        else:
            tkinter.messagebox.showinfo('Aviso!',
                                        'veiculo Excluido com Sucesso!')
            #self.clear_all()
            self.view_command()

    def close(self):
        '''Função para fechar a tela, fecha a conexão com o banco de dados e destroi a janela atual.'''
        self.dao.close()
        self.destroy()

    def run(self):
        '''Função para chamar a tela.'''
        self.mainloop()
예제 #22
0
    def view_details(self, Medikom, id):
        self.selected_id = id
        self.overview(Medikom)
        entry_results, attachments = Medikom.get_entry(id)
        ts, title, notes = entry_results
        ts = self.format_ts(ts)[:-3]
        details_text = 'Details zu %s (zuletzt geändert am %s)' % (title, ts)
        details_label = Label(
            self, text=details_text, font='Liberation 10', fg='Black', anchor='w')
        details_label.place(
            x=self.SPACE_TWO,
            y=(self.n + 2) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=self.WIN_WIDTH - self.SPACE_TWO, height=self.ROW_HIGHT)

        details_label.bind(sequence='<Button-1>',
            func=Callable(self.view_edit_title, Medikom, id, title))

        # add attachment button and list attachments
        attach_button = Button(
            self, text='Neuer Anhang',
            command=lambda: self.attach_file(Medikom, id))
        attach_button.place(
            x=self.SPACE_TWO,
            y=(self.n + 3) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=self.WIN_WIDTH / 8, height=self.ROW_HIGHT)
        if attachments:
            xpos = (1.5 * self.SPACE_TWO) + (self.WIN_WIDTH / 8)
            for i, attachment in enumerate(attachments):
                attachment = attachment[0]
                filename = ''
                if '\\' in attachment:
                    filename = attachment.split('\\')[-1]
                elif '/' in attachment:
                    filename = attachment.split('/')[-1]
                width = len(filename) * 7.2
                attachment_button = Button(
                    self, text=filename, font='Courier 9', fg="blue",
                    command=Callable(self.open_attachment, attachment))
                attachment_button.place(
                    x=xpos,
                    y=(self.n + 3) * (self.ROW_HIGHT + self.ROW_SPACE),
                    width=width, height=self.ROW_HIGHT)
                xpos = xpos + width + (self.SPACE_TWO/2)
                attachment_button.config(relief='flat')
                attachment_button.bind(sequence='<Button-3>',
                    func=Callable(self.unattach_file, Medikom, id, attachment))

        # text element and scrollbar
        textframe = Text(
            self, font='Liberation 12', height=self.TEXT_FRAME_LINES,
            width=int(self.WIN_WIDTH / 4))
        scrollbar = Scrollbar(self)
        textframe.place(
            x=self.SPACE_TWO,
            y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=self.WIN_WIDTH - self.SPACE_ONE - 10,
            height=self.ROW_HIGHT * self.TEXT_FRAME_LINES)
        scrollbar.place(
            x=self.SPACE_TWO + self.WIN_WIDTH - self.SPACE_ONE - 10,
            y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE),
            width=10,
            height=self.ROW_HIGHT * self.TEXT_FRAME_LINES)
        scrollbar.config(command=textframe.yview)
        textframe.config(yscrollcommand=scrollbar.set)
        textframe.insert(END, notes)

        # update button
        update_button = Button(
            self, text='Text Aktualisieren',
            command=lambda: self.update_entry_notes(
                Medikom, id, textframe.get(1.0, END)))
        update_button.place(
            x=self.WIN_WIDTH / 2 - 0.125 * self.WIN_WIDTH,
            y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE) + (self.ROW_HIGHT * self.TEXT_FRAME_LINES + 5),
            width=self.WIN_WIDTH/4, height=self.ROW_HIGHT)
예제 #23
0
class Chatbot:
    def __init__(self, window):
        window.title('Thesaurus Bot')
        window.geometry('400x500')
        window.resizable(0, 0)

        self.message_position = 1.5

        self.message_window = Entry(window, width=30, font=('Times', 12))
        self.message_window.bind('<Return>', self.reply_to_you)
        self.message_window.place(x=128, y=400, height=88, width=260)

        self.chat_window = Text(window,
                                bd=3,
                                relief="flat",
                                font=("Times", 10),
                                undo=True,
                                wrap="word")
        self.chat_window.place(x=6, y=6, height=385, width=370)
        self.overscroll = Scrollbar(window, command=self.chat_window.yview)
        self.overscroll.place(x=375, y=5, height=385)

        self.chat_window["yscrollcommand"] = self.overscroll.set

        self.send_button = Button(window,
                                  text='Submit',
                                  fg='white',
                                  bg='grey',
                                  width=12,
                                  height=5,
                                  font=('Times', 12),
                                  relief='flat',
                                  command=self.reply_to_you)
        self.send_button.place(x=6, y=400, height=88)

        self.data = json.load(open("data.json"))
        self.error = [
            "Sorry, I don't know that word", "What did you say?",
            "The word doesn't exist", "Please double check."
        ]

    def add_chat(self, message):
        self.message_position += 1.5
        print(self.message_position)
        self.message_window.delete(0, 'end')
        self.chat_window.config(state='normal')
        self.chat_window.insert(self.message_position, message)
        self.chat_window.see('end')
        self.chat_window.config(state='disabled')

    def reply_to_you(self, event=None):
        message = self.message_window.get()
        w = message.lower()
        message = f'You: {message} \n'
        if w in self.data:  # if word is a key in data
            reply = f'Bot: {self.data[w][0]} \n'
        elif w.title(
        ) in self.data:  # elseif capitalize the first letter with the tittle command and check again
            reply = f'Bot: {self.data[w.title()][0]} \n'
        elif w.upper(
        ) in self.data:  # else check in full caps in case user enters words like USA or NATO
            reply = f'Bot: {self.data[w.upper()][0]} \n'
        elif len(get_close_matches(w, self.data.keys())) > 0:
            reply = f'''Bot: Did you mean {get_close_matches(w, self.data.keys())[0]} instead? That one means: \n
            {self.data[get_close_matches(w, self.data.keys())[0]][0]} \n'''
        else:
            reply = f'Bot: {choice(self.error)}\n'
        self.add_chat(message)
        self.add_chat(reply)
    def historyTab():
        # window that shows history of all chats.
        historyWindow = Toplevel(root)
        root.withdraw()
        historyWindow.title("{} - History".format(userEmailAddress))
        historyWindow.geometry("1000x800")
        historyWindow.config(bg="#ccffcc")
        historyWindow.resizable(height=False, width=False)

        historyList = Listbox(
            historyWindow,
            height=37,
            width=96,
            bg="#ccffcc",
            foreground="#446665",
            font=("Verdana", 12),
            borderwidth=5,
        )
        historyList.place(x=10, y=10)

        def returnList(text):
            responseList = []
            i = 0
            while i < len(text):
                if len(text) - i > 87:
                    responseList.append(text[i:i + 87] + '-')
                    i = i + 87
                else:
                    responseList.append(text[i:])
                    break
            return responseList

        scrollbary = Scrollbar(historyWindow, command=historyList.yview)
        historyList['yscrollcommand'] = scrollbary.set
        scrollbary.place(x=985, y=10, height=720)
        scrollbary.config(bg="#ccffcc")

        #scrollbarx = Scrollbar(historyWindow, command=historyList.xview, orient="horizontal")
        #historyList['xscrollcommand'] = scrollbarx.set
        #scrollbarx.place(x=10, y=725, width=980)
        #scrollbarx.config(bg="#ccffcc")

        mycursor = con.execute(""" select * from MsgStoreHistory """)
        histories = mycursor.fetchall()
        i = 1
        try:
            dateTime = str(histories[0][0])
            date = dateTime[:10]
            historyList.insert(i, date)
            historyList.itemconfig(i - 1, {'fg': 'red'})
            i += 1
            for chats in histories:
                chatsDateTime = str(chats[0])
                chatsDate = chatsDateTime[:10]
                chatsTime = chatsDateTime[11:]
                if chatsDate != date:
                    historyList.insert(i, " ")
                    i += 1
                    date = chatsDate
                    historyList.insert(i, date)
                    historyList.itemconfig(i - 1, {'fg': 'red'})
                    i += 1
                else:
                    pass
                if chats[1] == userEmailAddress:
                    textList = returnList(chats[2])
                    historyList.insert("end",
                                       chatsTime + " : You: " + textList[0])
                    historyList.itemconfig("end", {'fg': 'blue'})
                    for response in textList[1:]:
                        historyList.insert(
                            "end", "                            " + response)
                        historyList.itemconfig("end", {'fg': 'blue'})
                    i += 1
                elif chats[1] == "bot" + userEmailAddress:
                    textList = returnList(chats[2])
                    historyList.insert("end",
                                       chatsTime + " : Bot: " + textList[0])
                    historyList.itemconfig("end", {'fg': 'green'})
                    for response in textList[1:]:
                        historyList.insert(
                            "end",
                            "                                 " + response)
                        historyList.itemconfig("end", {'fg': 'green'})
                    i += 1
        except IndexError:
            pass

        # calls when user invokes clear button
        def clearButtonListener():
            answer = messagebox.askyesno("Clear", "Sure?")
            if answer == True:
                con.execute(
                    """ delete from MsgStoreHistory where sender in ("{}", "{}") """
                    .format(userEmailAddress, 'bot' + userEmailAddress))
                con.commit()
                historyList.delete(0, "end")
                messagebox.showinfo("Clear",
                                    "All the chat history has been deleted.")
            else:
                pass

        # loading and using clear button image
        clearButton = Button(historyWindow,
                             image=clear_button_image,
                             bg="#ccffcc",
                             borderwidth=0,
                             command=clearButtonListener)
        clearButton.place(x=8, y=740)

        # exports the chats to a file appended with current time. (Invokes when 'export chats history' invoke in menu bar of this particular window.)
        def exportChats():
            timestr = str(datetime.now())
            textFile = open(
                "Histories/{}_chatHistories_{}.txt".format(
                    userEmailAddress, '_'.join([
                        timestr[:4], timestr[5:7], timestr[8:10],
                        timestr[11:13], timestr[14:16], timestr[17:19]
                    ])), 'w')
            mycursor = con.execute(""" select * from MsgStoreHistory """)
            messages = mycursor.fetchall()
            for message in messages:
                if message[1] == userEmailAddress:
                    textFile.write(
                        str(message[0]) + " => You:" + message[2] + '\n')
                elif message[1] == 'bot' + userEmailAddress:
                    textFile.write(
                        str(message[0]) + " => Bot:" + message[2] + '\n')
            textFile.close()
            messagebox.showinfo(
                "Export",
                """ Chats has been exported to "{}_chatsHistory_{}.txt" file """
                .format(
                    userEmailAddress, '_'.join([
                        timestr[:4], timestr[5:7], timestr[8:10],
                        timestr[11:13], timestr[14:16], timestr[17:19]
                    ])))

        # calks when user exits from the history window.
        def exitWindow():
            root.deiconify()
            historyWindow.withdraw()

        # menu bar for history window
        menubar = Menu(historyWindow, bg="#ccffcc")
        options = Menu(menubar, tearoff=0, bg="#ccffcc")
        menubar.add_cascade(label="Options", menu=options)
        options.add_command(label="Export Chat History", command=exportChats)
        options.add_separator()
        options.add_command(label="Exit", command=exitWindow)
        historyWindow.config(menu=menubar)

        historyWindow.protocol("WM_DELETE_WINDOW", exitWindow)
def mainWindow():
    signUpWindow.withdraw()
    # inserts the given parameter to the database.

    # this temporary table is used to store the messages of the chat window.
    con.execute(""" CREATE TEMP TABLE "MsgStore" (
	                    "time"	TEXT,
                    	"sender"	TEXT NOT NULL,
	                    "message"	TEXT DEFAULT '',
	                    PRIMARY KEY("time") ) """)

    def insertIntoDatabase(table, sender, message):
        con.execute("""insert into {} values ("{}", "{}", "{}")""".format(
            table, datetime.now(), sender, message))
        con.commit()

    # disables the mic_button when user types anything in the EntryBox.
    def entryFocusInHandler(event=None):
        mic_button.config(state="disabled")

    # top level window for chatbot, but comes under signUpWindow
    root = Toplevel(signUpWindow)
    root.title("{} - Wikipedia Chatbot".format(userEmailAddress))
    root.geometry("1000x800")
    root.config(bg="#ccffcc")
    root.resizable(height=False, width=False)

    no_of_linesLabel = Label(root, text="No. of lines:", bg='#ccffcc')
    no_of_linesLabel.place(x=5, y=5)
    no_of_lines = IntVar()
    ComboBox = Combobox(root,
                        textvariable=no_of_lines,
                        width=5,
                        justify='left')
    ComboBox['values'] = (1, 2, 3, 4, 5)
    ComboBox.set(2)
    ComboBox.place(x=100, y=5)

    # listbox which displays the chats between the user and the bot.
    ChatBox = Listbox(root,
                      height=36,
                      width=96,
                      background="#ccffcc",
                      foreground="#446665",
                      font=("Verdana", 12),
                      borderwidth=5)
    ChatBox.place(x=5, y=30)

    # scrollbars for ChatBox.
    scrollbary = Scrollbar(root, command=ChatBox.yview)
    ChatBox['yscrollcommand'] = scrollbary.set
    scrollbary.place(x=980, y=30, height=690)
    scrollbary.config(bg="#ccffcc")
    #scrollbarx = Scrollbar(root, command=ChatBox.xview, orient="horizontal")
    #scrollbarx.config(bg="#ccffcc")
    #ChatBox['xscrollcommand'] = scrollbarx.set
    #scrollbarx.place(x=8, y=725, width=975)

    # used to switching focus. (This widget will no display on the screen)
    tempFrame = Frame(root, height=0, width=0)
    tempFrame.place(x=0, y=0)

    # EntryBox for user input.
    EntryBox = Entry(root,
                     bd=0,
                     bg="#ccffcc",
                     font="Arial",
                     relief="ridge",
                     borderwidth=5)
    EntryBox.place(x=68, y=740, height=55, width=810)
    EntryBox.bind("<Key>", entryFocusInHandler)

    # deletes all the entries of ChatBox. (Invokes when clearButton invokes).
    def clearButtonListener():
        answer = messagebox.askyesno("Clear", "Sure?")
        if answer == True:
            command = """ delete from MsgStore """
            con.execute(command)
            con.commit()
            ChatBox.delete(0, "end")
            messagebox.showinfo("Clear", "All chats has been cleared.")
        else:
            pass

    # clear button (Clear the chats from the chatbox and delete the chats from the MsgStore)
    clear_button = Button(root,
                          image=clear_button_image,
                          bg="#ccffcc",
                          borderwidth=0,
                          command=clearButtonListener)
    clear_button.place(x=8, y=740)

    # listens the user input when user clicks on mic_button. (Invokes when mic_button invokes)
    def micButtonListener():
        global stringToSpeak
        text = listenAndSpeak.takeUserSpeech()
        EntryBox.delete(0, "end")
        EntryBox.insert(0, text)
        sendButtonListener()
        listenAndSpeak.speak(stringToSpeak)

    # mic button (When invkokes listens to user's speech)
    mic_button = Button(root,
                        image=mic_button_image,
                        bg="#ccffcc",
                        borderwidth=0,
                        padx=2,
                        pady=2,
                        command=micButtonListener)
    mic_button.place(x=935, y=740, height=50, width=60)
    mic_button.bind('')

    # send the user response for evaluation. (Invokes when send_button invokes and by micButtonListener)
    def sendButtonListener(event=None):
        EntryBox.bind("<Return>", lambda event: tempFrame.focus_set())
        userInput = EntryBox.get()
        if len(userInput) != 0:
            ChatBox.insert("end", "You: " + userInput)
            ChatBox.itemconfig('end', {'fg': 'blue'})
            root.update_idletasks()
            responseList = Response.getResponse(userInput, no_of_lines.get())
            ChatBox.insert("end", "Bot: " + responseList[0])
            ChatBox.itemconfig('end', {'fg': 'green'})
            ChatBox.config(foreground="#446665", font=("Verdana", 12))
            root.update_idletasks()
            signUpWindow.update_idletasks()
            for response in responseList[1:]:
                ChatBox.insert("end", "       " + response)
                ChatBox.itemconfig('end', {'fg': 'green'})
                ChatBox.config(foreground="#446665", font=("Verdana", 12))
                root.update_idletasks()
                signUpWindow.update_idletasks()
            root.update_idletasks()
            signUpWindow.update_idletasks()
            mic_button.config(state='active')
            response = "".join(responseList)
            insertIntoDatabase("MsgStore", userEmailAddress, userInput)
            insertIntoDatabase("MsgStoreHistory", userEmailAddress, userInput)
            insertIntoDatabase("MsgStore", "bot" + userEmailAddress, response)
            insertIntoDatabase("MsgStoreHistory", "bot" + userEmailAddress,
                               response)
            EntryBox.delete(0, 'end')
            global stringToSpeak
            stringToSpeak = response
        else:
            return

    # send button (sends the message to the chatbox)
    send_button = Button(root,
                         image=send_button_image,
                         bg="#ccffcc",
                         borderwidth=0,
                         command=sendButtonListener)
    root.bind('<Return>', sendButtonListener)
    send_button.place(x=880, y=740)

    # history tab. (Invokes when history option in invoke in menu bar)
    def historyTab():
        # window that shows history of all chats.
        historyWindow = Toplevel(root)
        root.withdraw()
        historyWindow.title("{} - History".format(userEmailAddress))
        historyWindow.geometry("1000x800")
        historyWindow.config(bg="#ccffcc")
        historyWindow.resizable(height=False, width=False)

        historyList = Listbox(
            historyWindow,
            height=37,
            width=96,
            bg="#ccffcc",
            foreground="#446665",
            font=("Verdana", 12),
            borderwidth=5,
        )
        historyList.place(x=10, y=10)

        def returnList(text):
            responseList = []
            i = 0
            while i < len(text):
                if len(text) - i > 87:
                    responseList.append(text[i:i + 87] + '-')
                    i = i + 87
                else:
                    responseList.append(text[i:])
                    break
            return responseList

        scrollbary = Scrollbar(historyWindow, command=historyList.yview)
        historyList['yscrollcommand'] = scrollbary.set
        scrollbary.place(x=985, y=10, height=720)
        scrollbary.config(bg="#ccffcc")

        #scrollbarx = Scrollbar(historyWindow, command=historyList.xview, orient="horizontal")
        #historyList['xscrollcommand'] = scrollbarx.set
        #scrollbarx.place(x=10, y=725, width=980)
        #scrollbarx.config(bg="#ccffcc")

        mycursor = con.execute(""" select * from MsgStoreHistory """)
        histories = mycursor.fetchall()
        i = 1
        try:
            dateTime = str(histories[0][0])
            date = dateTime[:10]
            historyList.insert(i, date)
            historyList.itemconfig(i - 1, {'fg': 'red'})
            i += 1
            for chats in histories:
                chatsDateTime = str(chats[0])
                chatsDate = chatsDateTime[:10]
                chatsTime = chatsDateTime[11:]
                if chatsDate != date:
                    historyList.insert(i, " ")
                    i += 1
                    date = chatsDate
                    historyList.insert(i, date)
                    historyList.itemconfig(i - 1, {'fg': 'red'})
                    i += 1
                else:
                    pass
                if chats[1] == userEmailAddress:
                    textList = returnList(chats[2])
                    historyList.insert("end",
                                       chatsTime + " : You: " + textList[0])
                    historyList.itemconfig("end", {'fg': 'blue'})
                    for response in textList[1:]:
                        historyList.insert(
                            "end", "                            " + response)
                        historyList.itemconfig("end", {'fg': 'blue'})
                    i += 1
                elif chats[1] == "bot" + userEmailAddress:
                    textList = returnList(chats[2])
                    historyList.insert("end",
                                       chatsTime + " : Bot: " + textList[0])
                    historyList.itemconfig("end", {'fg': 'green'})
                    for response in textList[1:]:
                        historyList.insert(
                            "end",
                            "                                 " + response)
                        historyList.itemconfig("end", {'fg': 'green'})
                    i += 1
        except IndexError:
            pass

        # calls when user invokes clear button
        def clearButtonListener():
            answer = messagebox.askyesno("Clear", "Sure?")
            if answer == True:
                con.execute(
                    """ delete from MsgStoreHistory where sender in ("{}", "{}") """
                    .format(userEmailAddress, 'bot' + userEmailAddress))
                con.commit()
                historyList.delete(0, "end")
                messagebox.showinfo("Clear",
                                    "All the chat history has been deleted.")
            else:
                pass

        # loading and using clear button image
        clearButton = Button(historyWindow,
                             image=clear_button_image,
                             bg="#ccffcc",
                             borderwidth=0,
                             command=clearButtonListener)
        clearButton.place(x=8, y=740)

        # exports the chats to a file appended with current time. (Invokes when 'export chats history' invoke in menu bar of this particular window.)
        def exportChats():
            timestr = str(datetime.now())
            textFile = open(
                "Histories/{}_chatHistories_{}.txt".format(
                    userEmailAddress, '_'.join([
                        timestr[:4], timestr[5:7], timestr[8:10],
                        timestr[11:13], timestr[14:16], timestr[17:19]
                    ])), 'w')
            mycursor = con.execute(""" select * from MsgStoreHistory """)
            messages = mycursor.fetchall()
            for message in messages:
                if message[1] == userEmailAddress:
                    textFile.write(
                        str(message[0]) + " => You:" + message[2] + '\n')
                elif message[1] == 'bot' + userEmailAddress:
                    textFile.write(
                        str(message[0]) + " => Bot:" + message[2] + '\n')
            textFile.close()
            messagebox.showinfo(
                "Export",
                """ Chats has been exported to "{}_chatsHistory_{}.txt" file """
                .format(
                    userEmailAddress, '_'.join([
                        timestr[:4], timestr[5:7], timestr[8:10],
                        timestr[11:13], timestr[14:16], timestr[17:19]
                    ])))

        # calks when user exits from the history window.
        def exitWindow():
            root.deiconify()
            historyWindow.withdraw()

        # menu bar for history window
        menubar = Menu(historyWindow, bg="#ccffcc")
        options = Menu(menubar, tearoff=0, bg="#ccffcc")
        menubar.add_cascade(label="Options", menu=options)
        options.add_command(label="Export Chat History", command=exportChats)
        options.add_separator()
        options.add_command(label="Exit", command=exitWindow)
        historyWindow.config(menu=menubar)

        historyWindow.protocol("WM_DELETE_WINDOW", exitWindow)

    # exports chats to a file appended with current time. (Invokes when 'exports chats' invokes in menubar of root.)
    def exportChats():
        time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        textFile = open("Chats/{}_chats_{}.txt".format(userEmailAddress, time),
                        'w')
        mycursor = con.execute(""" select * from MsgStoreHistory """)
        messages = mycursor.fetchall()
        for message in messages:
            if message[1] == userEmailAddress:
                textFile.write(
                    str(message[0]) + " => You:" + message[2] + '\n')
            elif message[1] == 'bot' + userEmailAddress:
                textFile.write(
                    str(message[0]) + " => Bot:" + message[2] + '\n')
        textFile.close()
        messagebox.showinfo(
            "Export",
            """ Chats has been exported to "{}_chats_{}.txt" file """.format(
                userEmailAddress, time))

    # calls when sign out invokes
    def signout():
        answer = messagebox.askyesno("Sign Out", "Sure?")
        if answer == True:
            con.execute(
                """ update SignUpTable set keep_me_signed_in = 0  where emailAddress = "{}" """
                .format(userEmailAddress))
            con.commit()
            root.withdraw()
            signUpWindow.deiconify()
            con.execute(""" drop table MsgStore """)
            con.commit()
        else:
            pass

    # invokes when click on change password from menu bar
    def changePassword():

        # window for changing password.
        changePasswordWindow = Toplevel(signUpWindow)
        root.withdraw()
        changePasswordWindow.title("Change Password")
        changePasswordWindow.geometry("500x500")
        changePasswordWindow.config(bg="#ccffcc")
        changePasswordWindow.resizable(height=False, width=False)

        # loading and using logo image
        logo = Label(changePasswordWindow, image=logo_image, bg='#ccffcc')
        logo.place(x=50, y=10)

        # old password label and entry box.
        oldPasswordLabel = Label(changePasswordWindow,
                                 text='Old Password',
                                 bg='#ccffcc')
        oldPasswordLabel.place(x=80, y=250)
        oldPasswordEntryBox = Entry(changePasswordWindow, show='*')
        oldPasswordEntryBox.place(x=250, y=250)

        # new password label and entry box.
        newPasswordLabel = Label(changePasswordWindow,
                                 text='Password',
                                 bg='#ccffcc')
        newPasswordLabel.place(x=80, y=290)
        newPasswordEntryBox = Entry(changePasswordWindow, show='*')
        newPasswordEntryBox.place(x=250, y=290)

        # confirn new password label and entry box.
        confirmNewPasswordLabel = Label(changePasswordWindow,
                                        text='Confirm Password',
                                        bg='#ccffcc')
        confirmNewPasswordLabel.place(x=80, y=330)
        confirmNewPasswordEntryBox = Entry(changePasswordWindow, show='*')
        confirmNewPasswordEntryBox.place(x=250, y=330)

        # calls when user invokes chnage password button
        def changePasswordButtonListenener(event=None):
            mycursor = con.execute(
                """ select password from SignUpTable where emailAddress = "{}" """
                .format(userEmailAddress))
            password = mycursor.fetchall()[0][0]
            if password == oldPasswordEntryBox.get():
                if newPasswordEntryBox.get() == confirmNewPasswordEntryBox.get(
                ):
                    con.execute(
                        """ update SignUpTable set password = "******" where emailAddress = "{}" """
                        .format(newPasswordEntryBox.get(), userEmailAddress))
                    con.commit()
                    messagebox.showinfo(title="Password",
                                        message='Password has been changed.')
                    oldPasswordEntryBox.delete(0, 'end')
                    newPasswordEntryBox.delete(0, 'end')
                    confirmNewPasswordEntryBox.delete(0, 'end')
                    changePasswordWindow.withdraw()
                    root.deiconify()
                else:
                    messagebox.showerror(
                        title="Error",
                        message=
                        'New password should be same as confirm password.')
            else:
                messagebox.showerror(title="Error",
                                     message='Wrong old password.')

        # loading and using chnage password image
        change_password_button = Button(changePasswordWindow,
                                        image=change_password_button_image,
                                        command=changePasswordButtonListenener,
                                        borderwidth=0)
        change_password_button.place(x=180, y=400)
        changePasswordWindow.bind('<Return>', changePasswordButtonListenener)

        # calls when user exits from the chnage password window.
        def on_closing():
            changePasswordWindow.withdraw()
            root.deiconify()

        changePasswordWindow.protocol("WM_DELETE_WINDOW", on_closing)

    # deletes the current user and all the chats.
    def deleteAccount():
        answer = messagebox.askyesno("Delete", "Sure?")
        if answer == True:
            con.execute(
                """ delete from SignUpTable where emailAddress = "{}" """.
                format(userEmailAddress))
            con.execute(
                """ delete from MsgStoreHistory where sender in ("{}", "{}") """
                .format(userEmailAddress, 'bot' + userEmailAddress))
            con.commit()
            messagebox.showinfo(title="Delete",
                                message="Account has been deleted.")
            root.withdraw()
            signUpWindow.deiconify()
            con.execute(""" drop table MsgStore """)
            con.commit()
        else:
            pass

    # menu bar for chat window
    menubar = Menu(root, bg="#000000")
    options = Menu(menubar, tearoff=0, bg="#ccffcc")
    menubar.add_cascade(label="Options", menu=options)
    options.add_command(label="History", command=historyTab)
    options.add_separator()
    options.add_command(label="Export Chats.", command=exportChats)
    options.add_separator()
    options.add_command(label="Change Password", command=changePassword)
    options.add_command(label="Delete Account", command=deleteAccount)
    options.add_separator()
    options.add_command(label="Sign Out", command=signout)
    root.config(menu=menubar)

    # calls when user exits from the chat window.
    def on_closing():
        root.withdraw()
        signUpWindow.destroy()
        con.execute(""" drop table MsgStore """)
        con.commit()

    root.protocol("WM_DELETE_WINDOW", on_closing)
예제 #26
0
    def createWindow(self, parent, handleSavePassword, copyPasswordToClipboard,
                     handleEditPassword, deletePassword, getDecryptedPassword):
        for child in parent.winfo_children():
            child.destroy()
        h1 = Label(parent,
                   bg='#32425B',
                   fg='white',
                   font=('Roboto', 14),
                   borderwidth=0,
                   text="Passwords")
        h1.place(relx=0.1, rely=0.1, anchor=W)
        addNew = Button(parent,
                        bg='#198a78',
                        fg='white',
                        font=('Roboto', 10),
                        text="Add new",
                        borderwidth=0,
                        command=lambda: self.handleAddNewPassword(
                            parent, handleSavePassword))
        addNew.place(relx=0.95, rely=0.1, anchor=E)
        canvas = Canvas(parent,
                        height=380,
                        bg='#32425B',
                        bd=0,
                        highlightthickness=0,
                        relief='ridge')
        scroll_y = Scrollbar(parent,
                             orient="vertical",
                             command=canvas.yview,
                             bg='#32425B')

        listOfButtons = Frame(canvas, height=380, borderwidth=0, bg='#32425B')
        row = column = 0
        for password in self.passwords:
            card = Label(listOfButtons, borderwidth=0, bg='#32425B', width=100)
            if password.getLogo() == None:
                cardButton = Button(
                    card,
                    text=password.getWebsite(),
                    bg='#32425B',
                    fg='white',
                    borderwidth=0,
                    width=10,
                    padx=20,
                    pady=20,
                    command=lambda password=password:
                    SinglePassword(password).createWindow(
                        parent, copyPasswordToClipboard, handleEditPassword,
                        deletePassword, getDecryptedPassword))
            else:
                cardLogotk = ImageTk.PhotoImage(password.getLogo().resize(
                    (50, 50), Image.ANTIALIAS))
                cardLogo = Label(card,
                                 borderwidth=0,
                                 bg='#32425B',
                                 image=cardLogotk)
                cardLogo.image = cardLogotk
                cardButton = Button(
                    card,
                    text=password.getWebsite(),
                    bg='#32425B',
                    fg='white',
                    borderwidth=0,
                    image=cardLogotk,
                    compound=TOP,
                    width=100,
                    padx=20,
                    pady=20,
                    wraplength=100,
                    command=lambda password=password:
                    SinglePassword(password).createWindow(
                        parent, copyPasswordToClipboard, handleEditPassword,
                        deletePassword, getDecryptedPassword))
            cardButton.pack()
            card.grid(row=int(row), column=column % 4)
            row = row + 0.25
            column = column + 1
        canvas.create_window(0, 0, anchor='nw', window=listOfButtons)
        canvas.update_idletasks()
        canvas.configure(scrollregion=canvas.bbox('all'),
                         yscrollcommand=scroll_y.set)
        canvas.place(relx=0, rely=1, anchor=SW, width=600)
        scroll_y.place(relx=1, rely=1, anchor=SE, height=380)
예제 #27
0
def ui():
    # List of possible querys, each query changes the labels for the two words
    possible_querys = [
        'Si dos palabras son herman@s', 'Si dos palabras son prim@s',
        'Si una palabra es hij@ de otra', 'Si una palabra es ti@',
        'Si son prim@s y en qué grado',
        'Si una palabra está relacionada con un idioma',
        'Palabras en un idioma originadas por una palabra específica',
        'Listar los idiomas relacionados con una palabra',
        'Contar todas las palabras comunes entre dos idiomas',
        'Listar todas las palabras comunes entre dos idiomas',
        'Idioma que más aportó a otro',
        'Listar todos los idiomas que aportaron a otro'
    ]
    # List of possible relations on knowledge database
    possible_relations = [
        'rel:derived', 'rel:etymological_origin_of', 'rel:etymologically',
        'rel:etymologically_related', 'rel:etymology', 'rel:has_derived_form',
        'rel:is_derived_from', 'rel:variant:orthography'
    ]

    # Window Properties
    window = Tk()
    window.title("Project 2 - Ethymological Relationships")
    window.geometry("1000x800+180+20")

    # Title
    Label(window, text="Ethymological Relationships",
          font="Helvetica 18 bold").place(x=337, y=50)

    # Entry DB
    Label(window, text="Database File:", font="Helvetica 14").place(x=310,
                                                                    y=130)

    input = StringVar()
    Entry(window, font="Helvetica 12", textvariable=input).place(x=445, y=132)

    # Button input database
    enter_db = Button(
        window,
        font="Helvetica 12",
        text="Enter",
        command=lambda: db_input(input, window, possible_relations)).place(
            x=640, y=125)

    # Relations
    Label(window, text="Relations:", font="Helvetica 12").place(x=30, y=200)
    relations = Listbox(window,
                        height=8,
                        font="Helvetica 12",
                        selectmode=EXTENDED,
                        exportselection=0)
    relations.place(x=30, y=220)

    for item in possible_relations:
        relations.insert(END, item)

    # Results
    Label(window, text="Results:", font="Helvetica 12").place(x=20, y=420)
    results = Text(window,
                   font="Helvetica 12",
                   height=18,
                   width=105,
                   state='disabled')
    results.place(x=20, y=440)

    # Entry
    first_entry = Label(window, text="First word:", font="Helvetica 14")
    first_entry.place(x=550, y=240)
    input_first_entry = StringVar()
    Entry(window, font="Helvetica 12",
          textvariable=input_first_entry).place(x=675, y=242)

    # Entry
    second_entry = Label(window, text="Second word:", font="Helvetica 14")
    second_entry.place(x=550, y=300)
    input_second_entry = StringVar()
    Entry(window, font="Helvetica 12",
          textvariable=input_second_entry).place(x=675, y=302)

    # Querys
    Label(window, text="Querys:", font="Helvetica 12").place(x=240, y=200)
    querys = Listbox(window,
                     height=7,
                     width=30,
                     font="Helvetica 12",
                     exportselection=0)
    querys.place(x=240, y=220)
    scrollbar = Scrollbar(window, orient="horizontal")
    scrollbar.place(x=240, y=360, width=270)
    scrollbar.config(command=querys.xview)

    querys.bind('<<ListboxSelect>>',
                lambda evt: onselect(evt, first_entry, second_entry))

    for item in possible_querys:
        querys.insert(END, item)

    # Button search
    Button(
        window,
        font="Helvetica 12",
        text="Search",
        command=lambda: search(
            input_first_entry, input_second_entry, relations, querys, results,
            window, possible_querys, possible_relations, Relations)).place(
                x=890, y=270)

    # Ejecuta la ventana
    window.mainloop()
예제 #28
0
파일: app.py 프로젝트: YodaPY/Chatbot
    def layout(self) -> None: 
        self.master.deiconify() 
        self.master.title("Chatbot") 
        self.master.resizable(
            width = False, 
            height = False
        ) 
        self.master.configure(
            width = 470,
            height = 550, 
            bg = "#17202A"
        )

        self.line = Label(
            self.master,
            width = 450, 
            bg = "#ABB2B9"
        ) 
          
        self.line.place(
            relwidth = 1, 
            rely = 0.07, 
            relheight = 0.012) 
          
        self.text_cons = Text(
            self.master, 
            width = 20,  
            height = 2, 
            bg = "#17202A", 
            fg = "#EAECEE", 
            font = "Helvetica 14",  
            padx = 5, 
            pady = 5
        ) 
          
        self.text_cons.place(
            relheight = 0.745, 
            relwidth = 1,  
            rely = 0.08
        ) 
          
        self.label_bottom = Label(
            self.master, 
            bg = "#ABB2B9", 
            height = 80
        ) 
          
        self.label_bottom.place(
            relwidth = 1, 
            rely = 0.825
        ) 
          
        self.entry_msg = Entry(
            self.label_bottom, 
            bg = "#2C3E50", 
            fg = "#EAECEE", 
            font = "Helvetica 13"
        ) 
          
        self.entry_msg.place(
            relwidth = 0.74, 
            relheight = 0.06, 
            rely = 0.008, 
            relx = 0.011
        ) 
          
        self.entry_msg.focus() 
    
        self.button_msg = Button(
            self.label_bottom, 
            text = "Send", 
            font = "Helvetica 10 bold",  
            width = 20, 
            bg = "#ABB2B9", 
            command = lambda : self.send(self.entry_msg.get())
        ) 
          
        self.button_msg.place(
            relx = 0.77, 
            rely = 0.008, 
            relheight = 0.06,  
            relwidth = 0.22
        ) 
          
        self.text_cons.config(
            cursor = "arrow"
        ) 
          
        scrollbar = Scrollbar(self.text_cons) 
           
        scrollbar.place(
            relheight = 1, 
            relx = 0.974
        ) 
          
        scrollbar.config(
            command = self.text_cons.yview
        ) 
          
        self.text_cons.config(
            state = DISABLED
        )
예제 #29
0
buttonShowPoints = createButton(window, "показать точки", (15, 2), 
    partial(showPoints, placeGraph, listAllPoint))

# set location
placeGraph.pack(side=RIGHT)

listBox.place(x=5, y=400, anchor="nw")
listBox2.place(x=240, y=400, anchor="nw")

entryX.place(x=40, y=35, anchor="nw")
entryY.place(x=160, y=35, anchor="nw")
entryType.place(x=330, y=35, anchor="nw")

labelX.place(x=5, y=37)
labelY.place(x=120, y=37)
labelType.place(x=205, y=37)
labelEntry.place(x=5, y=8, anchor="nw")
label1Type.place(x=5, y=370)
label2Type.place(x=270, y=370)

buttonShowPoints.place(x=5, y=80, anchor="nw")
buttonAdd.place(x=5, y=130, anchor="nw")
buttonRemove.place(x=5, y=180, anchor="nw")
buttonEdit.place(x=5, y=230, anchor="nw")
buttonCreateGraph.place(x=5, y=280, anchor="nw")

scrollbar.place(x=190, y=400)
scrollbar2.place(x=425, y=400)

window.mainloop()
예제 #30
0
class Mainwindow(Frame):

    def __init__(self, height, width, server_host, users_list, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.height = height
        self.width = width
        self.server_host = server_host
        self.pack()
        self.createWidgets()
        self.setupFunctions()
        self.insert_text("Has entrado a la conversación!")
        self.add_connect(users_list[0])

    def createWidgets(self):
        self.chat_browser_scrollBar = Scrollbar(self.master)
        self.chat_browser_scrollBar.place(x=self.width-15, y=0, height=self.height*0.5)
        self.chat_browser = Text(self.master, yscrollcommand=self.chat_browser_scrollBar.set)
        self.chat_browser.place(x=0, y=0, width=self.width-15, height=self.height * 0.5)
        self.chat_browser.config(state=DISABLED)
        self.chat_browser_scrollBar.config(command=self.chat_browser.yview)
        self.text_writter = Text(self.master)
        self.text_writter.place(x=0, y=(self.height * 0.5) + 5, height=140)
        self.connected_list = Listbox(self.master)
        self.connected_list.place(x=self.width + 5, y=0, height=self.height * 0.5, width=self.width * 0.44)
        self.send_button = Button(self.master, text="Enviar", command=self.send_message)
        self.send_button.place(x=self.width * 1.22, y=self.height / 2 + 15, height=40, width=100)
        self.clear_button = Button(self.master, text="Borrar", command=self.clear_text)
        self.clear_button.place(x=self.width * 1.22, y=self.height / 2 + 80, height=40, width=100)


    def setupFunctions(self):
        self.text_writter.bind_all("<Return>", self.send_key_pressed)
        self.text_writter.bind_all("<BackSpace>", self.clear_key_pressed)

    def send_key_pressed(self, event):
        self.send_message()

    def clear_key_pressed(self, event):
        self.clear_text()

    def receive_message(self, host, message):
        text = host+":\n\t"+message
        self.insert_text(text)

    def insert_text(self, message):
        message += "\n"
        self.chat_browser.config(state=NORMAL)
        self.chat_browser.insert("end", message)
        self.chat_browser.config(state=DISABLED)
        self.chat_browser.see("end")

    def add_connect(self, item):
        color = "white"
        if self.connected_list.size() % 2 == 1:
            color = "#eaeae1"
        self.connected_list.insert("end", item)
        self.connected_list.itemconfig("end", bg=color)

    def delete_connect(self, item, list):
        list.remove(item)
        self.connected_list.delete(0, "end")
        for i in list:
            self.add_connect(i)

    def reset_connected_list(self, list):
        self.connected_list.delete(0, "end")
        for i in list:
            self.add_connect(i)

    def clear_text(self):
        self.text_writter.delete("1.0", "end")

    def send_message(self, text=None):
        message = text
        if not message:
            message = self.text_writter.get("1.0", "end")
            message = message.strip()
            self.text_writter.delete("1.0", "end")
        if not message:
            return

        print("Enviando mensaje:", message)
        start_new_thread(self.send_sock, (message,))

    def send_sock(self, message):
        message = message.encode(encoding="UTF-8")
        sock = socket(AF_INET, SOCK_STREAM)
        sock.connect((self.server_host))
        sock.send(message)
        sock.close()
예제 #31
0
    cliks += 1
    if cliks > 1:
        v = askyesno("Proceed with caution", "Are you the developer?")
        if v:
            for i in range(20):
                showerror("Big mistake", "You have activated my trap card")
        cliks = 0


# Setting up Pluggy's GUI
top.title("Pluggy")
top.iconbitmap("pluggy.ico")

textarea = Text(top, height=6, width=30)
scrollbar = Scrollbar(top, command=textarea.yview)
scrollbar.place(in_=textarea, relx=1.0, relheight=1.0, bordermode="outside")
textarea.grid(row=0, column=1, sticky=N + E + S + W, padx=30, pady=10)

rightbtns = Frame(top)
browserbuttons = Frame(rightbtns)
popbtn = Button(browserbuttons, text="Start Browser", command=pop_a_window)
testbtn = Button(browserbuttons,
                 text="Test program",
                 command=lambda: test_program(textarea, top))
runbtn = Button(browserbuttons,
                text="Run program",
                command=lambda: run_program(textarea, top))
quitbtn = Button(browserbuttons, text="End program", command=end_program)
popbtn.pack(side=LEFT, padx=5)
testbtn.pack(side=LEFT, padx=5)
runbtn.pack(side=LEFT, padx=5)
예제 #32
0
파일: start_app.py 프로젝트: uditsg/chatbot
    # Create Button to send message
    SendButton = Button(
        base,
        font=("Verdana", 12, "bold"),
        text="Send",
        width="12",
        height=5,
        bd=0,
        bg="blue",
        activebackground="#ffffff",
        fg="#ffffff",
        command=send,
    )

    # Create the box to enter message
    EntryBox = Text(base,
                    bd=0,
                    bg="grey",
                    width="29",
                    height="5",
                    font="Arial")

    # Place all components on the screen
    scrollbar.place(x=376, y=6, height=386)
    ChatLog.place(x=6, y=6, height=386, width=370)
    EntryBox.place(x=128, y=401, height=90, width=265)
    SendButton.place(x=6, y=401, height=90)

    base.mainloop()