0

Good day!

I'm working with the log in page using python. However, everytime i run my scripts, and click the Student button an error occurred.

from tkinter import *

def student():
  screen1 = Toplevel(screen)
  screen1.title("Student Log in")
  screen1.geometry("300x250")

  username = StringVar()
  password = StringVar()

  Label(screen1, text = "Username * ").pack()
  Entry(screen1, textvariable = username)
  Label(screen1, text = "Password * ").pack()
  Entry(screen1, textvariable = password)
  

def main_screen():

  screen = Tk()
  screen.geometry("300x250")
  screen.title("Database Project 1")
  Label(text = "Database Project 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
  Label(text = "").pack()
  Button(text = "Student", height = "2", width = "30", command = student).pack()
  Label(text = "").pack()
  Button(text = "Teacher",height = "2", width = "30").pack()

  screen.mainloop()

main_screen()

Error:

"File "C:/Users/TEMP.asus.001/Desktop/project database/Student database/main screen in tk.py", line 5, in student
    screen1 = Toplevel(screen)
NameError: name 'screen' is not defined

So how i fix this error, my code seems correct though! "

Sreekiran A R
  • 3,123
  • 2
  • 20
  • 41
Raldenors
  • 311
  • 1
  • 4
  • 15
  • 2
    you are calling `Toplevel(screen)` with one argument but you are not defined the `screen`. that's why you are getting the error. You can fix it by passing argument to `student()` method `student(screen)` – deadshot Jul 02 '20 at 06:16
  • You can simply remove `screen` from `Toplevel(screen)`, then it will use the first instance of `Tk()` as its master which is `screen` actually. Same like calling `StringVar()` without passing the `master` parameter. – acw1668 Jul 02 '20 at 07:27

1 Answers1

0

You need to add screen as an argument to the function student, because the variable screen is defined in the local scope of the function main_screen, so is not visible inside the function student:

def student(screen):
  screen1 = Toplevel(screen)
  # etc

Having done that, you could use a lambda function with no arguments of its own, in order to construct the relevant command argument for Button that will pass this through, for example if you use:

  Button(text = "Student", height = "2", width = "30",
         command = lambda: student(screen)).pack()

or other possibilities at: How to pass arguments to a Button command in Tkinter?

alani
  • 12,573
  • 2
  • 13
  • 23