Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- import tkinter.ttk as ttk
- from tkinter import scrolledtext as st
- import tkinter.font as font
- from tkinter import filedialog
- import threading
- import imageio
- from PIL import Image, ImageTk
- import os
- import speech_recognition as sr
- from tkinter import messagebox
- from shutil import copyfile
- import re
- import sys
- # Re-run the program with admin rights
- #ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
- class CustomNotebook(ttk.Notebook):
- """A ttk Notebook with close buttons on each tab"""
- __initialized = False
- def __init__(self, *args, **kwargs):
- if not self.__initialized:
- self.__initialize_custom_style()
- self.__inititialized = True
- kwargs["style"] = "CustomNotebook"
- ttk.Notebook.__init__(self, *args, **kwargs)
- self._active = None
- self.bind("<ButtonPress-1>", self.on_close_press, True)
- self.bind("<ButtonRelease-1>", self.on_close_release)
- def on_close_press(self, event):
- """Called when the button is pressed over the close button"""
- element = self.identify(event.x, event.y)
- if "close" in element:
- index = self.index("@%d,%d" % (event.x, event.y))
- self.state(['pressed'])
- self._active = index
- def on_close_release(self, event):
- """Called when the button is released over the close button"""
- if not self.instate(['pressed']):
- return
- element = self.identify(event.x, event.y)
- index = self.index("@%d,%d" % (event.x, event.y))
- if "close" in element and self._active == index:
- self.forget(index)
- self.event_generate("<<NotebookTabClosed>>")
- self.state(["!pressed"])
- self._active = None
- def __initialize_custom_style(self):
- style = ttk.Style()
- self.images = (
- tk.PhotoImage("img_close", data='''
- R0lGODlhCAAIAMIBAAAAADs7O4+Pj9nZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
- d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
- 5kEJADs=
- '''),
- tk.PhotoImage("img_closeactive", data='''
- R0lGODlhCAAIAMIEAAAAAP/SAP/bNNnZ2cbGxsbGxsbGxsbGxiH5BAEKAAQALAAA
- AAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU5kEJADs=
- '''),
- tk.PhotoImage("img_closepressed", data='''
- R0lGODlhCAAIAMIEAAAAAOUqKv9mZtnZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
- d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
- 5kEJADs=
- ''')
- )
- style.element_create("close", "image", "img_close",
- ("active", "pressed", "!disabled", "img_closepressed"),
- ("active", "!disabled", "img_closeactive"), border=8, sticky='')
- style.layout("CustomNotebook", [("CustomNotebook.client", {"sticky": "nswe"})])
- style.layout("CustomNotebook.Tab", [
- ("CustomNotebook.tab", {
- "sticky": "nswe",
- "children": [
- ("CustomNotebook.padding", {
- "side": "top",
- "sticky": "nswe",
- "children": [
- ("CustomNotebook.focus", {
- "side": "top",
- "sticky": "nswe",
- "children": [
- ("CustomNotebook.label", {"side": "left", "sticky": ''}),
- ("CustomNotebook.close", {"side": "left", "sticky": ''}),
- ]
- })
- ]
- })
- ]
- })
- ])
- def msearch():
- global label
- try:
- label.master.destroy()
- except:
- pass
- busqueda=entryname_valor.get()
- #por nombre
- lista=os.listdir("C:\u005cUsers\u005cD\u005cBase de datos financiera")
- res = [i for i in lista if busqueda in i]
- #por contenido
- import glob
- #for result in [txt for txt in os.listdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005crana") if txt.endswith(".txt")]:
- # print(result)
- listatexto=glob.glob("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c*\u005c*.txt")
- #print(listatexto,type(listatexto))
- lista_match=[]
- group =tk.LabelFrame(tab_search, text="Resultados", padx=10, pady=10)
- group.pack(side=tk.BOTTOM)
- for i in listatexto:
- with open(i) as f:
- if busqueda in f.read():
- lista_match.append(i)
- res_clean=[]
- for i in res:
- i='C:\\Users\\D\\Base de datos financiera\\'+i+'\\'+i+".txt"
- res_clean.append(i)
- definitiva=res_clean+lista_match
- definitiva=set(definitiva)
- print(definitiva)
- resultados_lista=[]
- for i in definitiva:
- filename=os.path.basename('\\'+i)
- somestring='this is some string rec'
- somestring = re.sub('.txt$', '', filename)
- resultados_lista.append(somestring)
- print(resultados_lista)
- #for i in resultados_lista:
- #v=tk.StringVar()
- #resultado_label =tk.Label(tab1, textvariable=v,cursor="hand2")
- #v.set(i)
- #f = font.Font(resultado_label, resultado_label.cget("font"))
- #f.configure(underline=True)
- #resultado_label.bind("<Button-1>",lambda e: abrir_resultado(i))
- #resultado_label.pack(side=tk.BOTTOM)
- #resultado_label.configure(font=f)
- for i,url in enumerate(resultados_lista):
- v=tk.StringVar()
- #ponia tab1 en la linea de abajo
- tabName=tabControl.select()
- print(tabName)
- textWidget = tabControl.nametowidget(tabName)
- print(textWidget)
- label=tk.Label(group,textvariable=v, cursor="hand2")
- v.set(url)
- f = font.Font(label, label.cget("font"))
- f.configure(underline=True)
- label.pack(side=tk.BOTTOM)
- label.after(60000, label.pack_forget)
- label.bind("<Button-1>",lambda e,url=url:abrir_resultado(url))
- class SearchTab(ttk.Frame, CustomNotebook):
- def __init__(self,main_window):
- super().__init__(main_window)
- global entryname_valor
- entryname_valor=tk.StringVar()
- titulo =tk.Label(self, text="Introduce tu búsqueda")
- titulo.config(font=("Courier", 25))
- titulo.pack()
- mEntryname = tk.Entry(main_window, width=50, font=("Courier", 20), textvariable=entryname_valor).place(width=750,height=50,x=0, y=100)
- mSearch = tk.Button(main_window,text='Search',bg='white', command = msearch, height=5, width=15, font=fuente).pack(side=tk.BOTTOM)
- fuente2 = font.Font(family='Herculanum', size=12, weight='bold')
- top = tk.Tk()
- top.title("Base de datos financiera")
- top.geometry("750x500")
- fuente = font.Font(family='Herculanum', size=17, weight='bold')
- tabControl = CustomNotebook(top)
- tab_search = SearchTab(tabControl)
- tabControl.add(tab_search, text='Búsqueda')
- tabControl.pack(expand=1, fill="both")
- tab2 = ttk.Frame(tabControl)
- tabControl.add(tab2, text='Editar')
- tabControl.pack(side=tk.TOP)
- tab3 = ttk.Frame(tabControl)
- tabControl.add(tab3, text='Añadir nuevo')
- tabControl.pack(side=tk.TOP)
- def restart_program(hey):
- """Restarts the current program.
- Note: this function does not return. Any cleanup action (like
- saving data) must be done before calling this function."""
- #python = sys.executable
- #os.execl(python, python, * sys.argv)
- top.destroy()
- top.mainloop()
- def abrir_video():
- os.startfile("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+nombre+"\u005c"+nombre+".mp4")
- def guardar():
- #MsgBox= messagebox.askyesno('¿Quieres guardar los cambios en este concepto? (incluidos vídeo, texto y título)')
- #if MsgBox == 'yes':
- #print("yes")
- #else:
- #print("no")
- shutil.rmtree("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+nombre)
- titulo_nuevo=entrytitulo_resultado_valor.get()
- texto_nuevo=scr_resultado.get('1.0', 'end')
- os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo)
- file_edit= open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".txt","w")
- file_edit.write(texto_nuevo)
- file_edit.close()
- if video_añadido in globals():
- shutil.copyfile(video_añadido, "C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".mp4")
- def añadir_video():
- global video_añadido
- video_añadido = filedialog.askopenfilename(initialdir = "/",title = "Selecciona el archivo",filetypes = (("Vídeo MP4 (*.mp4)","*mp4"),("all files","*.*")))
- def abrir_resultado(resultado):
- global nombre
- nombre=resultado
- frame = tk.Frame(tabControl)
- tabControl.add(frame, text=resultado)
- tabControl.select(frame)
- global scr_resultado
- scr_resultado = st.ScrolledText(frame, width=40, height=10, wrap=tk.WORD)
- scr_texto = open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+resultado+"\u005c"+resultado+".txt","r")
- contents =scr_texto.read()
- scr_texto.close()
- scr_resultado.insert(tk.INSERT, contents)
- scr_resultado.place(x=400, y=0)
- titulo_resultado =tk.Label(frame, text=resultado)
- titulo_resultado.config(font=("Courier", 25))
- titulo_resultado.place(x=86, y=0)
- global entrytitulo_resultado_valor
- entrytitulo_resultado_valor = tk.StringVar()
- #entrytitulo_resultado = tk.Entry(frame, width=50, font=("Courier", 20), textvariable=entrytitulo_resultado_valor).place(width=400,height=33,x=0, y=50)
- if os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+nombre+"\u005c"+nombre+".mp4") == True:
- video_resultado_si=tk.Button(frame,text='Abrir vídeo',bg='white', command = abrir_video, height=5, width=15, font=fuente2).place(x=50,y=90)
- #video_resultado_si=tk.Button(frame,text='Cambiar video',bg='white', command = añadir_video, height=5, width=15, font=fuente2).place(x=50,y=180)
- #else:
- #video_resultado_no=tk.Button(frame,text='Añadir video',bg='white', command = añadir_video, height=5, width=15, font=fuente2).place(x=50,y=90)
- #video_resultado=tk.Button(frame,text='Guardar',bg='white', command = guardar, height=5, width=15, font=fuente2).pack(side=tk.BOTTOM)
- #IMPORTANTE DARLE APARIENCIA DE LINK Y HACER ESTO -->https://stackoverflow.com/questions/11504571/clickable-tkinter-labels
- #https://stackoverflow.com/questions/11504571/clickable-tkinter-labels
- # # <-- here's what you're looking fo
- def show_frame(label):
- video = imageio.get_reader(video_name)
- for image in video.iter_data():
- image=Image.fromarray(image)
- image= image.resize((400,400), Image.ANTIALIAS)
- ## The (250, 250) is (height, width)
- frame_image = ImageTk.PhotoImage(image)
- label.config(image=frame_image)
- label.image = frame_image
- final()
- #monty.grid(column=0, row=0, padx=8, pady=4)
- #menuBar = tk.Menu(tab1)
- #top.config(menu=menuBar)
- #fileMenu = tk.Menu(menuBar, tearoff=0)
- #menuBar.add_cascade(label="Categorías", menu=fileMenu)
- #helpMenu = tk.Menu(menuBar, tearoff=0)
- #menuBar.add_cascade(label="Help", menu=helpMenu)
- fuente2 = font.Font(family='Herculanum', size=12, weight='bold')
- def final():
- my_label = tk.Label(tab3, width=200, height=200)
- my_label.place(x=500,y=300)
- thread = threading.Thread(target=show_frame, args=(my_label,))
- thread.daemon = 1
- thread.start()
- def iniciar():
- global video_name
- video_name = filedialog.askopenfilename(initialdir = "/",title = "Selecciona el archivo",filetypes = (("Vídeo MP4 (*.mp4)","*mp4"),("all files","*.*")))
- final()
- video=tk.Button(tab3,text='Seleccionar vídeo',bg='white', command = iniciar, height=5, width=15, font=fuente2).place(x=50,y=90)
- scr = st.ScrolledText(tab3, width=40, height=10, wrap=tk.WORD)
- scr.insert(tk.INSERT, "Introduce aquí las notas que quieras sobre el concepto en cuestión")
- scr.place(x=400, y=0)
- titulo3 =tk.Label(tab3, text="Título")
- titulo3.config(font=("Courier", 25))
- titulo3.place(x=86, y=0)
- entrytitulo_valor = tk.StringVar()
- entrytitulo = tk.Entry(tab3, width=50, font=("Courier", 20), textvariable=entrytitulo_valor).place(width=400,height=33,x=0, y=50)
- def guardar():
- import shutil
- titulo_nuevo=entrytitulo_valor.get()
- texto_nuevo=scr.get('1.0', 'end')
- os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera")
- if os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera") == True:
- try:
- os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo)
- file = open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".txt","w")
- file.write(texto_nuevo)
- file.close()
- try:
- shutil.copyfile(video_name, "C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".mp4")
- except:
- messagebox.showwarning("Aviso", "No has añadido ningún vídeo, quizás quieras editar el concepto")
- messagebox.showinfo("Éxito", "El concepto se ha creado con éxito")
- except Exception as e:
- print(e)
- messagebox.showerror("Error", "Este concepto ya existe, edítalo en vez de crear uno nuevo")
- elif os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera") == False:
- try:
- os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera")
- os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo)
- file = open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".txt","w")
- file.write(texto_nuevo)
- file.close()
- try:
- shutil.copyfile(video_name, "C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".mp4")
- except:
- messagebox.showwarning("Aviso", "No has añadido ningún vídeo, quizás quieras editar el concepto")
- messagebox.showinfo("Éxito", "El concepto se ha creado con éxito")
- except:
- messagebox.showerror("Error", "Este concepto ya existe, edítalo en vez de crear uno nuevo")
- else:
- print("algo falla")
- guardar = tk.Button(tab3,text='Guardar',bg='white', command = guardar, height=5, width=15, font=fuente).pack(side=tk.BOTTOM)
- def leftKey(event):
- total=tabControl.index(tk.END)
- b=tabControl.index(tabControl.select())
- print(b)
- if b == 0:
- tabControl.select(tab_id=total-1)
- else:
- tabControl.select(tab_id=b-1)
- def rightKey(event):
- total=tabControl.index(tk.END)
- b=tabControl.index(tabControl.select())
- print(b)
- if b == total-1:
- tabControl.select(tab_id=0)
- else:
- tabControl.select(tab_id=b+1)
- def voice(event):
- r = sr.Recognizer()
- with sr.Microphone() as source:
- print("Say something!")
- audio = r.listen(source)
- a= r.recognize_google(audio, language='es-ES')
- # recognize speech using Google Speech Recognition
- try:
- # for testing purposes, we're just using the default API key
- # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
- # instead of `r.recognize_google(audio)`
- print("Google Speech Recognition thinks you said " + a)
- except sr.UnknownValueError:
- print("Google Speech Recognition could not understand audio")
- except sr.RequestError as e:
- print("Could not request results from Google Speech Recognition service; {0}".format(e))
- w=a.split()
- print(w)
- dia=w[0]
- mes=w[2]
- año=w[4]
- print(dia, mes, año)
- diccionario = {'enero':'01', 'febrero':'02', 'marzo':'03', 'abril':'04', 'mayo':'05', 'junio':'06', 'julio':'07', 'agosto':'08', 'septiembre':'09', 'octubre':'10', 'noviembre':'11', 'diciembre':'12'}
- mes_numero=diccionario.get(mes)
- diastring=str(dia)
- if len(diastring) == 1:
- diastring="0"+diastring
- imagen=str(año)+'-'+str(mes_numero)+'-'+diastring+'.png'
- print(imagen)
- img = Image.open('C:\u005cUsers\u005cD\u005cDesktop\u005cResumen diario\u005cMetaTrader\u005c'+imagen)
- img.show()
- def voice2(event):
- r = sr.Recognizer()
- with sr.Microphone() as source:
- print("Say something!")
- audio = r.listen(source)
- a= r.recognize_google(audio, language='es-ES')
- # recognize speech using Google Speech Recognition
- try:
- # for testing purposes, we're just using the default API key
- # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
- # instead of `r.recognize_google(audio)`
- print("Google Speech Recognition thinks you said " + a)
- except sr.UnknownValueError:
- print("Google Speech Recognition could not understand audio")
- except sr.RequestError as e:
- print("Could not request results from Google Speech Recognition service; {0}".format(e))
- w=a.split()
- print(w)
- dia=w[0]
- mes=w[2]
- año=w[4]
- print(dia, mes, año)
- diccionario = {'enero':'01', 'febrero':'02', 'marzo':'03', 'abril':'04', 'mayo':'05', 'junio':'06', 'julio':'07', 'agosto':'08', 'septiembre':'09', 'octubre':'10', 'noviembre':'11', 'diciembre':'12'}
- mes_numero=diccionario.get(mes)
- imagen=str(año)+'-'+str(mes_numero)+'-'+str(dia)+'.mp4'
- print(imagen)
- os.startfile('C:\u005cUsers\u005cD\u005cDesktop\u005cResumen diario\u005cForexTester 4\u005c'+imagen)
- top.bind('<F1>', voice)
- top.bind('<F2>', voice2)
- top.bind('<Left>', leftKey)
- top.bind('<F3>', restart_program)
- top.bind('<Right>', rightKey)
- #top.bind('<Enter>', msearch)
- def añadir_busqueda():
- tab_nueva = ttk.Frame(tabControl)
- tabControl.add(tab_nueva, text='Búsqueda')
- tabControl.pack(expand=1, fill="both")
- monty = tk.LabelFrame(tab_nueva, text=' Monty Python ')
- titulo =tk.Label(tab_nueva, text="Introduce tu búsqueda")
- titulo.config(font=("Courier", 25))
- titulo.pack()
- entryname_valor = tk.StringVar()
- mEntryname = tk.Entry(tab_nueva, width=50, font=("Courier", 20), textvariable=entryname_valor).place(width=750,height=50,x=0, y=100)
- mSearch = tk.Button(tab_nueva,text='Search',bg='white', command = msearch, height=5, width=15, font=fuente).pack(side=tk.BOTTOM)
- fuente2 = font.Font(family='Herculanum', size=12, weight='bold')
- def donothing():
- print(tabControl.index("current"))
- menubar = tk.Menu(top)
- filemenu = tk.Menu(menubar, tearoff = 0)
- filemenu.add_command(label = "Búsqueda", command = añadir_busqueda)
- filemenu.add_command(label = "Editar", command = donothing)
- filemenu.add_command(label = "Añadir nuevo", command = donothing)
- menubar.add_cascade(label = "Abrir", menu = filemenu)
- top.config(menu = menubar)
- top.mainloop()
- #self.createButtons()
- #MENU-->https://stackoverflow.com/questions/14000944/finding-the-currently-selected-tab-of-ttk-notebook
- #https://python-forum.io/Thread-Tkinter-How-to-create-multilple-tabs-in-tkinter-from-different-classes
- #createWidgets("hey")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement