Как открыть главное окно после успешного входа - PullRequest
0 голосов
/ 17 октября 2019

Я смотрю на питона. Я получил курс udemy, а также прочитал этот пост: Как открыть главное окно после успешного входа в Tkinter (PYTHON 3.6

Тем не менее, я не могу реализовать записанное событие. IЯ хочу открыть новое (главное) окно приложения desctop после входа в систему. По какой-то причине сценарий также неожиданно открывает третье окно. Я начинаю очень нервничать, работая с 2 das над этим материалом ...

Спасибо за помощь:)

from tkinter import Tk, Label, Button, messagebox
from tkinter import *

class AirsoftGunRack:


    ##### Main Window #####






    ##### Login Page #####


def __init__(self,master):
    """

    :type master: object
    """

    ##### Login Page #####

    self.master = master
    master.title("Login - Airsoft GunRack 3.0")
    master.geometry("450x230+450+170")


    # Creating describtions

    self.username = Label(master, text="Username:")
    self.username.place(relx=0.285, rely=0.298, height=20, width=55)

    self.password = Label(master, text="Password:")
    self.password.place(relx=0.285, rely=0.468, height=20, width=55)

    # Creating Buttons

    self.login_button = Button(master, text="Login")
    self.login_button.place(relx=0.440, rely=0.638, height=30, width=60)
    self.login_button.configure(command=self.login_user)

    self.exit_button = Button(master, text="Exit")  # , command=master.quit)
    self.exit_button.place(relx=0.614, rely=0.638, height=30, width=60)
    self.exit_button.configure(command=self.exit_login)

    # Creating entry boxes

    self.username_box = Entry(master)
    self.username_box.place(relx=0.440, rely=0.298, height=20, relwidth=0.35)

    self.password_box = Entry(master)
    self.password_box.place(relx=0.440, rely=0.468, height=20, relwidth=0.35)
    self.password_box.configure(show="*")
    self.password_box.configure(background="white")

    # Creating checkbox

    self.var = IntVar()
    self.show_password = Checkbutton(master)
    self.show_password.place(relx=0.285, rely=0.650, relheight=0.100, relwidth=0.125)
    self.show_password.configure(justify='left')
    self.show_password.configure(text='''Show''')
    self.show_password.configure(variable=self.var, command=self.cb)

def cb(self, ):

    if self.var.get() == True:
        self.password_box.configure(show="")
    else:
        self.password_box.configure(show="*")

# Giving function to login process

def login_user(self):
    name = self.username_box.get()
    password = self.password_box.get()

    if name == "user" and password == "1234":
        self.main_win.deiconify() #Unhides the root window
        self.master.destroy()  #Removes the toplevel window
        #messagebox.showinfo("Login page", "Login successful!")

    else:
        messagebox.showwarning("Login failed", "Username or password incorrect!")

def exit_login(self):
    msg = messagebox.askyesno("Exit login page", "Do you really want to exit?")

    if (msg):
        exit()




main_win = Toplevel()
main_win.title("Main Window")
main_win.title("Main Window")
main_win.geometry("800x800+450+170")

root = Tk()
gunrack = AirsoftGunRack(root)
root.mainloop()
#main_win.withdraw()
main_win.mainloop()

Ответы [ 3 ]

0 голосов
/ 17 октября 2019

Да, @Джим Эргинбаш! Вот как я хочу, чтобы это работало. Итак, я создал отдельный класс для главной победы. Я думал о процедуре аутентификации. Моя идея состоит в том, чтобы создать новую переменную (login_completed) со значением "true", если вход был успешным. На втором шаге класс main_win должен проверить, находится ли это значение в «true», прежде чем показывать главное окно (команда изъятия). К сожалению, я не могу заставить это работать правильно. Не знаю, где добавить код и как.

Это новый код до сих пор. Я также переименовал некоторые параметры для лучшего понимания, к которому они тоже относятся.

Я также заметил, что, закрыв страницу входа кнопкой фрейма (X), он также продолжит работу с кодом, создающим главное окно. Вы знаете, как его убить?

из tkinter import Tk, Label, Button, box сообщения от tkinter import *

    ##### Login Page #####

class Login_Page:

def __init__(self,login = Tk()): #This is my first change so i already initialize a Tk window inside the class
    """

    :type login: object
    """


    self.login = login
    login.title("Login - Airsoft GunRack 3.0")
    login.geometry("450x230+450+170")


    # Creating describtions

    self.username = Label(login, text="Username:")
    self.username.place(relx=0.285, rely=0.298, height=20, width=55)

    self.password = Label(login, text="Password:")
    self.password.place(relx=0.285, rely=0.468, height=20, width=55)

    # Creating Buttons

    self.login_button = Button(login, text="Login")
    self.login_button.place(relx=0.440, rely=0.638, height=30, width=60)
    self.login_button.configure(command=self.login_user)

    self.login_completed = IntVar()

    self.exit_button = Button(login, text="Exit")  # , command=master.quit)
    self.exit_button.place(relx=0.614, rely=0.638, height=30, width=60)
    self.exit_button.configure(command=self.exit_login)

    # Creating entry boxes

    self.username_box = Entry(login)
    self.username_box.place(relx=0.440, rely=0.298, height=20, relwidth=0.35)

    self.password_box = Entry(login)
    self.password_box.place(relx=0.440, rely=0.468, height=20, relwidth=0.35)
    self.password_box.configure(show="*")
    self.password_box.configure(background="white")

    # Creating checkbox

    self.var = IntVar()
    self.show_password = Checkbutton(login)
    self.show_password.place(relx=0.285, rely=0.650, relheight=0.100, relwidth=0.125)
    self.show_password.configure(justify='left')
    self.show_password.configure(text='''Show''')
    self.show_password.configure(variable=self.var, command=self.cb)

def cb(self, ):

    if self.var.get() == True:
        self.password_box.configure(show="")
    else:
        self.password_box.configure(show="*")

# Giving function to login process

def login_user(self):
    name = self.username_box.get()
    password = self.password_box.get()
    login_completed = self.login_completed.get()

    if name == "user" and password == "1234":
        #messagebox.showinfo("Login page", "Login successful!")
        self.login.destroy()  #Removes the toplevel window
        #self.main_win.deiconify() #Unhides the root window
        self.login_completed == 1

    else:

        messagebox.showwarning("Login Failed - Acess Denied", "Username or Password incorrect!")

        #return

def exit_login(self):
    msg = messagebox.askyesno("Exit login page", "Do you really want to exit?")
    if (msg):
        exit()

def mainloop_window(self): #This is the class function that helps me to mainloop the window
    self.login.mainloop()


login_page = Login_Page() # I dont need to pass the root now since its initialized inside the class
login_page.mainloop_window() # Just mainlooping the authentication window



   ##### Main Window #####




class Main_Win:

def __init__(self,main_win = Tk()): #This is my first change so i already initialize a Tk window inside the class
    """

    :type main_win: object
    """

    #main_win.withdraw()
    #self.main_win.deiconify() #Unhides the root window
    self.main_win = main_win
    main_win.title("Airsoft GunRack 3.0")
    main_win.geometry("900x500+250+130")







def mainloop_window(self): #This is the class function that helps me to mainloop the window
    self.main_win.mainloop()



main_win = Main_Win() # I dont need to pass the root now since its initialized inside the class

main_win.mainloop_window() # Just mainlooping the authentication window
0 голосов
/ 19 октября 2019

Идея вашей аутентификации хороша.

На более продвинутых уровнях вам нужно начать управлять своим приложением tkinter с базой данных (я предлагаю postgresql) и управлять своими пользователями и паролями оттуда

Чтобы предотвратить ошибку с помощью кнопки X, вы можете добавить в инициализацию класса следующую строку:

login.protocol("WM_DELETE_WINDOW",self.event_X)

Также добавьте эту функцию в класс Login: (определите функцию event_X)

    def event_X(self):
        if messagebox.askokcancel("Exit", "Are you sure you want to exit?"):
            exit()

Это будет окончательный код:

from tkinter import Tk, Label, Button, messagebox
from tkinter import *


##### Login Page #####

class Login_Page:

    def __init__(self, login=Tk()):  # This is my first change so i already initialize a Tk window inside the class
        """

        :type login: object
        """
        self.login = login
        login.protocol("WM_DELETE_WINDOW",self.event_X)
        login.title("Login - Airsoft GunRack 3.0")
        login.geometry("450x230+450+170")

    # Creating describtioneves

        self.username = Label(login, text="Username:")
        self.username.place(relx=0.285, rely=0.298, height=20, width=55)

        self.password = Label(login, text="Password:")
        self.password.place(relx=0.285, rely=0.468, height=20, width=55)

        # Creating Buttons

        self.login_button = Button(login, text="Login")
        self.login_button.place(relx=0.440, rely=0.638, height=30, width=60)
        self.login_button.configure(command=self.login_user)

        self.login_completed = IntVar()

        self.exit_button = Button(login, text="Exit")  # , command=master.quit)
        self.exit_button.place(relx=0.614, rely=0.638, height=30, width=60)
        self.exit_button.configure(command=self.exit_login)

        # Creating entry boxes

        self.username_box = Entry(login)
        self.username_box.place(relx=0.440, rely=0.298, height=20, relwidth=0.35)

        self.password_box = Entry(login)
        self.password_box.place(relx=0.440, rely=0.468, height=20, relwidth=0.35)
        self.password_box.configure(show="*")
        self.password_box.configure(background="white")

        # Creating checkbox

        self.var = IntVar()
        self.show_password = Checkbutton(login)
        self.show_password.place(relx=0.285, rely=0.650, relheight=0.100, relwidth=0.125)
        self.show_password.configure(justify='left')
        self.show_password.configure(text='''Show''')
        self.show_password.configure(variable=self.var, command=self.cb)

    def event_X(self):
        if messagebox.askokcancel("Exit", "Are you sure you want to exit?"):
            exit()

    def cb(self, ):
        if self.var.get() == True:
            self.password_box.configure(show="")
        else:
            self.password_box.configure(show="*")


# Giving function to login process

    def login_user(self):
        name = self.username_box.get()
        password = self.password_box.get()
        login_completed = self.login_completed.get()

        if name == "user" and password == "1234":
            # messagebox.showinfo("Login page", "Login successful!")
            self.login.destroy()  # Removes the toplevel window
            # self.main_win.deiconify() #Unhides the root window
            self.login_completed == 1

        else:
            messagebox.showwarning("Login Failed - Acess Denied", "Username or Password incorrect!")

        # return


    def exit_login(self):
        msg = messagebox.askyesno("Exit login page", "Do you really want to exit?")
        if (msg):
            exit()


    def mainloop_window(self):  # This is the class function that helps me to mainloop the window
        self.login.mainloop()


login_page = Login_Page()  # I dont need to pass the root now since its initialized inside the class
login_page.mainloop_window()  # Just mainlooping the authentication window


    ##### Main Window #####


class Main_Win:
    def __init__(self, main_win=Tk()):  # This is my first change so i already initialize a Tk window inside the class
        self.main_win = main_win
        main_win.title("Airsoft GunRack 3.0")
        main_win.geometry("900x500+250+130")


    def mainloop_window(self):  # This is the class function that helps me to mainloop the window
        self.main_win.mainloop()


main_win = Main_Win()  # I dont need to pass the root now since its initialized inside the class
main_win.mainloop_window()  # Just mainlooping the authentication window
0 голосов
/ 17 октября 2019

Как только вы создадите новый экземпляр root = Tk () , вы автоматически откроете небольшое окно по умолчанию.

1st) У вас есть root = Tk ()

2-й) У вас есть инициализированный мастер

3-й) У вас есть main_win

Поэтому у вас есть три окна

Вы должны избегать повторного вызова класса Tk () вне класса, и это является раздражающей проблемой 3-го окна.

Я бы предложил добавить def , которыйэто только mainloop ваше окно AirsoftGunRack .

Вот окончательный код:

from tkinter import Tk, Label, Button, messagebox
from tkinter import *

class AirsoftGunRack:

    def __init__(self,master = Tk()): #This is my first change so i already initialize a Tk window inside the class
        """

        :type master: object
        """

        ##### Login Page #####

        self.master = master
        master.title("Login - Airsoft GunRack 3.0")
        master.geometry("450x230+450+170")


        # Creating describtions

        self.username = Label(master, text="Username:")
        self.username.place(relx=0.285, rely=0.298, height=20, width=55)

        self.password = Label(master, text="Password:")
        self.password.place(relx=0.285, rely=0.468, height=20, width=55)

        # Creating Buttons

        self.login_button = Button(master, text="Login")
        self.login_button.place(relx=0.440, rely=0.638, height=30, width=60)
        self.login_button.configure(command=self.login_user)

        self.exit_button = Button(master, text="Exit")  # , command=master.quit)
        self.exit_button.place(relx=0.614, rely=0.638, height=30, width=60)
        self.exit_button.configure(command=self.exit_login)

        # Creating entry boxes

        self.username_box = Entry(master)
        self.username_box.place(relx=0.440, rely=0.298, height=20, relwidth=0.35)

        self.password_box = Entry(master)
        self.password_box.place(relx=0.440, rely=0.468, height=20, relwidth=0.35)
        self.password_box.configure(show="*")
        self.password_box.configure(background="white")

        # Creating checkbox

        self.var = IntVar()
        self.show_password = Checkbutton(master)
        self.show_password.place(relx=0.285, rely=0.650, relheight=0.100, relwidth=0.125)
        self.show_password.configure(justify='left')
        self.show_password.configure(text='''Show''')
        self.show_password.configure(variable=self.var, command=self.cb)

    def cb(self, ):

        if self.var.get() == True:
            self.password_box.configure(show="")
        else:
            self.password_box.configure(show="*")

    # Giving function to login process

    def login_user(self):
        name = self.username_box.get()
        password = self.password_box.get()

        if name == "user" and password == "1234":
            self.main_win.deiconify() #Unhides the root window
            self.master.destroy()  #Removes the toplevel window
            #messagebox.showinfo("Login page", "Login successful!")

        else:
            messagebox.showwarning("Login failed", "Username or password incorrect!")

    def exit_login(self):
        msg = messagebox.askyesno("Exit login page", "Do you really want to exit?")
        if (msg):
            exit()

    def mainloop_window(self): #This is the class function that helps me to mainloop the window
        self.master.mainloop()




main_win = Toplevel()
main_win.title("Main Window")
main_win.title("Main Window")
main_win.geometry("800x800+450+170")

gunrack = AirsoftGunRack() # I dont need to pass the root now since its initialized inside the class
gunrack.mainloop_window() # Just mainlooping the authentication window
#main_win.withdraw()
main_win.mainloop()

Обратите внимание, что я добавил четыре комментария к этому коду. В строках 6,82,93,94

Эти изменения откроют окна, над которыми вы работали.

Это, конечно, мои единственные изменения в вашем блоке кода.

Пожалуйстапрокомментируйте этот ответ, если он повлияет на вашу производительность в проекте tkinter.

...