Advertisement
Guest User

Untitled

a guest
Sep 26th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.51 KB | None | 0 0
  1. import tkinter as tk
  2. import tkinter.ttk as ttk
  3. from tkinter import scrolledtext as st
  4. import tkinter.font as font
  5. from tkinter import filedialog
  6. import threading
  7. import imageio
  8. from PIL import Image, ImageTk
  9. import os
  10. import speech_recognition as sr
  11. from tkinter import messagebox
  12. from shutil import copyfile
  13. import re
  14. import sys
  15.  
  16. # Re-run the program with admin rights
  17. #ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
  18.  
  19. class CustomNotebook(ttk.Notebook):
  20. """A ttk Notebook with close buttons on each tab"""
  21.  
  22. __initialized = False
  23.  
  24. def __init__(self, *args, **kwargs):
  25. if not self.__initialized:
  26. self.__initialize_custom_style()
  27. self.__inititialized = True
  28.  
  29. kwargs["style"] = "CustomNotebook"
  30. ttk.Notebook.__init__(self, *args, **kwargs)
  31.  
  32. self._active = None
  33.  
  34. self.bind("<ButtonPress-1>", self.on_close_press, True)
  35. self.bind("<ButtonRelease-1>", self.on_close_release)
  36.  
  37. def on_close_press(self, event):
  38. """Called when the button is pressed over the close button"""
  39.  
  40. element = self.identify(event.x, event.y)
  41.  
  42. if "close" in element:
  43. index = self.index("@%d,%d" % (event.x, event.y))
  44. self.state(['pressed'])
  45. self._active = index
  46.  
  47. def on_close_release(self, event):
  48. """Called when the button is released over the close button"""
  49. if not self.instate(['pressed']):
  50. return
  51.  
  52. element = self.identify(event.x, event.y)
  53. index = self.index("@%d,%d" % (event.x, event.y))
  54.  
  55. if "close" in element and self._active == index:
  56. self.forget(index)
  57. self.event_generate("<<NotebookTabClosed>>")
  58.  
  59. self.state(["!pressed"])
  60. self._active = None
  61.  
  62. def __initialize_custom_style(self):
  63. style = ttk.Style()
  64. self.images = (
  65. tk.PhotoImage("img_close", data='''
  66. R0lGODlhCAAIAMIBAAAAADs7O4+Pj9nZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
  67. d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
  68. 5kEJADs=
  69. '''),
  70. tk.PhotoImage("img_closeactive", data='''
  71. R0lGODlhCAAIAMIEAAAAAP/SAP/bNNnZ2cbGxsbGxsbGxsbGxiH5BAEKAAQALAAA
  72. AAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU5kEJADs=
  73. '''),
  74. tk.PhotoImage("img_closepressed", data='''
  75. R0lGODlhCAAIAMIEAAAAAOUqKv9mZtnZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
  76. d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
  77. 5kEJADs=
  78. ''')
  79. )
  80.  
  81. style.element_create("close", "image", "img_close",
  82. ("active", "pressed", "!disabled", "img_closepressed"),
  83. ("active", "!disabled", "img_closeactive"), border=8, sticky='')
  84. style.layout("CustomNotebook", [("CustomNotebook.client", {"sticky": "nswe"})])
  85. style.layout("CustomNotebook.Tab", [
  86. ("CustomNotebook.tab", {
  87. "sticky": "nswe",
  88. "children": [
  89. ("CustomNotebook.padding", {
  90. "side": "top",
  91. "sticky": "nswe",
  92. "children": [
  93. ("CustomNotebook.focus", {
  94. "side": "top",
  95. "sticky": "nswe",
  96. "children": [
  97. ("CustomNotebook.label", {"side": "left", "sticky": ''}),
  98. ("CustomNotebook.close", {"side": "left", "sticky": ''}),
  99. ]
  100. })
  101. ]
  102. })
  103. ]
  104. })
  105. ])
  106.  
  107. def msearch():
  108. global label
  109. try:
  110. label.master.destroy()
  111. except:
  112. pass
  113. busqueda=entryname_valor.get()
  114. #por nombre
  115. lista=os.listdir("C:\u005cUsers\u005cD\u005cBase de datos financiera")
  116. res = [i for i in lista if busqueda in i]
  117. #por contenido
  118. import glob
  119. #for result in [txt for txt in os.listdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005crana") if txt.endswith(".txt")]:
  120. # print(result)
  121. listatexto=glob.glob("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c*\u005c*.txt")
  122. #print(listatexto,type(listatexto))
  123. lista_match=[]
  124. group =tk.LabelFrame(tab_search, text="Resultados", padx=10, pady=10)
  125. group.pack(side=tk.BOTTOM)
  126. for i in listatexto:
  127. with open(i) as f:
  128. if busqueda in f.read():
  129. lista_match.append(i)
  130. res_clean=[]
  131. for i in res:
  132. i='C:\\Users\\D\\Base de datos financiera\\'+i+'\\'+i+".txt"
  133. res_clean.append(i)
  134. definitiva=res_clean+lista_match
  135. definitiva=set(definitiva)
  136. print(definitiva)
  137. resultados_lista=[]
  138. for i in definitiva:
  139. filename=os.path.basename('\\'+i)
  140. somestring='this is some string rec'
  141. somestring = re.sub('.txt$', '', filename)
  142. resultados_lista.append(somestring)
  143. print(resultados_lista)
  144. #for i in resultados_lista:
  145. #v=tk.StringVar()
  146. #resultado_label =tk.Label(tab1, textvariable=v,cursor="hand2")
  147. #v.set(i)
  148. #f = font.Font(resultado_label, resultado_label.cget("font"))
  149. #f.configure(underline=True)
  150. #resultado_label.bind("<Button-1>",lambda e: abrir_resultado(i))
  151. #resultado_label.pack(side=tk.BOTTOM)
  152. #resultado_label.configure(font=f)
  153. for i,url in enumerate(resultados_lista):
  154. v=tk.StringVar()
  155. #ponia tab1 en la linea de abajo
  156. tabName=tabControl.select()
  157. print(tabName)
  158. textWidget = tabControl.nametowidget(tabName)
  159. print(textWidget)
  160. label=tk.Label(group,textvariable=v, cursor="hand2")
  161. v.set(url)
  162. f = font.Font(label, label.cget("font"))
  163. f.configure(underline=True)
  164. label.pack(side=tk.BOTTOM)
  165. label.after(60000, label.pack_forget)
  166. label.bind("<Button-1>",lambda e,url=url:abrir_resultado(url))
  167. class SearchTab(ttk.Frame, CustomNotebook):
  168. def __init__(self,main_window):
  169. super().__init__(main_window)
  170. global entryname_valor
  171. entryname_valor=tk.StringVar()
  172. titulo =tk.Label(self, text="Introduce tu búsqueda")
  173. titulo.config(font=("Courier", 25))
  174. titulo.pack()
  175. mEntryname = tk.Entry(main_window, width=50, font=("Courier", 20), textvariable=entryname_valor).place(width=750,height=50,x=0, y=100)
  176. mSearch = tk.Button(main_window,text='Search',bg='white', command = msearch, height=5, width=15, font=fuente).pack(side=tk.BOTTOM)
  177. fuente2 = font.Font(family='Herculanum', size=12, weight='bold')
  178.  
  179. top = tk.Tk()
  180. top.title("Base de datos financiera")
  181.  
  182. top.geometry("750x500")
  183. fuente = font.Font(family='Herculanum', size=17, weight='bold')
  184. tabControl = CustomNotebook(top)
  185. tab_search = SearchTab(tabControl)
  186. tabControl.add(tab_search, text='Búsqueda')
  187. tabControl.pack(expand=1, fill="both")
  188. tab2 = ttk.Frame(tabControl)
  189. tabControl.add(tab2, text='Editar')
  190. tabControl.pack(side=tk.TOP)
  191. tab3 = ttk.Frame(tabControl)
  192. tabControl.add(tab3, text='Añadir nuevo')
  193. tabControl.pack(side=tk.TOP)
  194.  
  195.  
  196. def restart_program(hey):
  197. """Restarts the current program.
  198. Note: this function does not return. Any cleanup action (like
  199. saving data) must be done before calling this function."""
  200. #python = sys.executable
  201. #os.execl(python, python, * sys.argv)
  202. top.destroy()
  203. top.mainloop()
  204.  
  205. def abrir_video():
  206. os.startfile("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+nombre+"\u005c"+nombre+".mp4")
  207.  
  208. def guardar():
  209. #MsgBox= messagebox.askyesno('¿Quieres guardar los cambios en este concepto? (incluidos vídeo, texto y título)')
  210. #if MsgBox == 'yes':
  211. #print("yes")
  212. #else:
  213. #print("no")
  214. shutil.rmtree("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+nombre)
  215. titulo_nuevo=entrytitulo_resultado_valor.get()
  216. texto_nuevo=scr_resultado.get('1.0', 'end')
  217. os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo)
  218. file_edit= open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".txt","w")
  219. file_edit.write(texto_nuevo)
  220. file_edit.close()
  221. if video_añadido in globals():
  222. shutil.copyfile(video_añadido, "C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".mp4")
  223.  
  224. def añadir_video():
  225. global video_añadido
  226. video_añadido = filedialog.askopenfilename(initialdir = "/",title = "Selecciona el archivo",filetypes = (("Vídeo MP4 (*.mp4)","*mp4"),("all files","*.*")))
  227.  
  228. def abrir_resultado(resultado):
  229. global nombre
  230. nombre=resultado
  231. frame = tk.Frame(tabControl)
  232. tabControl.add(frame, text=resultado)
  233. tabControl.select(frame)
  234. global scr_resultado
  235. scr_resultado = st.ScrolledText(frame, width=40, height=10, wrap=tk.WORD)
  236. scr_texto = open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+resultado+"\u005c"+resultado+".txt","r")
  237. contents =scr_texto.read()
  238. scr_texto.close()
  239. scr_resultado.insert(tk.INSERT, contents)
  240. scr_resultado.place(x=400, y=0)
  241. titulo_resultado =tk.Label(frame, text=resultado)
  242. titulo_resultado.config(font=("Courier", 25))
  243. titulo_resultado.place(x=86, y=0)
  244. global entrytitulo_resultado_valor
  245. entrytitulo_resultado_valor = tk.StringVar()
  246. #entrytitulo_resultado = tk.Entry(frame, width=50, font=("Courier", 20), textvariable=entrytitulo_resultado_valor).place(width=400,height=33,x=0, y=50)
  247. if os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+nombre+"\u005c"+nombre+".mp4") == True:
  248. 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)
  249. #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)
  250. #else:
  251. #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)
  252. #video_resultado=tk.Button(frame,text='Guardar',bg='white', command = guardar, height=5, width=15, font=fuente2).pack(side=tk.BOTTOM)
  253.  
  254.  
  255. #IMPORTANTE DARLE APARIENCIA DE LINK Y HACER ESTO -->https://stackoverflow.com/questions/11504571/clickable-tkinter-labels
  256. #https://stackoverflow.com/questions/11504571/clickable-tkinter-labels
  257. # # <-- here's what you're looking fo
  258.  
  259. def show_frame(label):
  260.  
  261. video = imageio.get_reader(video_name)
  262. for image in video.iter_data():
  263. image=Image.fromarray(image)
  264. image= image.resize((400,400), Image.ANTIALIAS)
  265. ## The (250, 250) is (height, width)
  266. frame_image = ImageTk.PhotoImage(image)
  267. label.config(image=frame_image)
  268. label.image = frame_image
  269. final()
  270.  
  271. #monty.grid(column=0, row=0, padx=8, pady=4)
  272.  
  273. #menuBar = tk.Menu(tab1)
  274. #top.config(menu=menuBar)
  275. #fileMenu = tk.Menu(menuBar, tearoff=0)
  276. #menuBar.add_cascade(label="Categorías", menu=fileMenu)
  277. #helpMenu = tk.Menu(menuBar, tearoff=0)
  278. #menuBar.add_cascade(label="Help", menu=helpMenu)
  279.  
  280. fuente2 = font.Font(family='Herculanum', size=12, weight='bold')
  281. def final():
  282. my_label = tk.Label(tab3, width=200, height=200)
  283. my_label.place(x=500,y=300)
  284. thread = threading.Thread(target=show_frame, args=(my_label,))
  285. thread.daemon = 1
  286. thread.start()
  287. def iniciar():
  288. global video_name
  289. video_name = filedialog.askopenfilename(initialdir = "/",title = "Selecciona el archivo",filetypes = (("Vídeo MP4 (*.mp4)","*mp4"),("all files","*.*")))
  290. final()
  291.  
  292.  
  293.  
  294. video=tk.Button(tab3,text='Seleccionar vídeo',bg='white', command = iniciar, height=5, width=15, font=fuente2).place(x=50,y=90)
  295. scr = st.ScrolledText(tab3, width=40, height=10, wrap=tk.WORD)
  296. scr.insert(tk.INSERT, "Introduce aquí las notas que quieras sobre el concepto en cuestión")
  297. scr.place(x=400, y=0)
  298. titulo3 =tk.Label(tab3, text="Título")
  299. titulo3.config(font=("Courier", 25))
  300. titulo3.place(x=86, y=0)
  301. entrytitulo_valor = tk.StringVar()
  302. entrytitulo = tk.Entry(tab3, width=50, font=("Courier", 20), textvariable=entrytitulo_valor).place(width=400,height=33,x=0, y=50)
  303. def guardar():
  304. import shutil
  305. titulo_nuevo=entrytitulo_valor.get()
  306. texto_nuevo=scr.get('1.0', 'end')
  307. os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera")
  308. if os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera") == True:
  309. try:
  310. os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo)
  311. file = open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".txt","w")
  312. file.write(texto_nuevo)
  313. file.close()
  314. try:
  315. shutil.copyfile(video_name, "C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".mp4")
  316. except:
  317. messagebox.showwarning("Aviso", "No has añadido ningún vídeo, quizás quieras editar el concepto")
  318. messagebox.showinfo("Éxito", "El concepto se ha creado con éxito")
  319. except Exception as e:
  320. print(e)
  321. messagebox.showerror("Error", "Este concepto ya existe, edítalo en vez de crear uno nuevo")
  322. elif os.path.exists("C:\u005cUsers\u005cD\u005cBase de datos financiera") == False:
  323. try:
  324. os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera")
  325. os.mkdir("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo)
  326. file = open("C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".txt","w")
  327. file.write(texto_nuevo)
  328. file.close()
  329. try:
  330. shutil.copyfile(video_name, "C:\u005cUsers\u005cD\u005cBase de datos financiera\u005c"+titulo_nuevo+"\u005c"+titulo_nuevo+".mp4")
  331. except:
  332. messagebox.showwarning("Aviso", "No has añadido ningún vídeo, quizás quieras editar el concepto")
  333. messagebox.showinfo("Éxito", "El concepto se ha creado con éxito")
  334. except:
  335. messagebox.showerror("Error", "Este concepto ya existe, edítalo en vez de crear uno nuevo")
  336.  
  337. else:
  338. print("algo falla")
  339.  
  340. guardar = tk.Button(tab3,text='Guardar',bg='white', command = guardar, height=5, width=15, font=fuente).pack(side=tk.BOTTOM)
  341.  
  342. def leftKey(event):
  343. total=tabControl.index(tk.END)
  344. b=tabControl.index(tabControl.select())
  345. print(b)
  346. if b == 0:
  347. tabControl.select(tab_id=total-1)
  348. else:
  349. tabControl.select(tab_id=b-1)
  350.  
  351. def rightKey(event):
  352. total=tabControl.index(tk.END)
  353. b=tabControl.index(tabControl.select())
  354. print(b)
  355. if b == total-1:
  356. tabControl.select(tab_id=0)
  357. else:
  358. tabControl.select(tab_id=b+1)
  359. def voice(event):
  360. r = sr.Recognizer()
  361. with sr.Microphone() as source:
  362. print("Say something!")
  363. audio = r.listen(source)
  364.  
  365. a= r.recognize_google(audio, language='es-ES')
  366. # recognize speech using Google Speech Recognition
  367. try:
  368. # for testing purposes, we're just using the default API key
  369. # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
  370. # instead of `r.recognize_google(audio)`
  371. print("Google Speech Recognition thinks you said " + a)
  372. except sr.UnknownValueError:
  373. print("Google Speech Recognition could not understand audio")
  374. except sr.RequestError as e:
  375. print("Could not request results from Google Speech Recognition service; {0}".format(e))
  376. w=a.split()
  377. print(w)
  378. dia=w[0]
  379. mes=w[2]
  380. año=w[4]
  381. print(dia, mes, año)
  382. 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'}
  383. mes_numero=diccionario.get(mes)
  384. diastring=str(dia)
  385. if len(diastring) == 1:
  386. diastring="0"+diastring
  387.  
  388. imagen=str(año)+'-'+str(mes_numero)+'-'+diastring+'.png'
  389. print(imagen)
  390. img = Image.open('C:\u005cUsers\u005cD\u005cDesktop\u005cResumen diario\u005cMetaTrader\u005c'+imagen)
  391. img.show()
  392. def voice2(event):
  393. r = sr.Recognizer()
  394. with sr.Microphone() as source:
  395. print("Say something!")
  396. audio = r.listen(source)
  397.  
  398. a= r.recognize_google(audio, language='es-ES')
  399. # recognize speech using Google Speech Recognition
  400. try:
  401. # for testing purposes, we're just using the default API key
  402. # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
  403. # instead of `r.recognize_google(audio)`
  404. print("Google Speech Recognition thinks you said " + a)
  405. except sr.UnknownValueError:
  406. print("Google Speech Recognition could not understand audio")
  407. except sr.RequestError as e:
  408. print("Could not request results from Google Speech Recognition service; {0}".format(e))
  409. w=a.split()
  410. print(w)
  411. dia=w[0]
  412. mes=w[2]
  413. año=w[4]
  414. print(dia, mes, año)
  415. 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'}
  416. mes_numero=diccionario.get(mes)
  417. imagen=str(año)+'-'+str(mes_numero)+'-'+str(dia)+'.mp4'
  418. print(imagen)
  419. os.startfile('C:\u005cUsers\u005cD\u005cDesktop\u005cResumen diario\u005cForexTester 4\u005c'+imagen)
  420.  
  421. top.bind('<F1>', voice)
  422. top.bind('<F2>', voice2)
  423. top.bind('<Left>', leftKey)
  424. top.bind('<F3>', restart_program)
  425. top.bind('<Right>', rightKey)
  426. #top.bind('<Enter>', msearch)
  427. def añadir_busqueda():
  428. tab_nueva = ttk.Frame(tabControl)
  429. tabControl.add(tab_nueva, text='Búsqueda')
  430. tabControl.pack(expand=1, fill="both")
  431. monty = tk.LabelFrame(tab_nueva, text=' Monty Python ')
  432. titulo =tk.Label(tab_nueva, text="Introduce tu búsqueda")
  433. titulo.config(font=("Courier", 25))
  434. titulo.pack()
  435. entryname_valor = tk.StringVar()
  436. mEntryname = tk.Entry(tab_nueva, width=50, font=("Courier", 20), textvariable=entryname_valor).place(width=750,height=50,x=0, y=100)
  437. mSearch = tk.Button(tab_nueva,text='Search',bg='white', command = msearch, height=5, width=15, font=fuente).pack(side=tk.BOTTOM)
  438. fuente2 = font.Font(family='Herculanum', size=12, weight='bold')
  439. def donothing():
  440. print(tabControl.index("current"))
  441. menubar = tk.Menu(top)
  442. filemenu = tk.Menu(menubar, tearoff = 0)
  443. filemenu.add_command(label = "Búsqueda", command = añadir_busqueda)
  444. filemenu.add_command(label = "Editar", command = donothing)
  445. filemenu.add_command(label = "Añadir nuevo", command = donothing)
  446. menubar.add_cascade(label = "Abrir", menu = filemenu)
  447. top.config(menu = menubar)
  448. top.mainloop()
  449. #self.createButtons()
  450. #MENU-->https://stackoverflow.com/questions/14000944/finding-the-currently-selected-tab-of-ttk-notebook
  451. #https://python-forum.io/Thread-Tkinter-How-to-create-multilple-tabs-in-tkinter-from-different-classes
  452. #createWidgets("hey")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement