0
archivo=open("USERS.txt","a")
from tkinter import *
from tkinter import font
global User
global Password
############################################################
############################################################
class USER:
    def __init__(self):
        self.nick=""
        self.user=""
        self.password=""
        self.email=""
    def set_info(self,Nick,User,Password,Email):
        self.nick=Nick
        self.user=User
        self.password=Password
        self.email=Email
        archivo.write(self.nick)
        archivo.write(",")
        archivo.write(self.user)
        archivo.write(",")
        archivo.write(self.password)
        archivo.write(",")
        archivo.write(self.email)
        archivo.write("\n")
        archivo.close()
#############################################################
class Register(Frame):
    u=USER()
    def __init__(self):
        Frame.__init__(self)
        self.Lab=Frame(self)
        self.master.title('Register')
        self.master.geometry("300x300")
        self.Nick = StringVar()
        self.User = StringVar()
        self.Password = StringVar()
        self.Email = StringVar()
        self.nickn = Label(self.master, text="Nick Name:").place(x=50, y=30)
        self.Nic = Entry(self.master, textvariable=self.Nick)
        self.Nic.place(x=120, y=30)
        self.usernn = Label(self.master, text="UserName:").place(x=50, y=50)
        self.Use = Entry(self.master, textvariable=self.User)
        self.Use.place(x=120, y=50)
        self.passww = Label(self.master, text="Password: ").place(x=50, y=70)
        self.Passwor = Entry(self.master, textvariable=self.Password)
        self.Passwor.place(x=120, y=70)
        self.emi = Label(self.master, text="Email:").place(x=50, y=90)
        self.Emai = Entry(self.master, textvariable=self.Email)
        self.Emai.place(x=120, y=90)
        finish = Button(self.master, text="Continue", bg="green", command=self.gets).place(x=150, y=150)
    def close(self):
        self.destroy()
    def gets(self):
        u=USER()
        N = self.Nic.get()
        U = self.Use.get()
        P = self.Passwor.get()
        E = self.Emai.get()
        u.set_info(N,U,P,E)




##############################################
USERS=[] #lista de usuarios registrados
def ext_user(): #extrae la informacion de usuario del txt USERS
    dic={}
    archi=open("USERS.txt","r")
    b=archi.readline()
    while b != "": #ciclo para poder recorrer cada linea del txt
        user=b.split(",")
        user[3]=user[3][:-1]
        dic["nick"]=user[0]
        dic["user"]=user[1]
        dic["password"]=user[2]
        dic["email"]=user[3]
        USERS.append(dic) #agrego el diccionario con la info del usuario a la lista de usuarios
        b=archi.readline()
#####################################################
def login(User,Password):
    band=False
    user=User
    passW=Password
    for us in USERS:
        if us["user"]==user and us["password"]==passW:
            # llamar la funcion correspondiente
            band=True
    if band==False:
        vent=Tk()
        vent.title("Error login")
        vent.geometry("100x100")
        final=Button(vent,text="User or Password Error",bg="Red",command="close")
