Question

I'm using Python3, I am trying to pass what the user has typed in the username and password box to the login function when they press the login button. And the login functions should just pack a label of the username onto the GUI.

Code:

import tkinter
from tkinter import *
import sys

def login_gui():
    global login_window
    global studentid_entry_login
    usr_login = StringVar()
    pwd_login = StringVar()
    login_window=tkinter.Tk()
    login_window.title("Login")
    login_window.geometry("200x200+500+300")
    username_label_login = tkinter.Label(login_window, text="Username:").pack()
    username_entry_login = tkinter.Entry(login_window, textvariable=usr_login).pack()
    password_label_login = tkinter.Label(login_window, text="\nPassword:").pack()
    password_entry_login = tkinter.Entry(login_window, textvariable=pwd_login).pack()
    button_login = tkinter.Button(login_window, text="Login", command = login).pack()
    login_window.mainloop()

def login():
    username = usr_login.get()
    label1 = tkinter.Label(login_window, text=username).pack()
    return

login_gui()

Traceback:

Traceback (most recent call last):
  File "C:/Python33/Folder/tkinter-test.py", line 25, in <module>
    login_gui()
  File "C:/Python33/Folder/tkinter-test.py", line 8, in login_gui
    usr_login = StringVar()
  File "C:\Python33\lib\tkinter\__init__.py", line 254, in __init__
    Variable.__init__(self, master, value, name)
  File "C:\Python33\lib\tkinter\__init__.py", line 182, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
Was it helpful?

Solution

You can't create a StringVar unless a Tk object has already been initialized.

Move your login_window line so that it appears before the other assignments:

login_window=tkinter.Tk()
usr_login = StringVar()
pwd_login = StringVar()

Also, usr_login won't be visible in login, so you'll get a NameError. make it global, or consider putting both login_gui and login in a class, so they can access common attributes through self.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top