0

I'm trying to build a login screen for practice and I'm having trouble with it. The general idea is that pressing the Login button closes the current window and opens another in a separate file. However, when I run the main file it opens the GUI window created in the second file. I'm not sure what would be causing it to do this.

import tkinter as tk
import loginEntry

HEIGHT = 200
WIDTH = 500


def login_function():
    root.destroy()
    loginEntry.NewScreen()


def register_function():
    print("Register!")


root = tk.Tk()

root.title("Login Screen")
root.resizable(False, False)

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='grey')
frame.place(relx=0.1, rely=0.25, relwidth=0.8, relheight=0.5)

login = tk.Button(frame, text="Login", command=login_function)
login.place(relx=0.05, rely=0.25, relwidth=0.425, relheight=0.5,)

register = tk.Button(frame, text="Register", command=register_function)
register.place(relx=0.525, rely=0.25, relwidth=0.425, relheight=0.5,)

introduction = tk.Label(root, text="Hello and welcome to DogNet, please login below.", font='bold 12')
introduction.place(relx=0.5, anchor='center', rely=0.1)

root.mainloop()

and then the second file

import tkinter as tk

def NewScreen():
    root = tk.Tk()

    canvas = tk.Canvas(root, bg='black')
    canvas.pack()

    root.mainloop()

NewScreen()
Ethan Field
  • 4,646
  • 3
  • 22
  • 43
  • Read [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) – stovfl Oct 03 '19 at 13:42

1 Answers1

1

This is because, in your second file, you are calling the definition when it is imported.

import tkinter as tk

def NewScreen():
    root = tk.Tk()

    canvas = tk.Canvas(root, bg='black')
    canvas.pack()

    root.mainloop()

NewScreen() #< here you call the definition

This means that the series of events that happen in your program are as follows.

  1. First file starts
  2. Second file is imported
  3. Definition "NewScreen" is called
  4. tkinter mainloop starts which puts your program into a loop and stops the program from going on to any new lines until the loop is closed
Ethan Field
  • 4,646
  • 3
  • 22
  • 43