Estoy haciendo un programa con muchos programas a la vez, y en el menu hay botones que ejecutan diferentes aplicaciones
Entonces, primero hay un boton para ejecutar la calculadora, como la caluladora no necesita imagenes ni acceder a un archivo JSON, se ejecuta sin problemas pero todo el codigo lo tengo guardado en una funcion llamada main
Luego, hay un boton que deberia ejecutar un reproductor de musica, PERO ese SI NECESITA IMAGENES, entonces no funciona, me aparece un error
Codigo del MENU:
import repcarpeta.repmain # Aca importo: En la carpeta "repcarpeta" el archivo "repmain.py"
# Y aca se necesita ejecutar en una funcion:
def openRep():
repcarpeta.repmain.main() # Esto no funciona, el programa no se ejecuta porque necesita acceder a una carpeta externa con las imagenes necesarias
Entonces... ¿Como hago para ejecutar todo un script? ¿O hay una solucion a esto?
Saludos!
EDIT: Agrego la carpeta y los subdirectorios que hay en mi programa:
Principalmente, el programa accede a 2 carpetas, una llamada "assets", donde se encuentran todas las imagenes necesarias; Y la ootra seria su propia carpeta, donde accede a un archivo JSON
repcarpeta:
repdata.json
repmain.py
assets:
Aqui hay solo imagenes, en formatos JPG y PNG
Salida: tkinter.TclError: image "pyimage5" doesn't exist
Codigo entero:
import json
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import pytube;
from tkinter import filedialog as fd
from pygame import mixer
import pyperclip;
import webbrowser;
mixer.init()
isplaying = False
def importSong():
songs = fd.askopenfilenames(initialdir="/", title="Elije cancion(es)!", filetypes=(("MP3 Files (.mp3)", "*.mp3"), ("OGG Files (.ogg)", "*.ogg"), ("WAW Files (.waw)", "*.waw"), ("Todos los archivos", "*.*")))
for song in songs:
song = song.replace("C:/Users/User/Downloads/", "")
song = song.replace(".mp3", "")
queue.insert(END, song)
i = 0
def play():
global i
global openMusic, isplaying, o, volumen
if (isplaying):
mixer.music.pause()
i = 1
isplaying = False
else:
if (i == 1):
mixer.music.unpause()
isplaying = True
else:
try:
song = queue.get(ACTIVE)
song = f'{song}.mp3'
mixer.music.load(song)
mixer.music.play(loops=0)
isplaying = True
except:
messagebox.showerror("Error!", "Se ha producido un error! Puede que no hayas importado canciones a la lista. Si no es asi... Asegurate de dejar seleccionada una cancion en la lista de canciones para que se reproduzca la cancion!")
def download():
global openMusic, entry
i = 0
try:
url = entry.get();
if (url == ""):
messagebox.showinfo("Informacion faltante", "Introduce un URL en la entrada de texto de la derecha")
i = 1
else:
youtube = pytube.YouTube(url);
except:
messagebox.showerror("Error", "El URL no es valido")
i = 1
if (i == 0):
try:
directory = fd.askdirectory(initialdir = "/",title = "Seleccione destinatario a guardar cancion (SE RECOMIENDA EN CARPETA)")
print(directory)
video = youtube.streams.get_audio_only();
messagebox.showinfo("Descarga lista", "Su descarga esta lista, recuerde que su conexion debe ser estable")
video.download(directory);
messagebox.showinfo("Descarga exitosa", "Su cancion se ha descargado, importela para poder reproducirla")
entry.insert(END, "");
openMusic = video
except:
messagebox.showerror("Error", "Ha ocurrido un error al descargar, probablemente tu link no es valido. Prueba otra vez, revisa tu coneccion o intentalo mas tarde.")
else:
pass
def move(e):
window.geometry(f'+{e.x_root}+{e.y_root}')
p = 1
def nextsong():
try:
prox = queue.curselection()
prox = prox[0]+1
song = queue.get(prox)
song = f'{song}.mp3'
mixer.music.load(song)
mixer.music.play(loops=0)
queue.selection_clear(0, END)
queue.activate(prox)
last = None
queue.selection_set(prox, last)
except:
messagebox.showerror("Error!", "Asegurate de dejar seleccionada una cancion en la lista de canciones para que se reconozca la siguiente cancion!")
def lastsong():
try:
prox = queue.curselection()
prox = prox[0]-1
song = queue.get(prox)
song = f'{song}.mp3'
mixer.music.load(song)
mixer.music.play(loops=0)
queue.selection_clear(0, END)
queue.activate(prox)
last = None
queue.selection_set(prox, last)
except:
messagebox.showerror("Error!", "Asegurate de dejar seleccionada una cancion en la lista de canciones para que se reconozca la cancion anterior!")
def deleteSong():
queue.delete(ANCHOR)
mixer.music.stop()
def clearQueue():
queue.delete(0, END)
mixer.music.stop()
def updateVolume(event):
global volumen
dir = "ecordaconfigs.json"
data = {
"volume" : mixer.music.get_volume()*1.0
}
with open(dir, 'w') as arch:
json.dump(data, arch)
y = float(int(volumen.get())*0.1)
mixer.music.set_volume(y)
def main():
global window, entry, queue, volumen
global song1, song2, song3, song4, song5
window = Tk()
window.geometry("800x500")
window.overrideredirect(True)
titleBar = Frame(window, bg="#000000", relief="raised", bd=0)
titleBar.pack(expand=0, fill=X)
titleBar.bind("<B1-Motion>", move)
titleLabel = Label(titleBar, bg="black", relief="raised", bd=0)
titleLabel.pack(side=LEFT, pady=4)
closeWindow = Label(titleBar, text=" X ", font=("Arial Blonded", 15),bg="black", fg="red")
closeWindow.pack(side=RIGHT, pady=4)
closeWindow.bind("<Button-1>", exit)
bgI = Image.open('assets/bgEcorda.png')
window.bgI = ImageTk.PhotoImage(bgI)
bg = Label(window, image=window.bgI,bd=0, relief=SUNKEN);bg.pack();bg.place();bg.config(width=800, height=500)
playI = Image.open('assets/play.png')
playI = playI.resize((80, 80))
window.playI = ImageTk.PhotoImage(playI)
downloadB = Button(window, text="Descargar", bg="purple", fg="white", width=10, height=2,bd=0, command=download);downloadB.pack();downloadB.place(x=530, y= 235)
entry = Entry(window, width=35, bg="purple", fg="white", bd=20);entry.pack();entry.place(x= 270, y= 225)
playB = Button(window, height=80, width=80,image=window.playI, bd=0, command=play);playB.pack();playB.place(x=325, y= 400)
importB = Button(window, height=5, width=8, text="IMPORTAR",bd=0, command=importSong);importB.pack();importB.place(x=200, y=400)
nextB = Button(window, height=5, width=7, text="SIGUIENTE", bd=0, command=nextsong);nextB.pack();nextB.place(x=415, y=400)
lastB = Button(window, height=5, width=6, text="VOLVER", bd=0, command=lastsong);lastB.pack();lastB.place(x=270, y=400)
volumen = ttk.Scale(window, to = 0.0, from_ = 10.0, orient='vertical',length=90)
volumen.pack();volumen.place(x= 168, y= 396);volumen.set(10)
queue = Listbox(window, bg="violet", fg= "black", width=60,selectbackground="black", selectforeground="white");queue.pack();queue.place(x= 216, y= 35)
clear = Button(window, height=5, width=5, text="CLEAR", bd=0, command= clearQueue);clear.pack();clear.place(x=478, y=400)
deleteSel = Button(window, height=5, width=7, text="ELIMINAR", bd=0, command= deleteSong);deleteSel.pack();deleteSel.place(x=525, y=400)
window.bind("<B1-Motion>", updateVolume)
window.mainloop()
# main()
EDIT 2: Por peticion de lso comentarios, dejo el codigo del menu:
from time import strftime
from tkinter import *
from tkinter import messagebox
from sys import exit
import datetime
from PIL import Image, ImageTk
import calculator.supcalculator
import ecorda.ecordamain
def openCalculator():
calculator.supcalculator.start()
def openEcorda():
ecorda.ecordamain.main()
def move(e):
window.geometry(f'+{e.x_root}+{e.y_root}')
def pos(event):
global x, y
x = event.x
y = event.y
def mover(event):
global x, y
deltax = event.x - x
deltay = event.y - y
window.geometry("+%s+%s" % (window.winfo_x() +
deltax, window.winfo_y() + deltay))
window.update()
def openPrimitive():
w = Tk()
w.title("Ejecutar Sistema de Desarrollo")
W.geometry("150x200")
w.mainloop()
def updateTime():
global timetext, timeText
hour = strftime("%H:%M (%Z)")
day = strftime("%A")
nDay = strftime("%d")
if (day == "Monday"):
day = "Lunes"
elif (day == "Tuesday"):
day = "Martes"
elif (day == "Wednesday"):
day = "Miercoles"
elif (day == "Thursday"):
day = "Jueves"
elif (day == "Friday"):
day = "Viernes"
elif (day == "Saturday"):
day = "Sabado"
elif (day == "Sunday"):
day = "Domingo"
time = datetime.datetime.now()
timetext = ("Bienvenido | " + day + " " + nDay + " de "
timeText.config(text=timetext)
timeText.after(1, updateTime)
def start():
global timeText, time, timetext
time = datetime.datetime.now()
timetext = ("Bienvenido | " + str(time.strftime("%d"))
global window
window = Tk()
window.configure(bg="#000000")
window.geometry("1100x650")
window.overrideredirect(1)
## ICONS ##
# SupCalculator
btn_calculator = Image.open('assets/calculator.png')
btn_calculator = btn_calculator.resize((125, 125))
window.btn_calculator = ImageTk.PhotoImage(btn_calculat
# Primitive and NEXT
btn_primitive = Image.open('assets/console.jpg')
btn_primitive = btn_primitive.resize((125, 125))
window.btn_primitive = ImageTk.PhotoImage(btn_primitiv
# Ecorda
btn_ecorda = Image.open('assets/music.png')
btn_ecorda = btn_ecorda.resize((125, 125))
window.btn_ecorda = ImageTk.PhotoImage(btn_ecorda)
# IText
btn_itext = Image.open('assets/txtproccesor.jpg')
btn_itext = btn_itext.resize((125, 125))
window.btn_itext = ImageTk.PhotoImage(btn_itext)
###########
titleBar = Frame(window, bg="#000000", relief="raised",
titleBar.pack(expand=0, fill=X)
titleBar.bind("<B1-Motion>", move)
titleLabel = Label(titleBar, bg="black", relief="raised
titleLabel.pack(side=LEFT, pady=4)
closeWindow = Label(titleBar, text=" X ", font=("Ar
closeWindow.pack(side=RIGHT, pady=4)
closeWindow.bind("<Button-1>", exit)
timeText = Label(titleBar, text=timetext, bg="black", f
timeText.pack()
timeText.place(x=10, y=2.5)
calculator = Button(window, image=window.btn_calculator
calculator.pack()
calculator.place(x=45, y=70)
primitive = Button(window, image=window.btn_primitive,
primitive.pack()
primitive.place(x=210, y=70)
ecorda = Button(window, image=window.btn_ecorda, width=
ecorda.pack()
ecorda.place(x=370, y=70)
itext = Button(window, image=window.btn_itext, width=12
itext.pack()
itext.place(x=530, y=70)
updateTime()
window.bind("<ButtonPress-1>", pos)
window.bind("<B1-Motion>", mover)
window.mainloop()
start()
EDIT 3: Peticion de los comentarios, dejo la carpeta de assets
https://drive.google.com/drive/folders/17mpoORmhfupGvCYNBFfVRDAiaU3WrcTV?usp=sharing