##############################################
class niveles(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Selec Level")
        self.master.geometry("800x600")
        self.Helvfont = font.Font(family="Arial", size=12, weight="bold")
        self.texto1=Label(self.master,text="Select an option",font=self.Helvfont,fg="steelblue").pack()
        self.Niv1=Button(self.master,bg="palegreen",width=28,height=3,text="Level 1",activebackground="lightseagreen").place(x=300,y=100)
        self.Niv2=Button(self.master,bg="springgreen",width=28,height=3,text="Level 2",activebackground="lightseagreen").place(x=300,y=155)
        self.Niv3=Button(self.master,bg="yellowgreen",width=28,height=3,text="Level 3",activebackground="lightseagreen").place(x=300,y=210)
        self.Niv4=Button(self.master,bg="olivedrab",width=28,height=3,text="Level 4",activebackground="lightseagreen").place(x=300,y=260)
        self.Niv5=Button(self.master,bg="darkolivegreen",width=28,height=3,text="Level 5",activebackground="lightseagreen").place(x=300,y=315)
        self.Niv6=Button(self.master,bg="darkgreen",width=28,height=3,text="Level 6",activebackground="lightseagreen").place(x=300,y=365)
        self.consults = Button(self.master, bg="Green", width=28, height=3, text="Statistics").place(x=300, y=420)


#####################################################

class Statistics(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Statistics")
        self.master.geometry("800x600")
        self.Helvfont = font.Font(family="Arial", size=12, weight="bold")
        self.texto1 = Label(self.master, text="Select an option", font=self.Helvfont, fg="steelblue").pack()
        self.con1 = Button(self.master, bg="palegreen", width=28, height=3, text="My top 5 matches",
                           activebackground="lightseagreen").place(x=300, y=100)
        self.con2 = Button(self.master, bg="springgreen", width=28, height=3, text="Top 10 of the best players",
                           activebackground="lightseagreen").place(x=300, y=155)
        self.con3 = Button(self.master, bg="yellowgreen", width=28, height=3, text="Average points for the games played",
                           activebackground="lightseagreen").place(x=300, y=210)
        self.con4 = Button(self.master, bg="olivedrab", width=28, height=3, text="Number of games saved",
                           activebackground="lightseagreen").place(x=300, y=260)
        self.con5 = Button(self.master, bg="darkolivegreen", width=28, height=3, text="Maximum level and score obtained",
                           activebackground="lightseagreen").place(x=300,y=315)


#################################################
class log(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title('Logeo')
        self.master.geometry("300x300")
        self.nombre_label = Label(self.master, text="UserName:").place(x=50, y=50)
        self.User= StringVar()
        self.Use= Entry(self.master, textvariable=self.User).place(x=120, y=50)
        self.last_label = Label(self.master, text="Password: ").place(x=50, y=70)
        self.Pass = StringVar()
        self.Password= Entry(self.master, textvariable=self.Pass,show="*")
        self.Password.place(x=120, y=70)
        finish = Button(self.master, text="Continue", bg="green",command=self.GetLog).place(x=150, y=150)
    def GetLog(self):
        U=self.User.get()
        P=self.Password.get()
        L=login(U,P)


#####################################
class menuprincipal(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Snake by Maco and Angel")
        self.master.geometry("800x600")
        self.boton1=Button(self.master,bg="Green",command=self.Log(),width=28,height=4,text="Login").place(x=300,y=240)
        self.boton2 = Button(self.master, bg="Green",command=self.Reg(), width=28, height=4, text="Register").place(x=300, y=330)
        self.boton3 = Button(self.master, bg="Green", width=28,command=self.EXIT(), height=4, text="Exit").place(x=300, y=425)
    def EXIT(self):
        self.master.destroy()
    def Log(self):
        log().mainloop()
    def Reg(self):
        Register().mainloop()
mP=menuprincipal()
mP.mainloop()

Quiero saber por que no me funciona esto, que está mal en este codigo, siempre me abre la ventana equivocada

1
  • Bienvenido a Stack Overflow en español Marco. Deberias tomarte algo de tiempo en redactar una buena pregunta. Solo dices 'me abre la ventana equivocada', estaría bien que explicaras que hace el código y que debería hacer porque nosotros no sabemos absolutamente nada de tu proyecto. En este caso dado que es Python no es relativamente sencillo dar con tu problema pero para obtener buenas respuestas nunca está de más facilitar la vida a los que te leen. Mirate recorrido de bienvenida y Cómo preguntar para más información sobre el sitio. Saludos.
    – FJSevilla
    el 4 jun. 2017 a las 21:12

1 respuesta 1

0

Cuando le pasas la función a ejecutar al constructor de tus botones en menuprincipal estas ejecutando esos métodos:

self.boton3 = Button(self.master, bg="Green", width=28,command=self.EXIT(), height=4, text="Exit").place(x=300, y=425)
                                                                        ^
                                                                        ^
                                                                        ^

Esto causa que nada más instanciar menuprincipal se lanze la ventana de login (command=self.Log()).

Debes pasar solo el nombre de la función, no ejecutarla:

self.boton1 = Button(self.master,bg="Green",command=self.Log,width=28,height=4,text="Login").place(x=300,y=240)
self.boton2 = Button(self.master, bg="Green",command=self.Reg, width=28, height=4, text="Register").place(x=300, y=330)
self.boton3 = Button(self.master, bg="Green", width=28,command=self.EXIT, height=4, text="Exit").place(x=300, y=425)

Por otro lado, el mainloop solo se lanza una vez. Si quieres crear ventanas secundarias usa toplevel o redibuja tu ventana principal (simplemente cambia el frame que se debe mostrar en la ventana en cada momento). Nunca puede haber más de una ventana principal en la misma GUI y toda la GUI debe correr bajo ese main-loop, y por consiguiente, en el mismo hilo.

Hay más cosas que puedes mejorar, los nombres de tus clases deberían empezar por mayúsculas. Por otro lado, ya que usas clases deberias crear una clase que se encargue de lanzar tu GUI y evitar el uso de variables globales que deben evitarse siempre que se pueda. Por otro lado, abres el archivo de texto pero nunca lo cierras apropiadamente, usa with para abrir o cierralo después de usarlo con .close().

1
  • Aun tengo una pregunta en cuanto lo que dijistes sobre utilizar toplevel, como puedo implemetarlo en mi codigo sin tener que desarmalo completamente o no existe manera?.Gracias el 4 jun. 2017 a las 23:07

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.