简体   繁体   中英

Tkinter entry box is always empty?

So I'm trying to write a program that updates a database based on user input. The program first allows users to log in with their username and password, and if it is successfully validated, then they can choose between four options, put/post/get/delete. The trouble I'm running into is I am unable to get user input from the entry boxes. (I inputed a small snippet of code underneath)

#The function that will call my api
def make_get_call(instructorid):
    print(instructorid.get())
    resp = requests.get(url)
    #expecting to get a status of 200 on success
    if resp.json()['status'] != 200:
        print ('Something went wrong {}').format(resp.status_code)
        exit()

    #print data returned
    print ("get succeeded")
    for inspector in resp.json()['response']:
        print (inspector["InspectorID"], str(inspector["InspectorName"]),inspector["Salary"])

#The window that pops up after the user clicks on "get user input" button
def getusers():
    top.withdraw()
    get.deiconify()
    get.geometry('400x150')
    get.title('Getting User Information')

    Label(get, text = "Enter ID of specific inspector").pack(anchor=W)
    id = StringVar()
    Entry(get, textvariable = id).pack(anchor=W)
    Button(get, text="Go", command = partial(make_get_call, id)).pack(anchor=W)

#THe window that pops up after user logs in successfully
def UserPage():
    global top 
    if login:
        tkWindow.withdraw()
        top.deiconify()
        top.geometry('400x150')
        top.title('Valid Input')

        commands = [("Get Information", getusers), ("Update Inspector", updateusers), ("Create User", createuser), ("Delete User", deleteuser)]
        row = 0 
        for command, function in commands:
            Button(top, text = command, command=function).grid(row = row, column = 5)
            row+=4


# Function to validate if user inputed the right username
def validateLogin(username, password):
    global login
    print("Username Entered :", username.get())
    print ("Password Entered: ", password.get())
    data = {"username": username.get(), "password": password.get()}
    #Sending to our API
    resp = requests.get("http://localhost:3001/api/userlogin", json=data)

    #If there is an error
    if resp.json()['status'] != 200:
        messagebox.showerror("Error", "Password/Username wrong. Please Try again")
        exit()

    else:
        login = True
        UserPage()

#THe GUI
tkWindow = Tk()
top = Tk()
top.withdraw()
get = Tk()
get.withdraw()
create = Tk()
create.withdraw()
update = Tk()
update.withdraw()
delete = Tk()
delete.withdraw()

login = False

tkWindow.geometry('400x150')
tkWindow.title('Login Form')

usernameLabel = Label(tkWindow, text = "User Name").grid(row= 0, column=3)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable = username).grid(row = 0, column=4)

passwordLabel = Label(tkWindow,text="Password").grid(row=1, column=3)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=4)  

validateLogin = partial(validateLogin, username, password)

#login button
loginButton = Button(tkWindow, text="Login", command=validateLogin).grid(row=4, column=3)  


tkWindow = Tk()
top = Tk()
top.withdraw()
get = Tk()
get.withdraw()
tkWindow.mainloop()

THe main issue is when the user tries to enter in the ID of the specific instructor in the entry box, when I pass the id variable to the function make_get_call(instructorid), instructorid is always empty. At first I thought it has something to do with delay, eg the main loop part, but I made sure to put the.get() inside a method so it should execute after the main loop. I also tried declaring id as a global variable, but that also didn't work. Any help would be much appreciated!

Sorry, I really dissected your code.

First, I would really recommend using classes and not global variables. Try this code, it should be a good starter for the rest of your application.

from tkinter import *
class App(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.grid(sticky = N+E+S+W)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1) 
        self.createWidgets()

    def createWidgets(self):
        usernameLabel = Label(self.master, text = "User Name").grid(row= 0, column=3)
        self.username = StringVar()
        usernameEntry = Entry(self.master, textvariable = self.username).grid(row = 0, column=4)

        passwordLabel = Label(self.master,text="Password").grid(row=1, column=3)  
        self.password = StringVar()
        passwordEntry = Entry(self.master, textvariable=self.password, show='*').grid(row=1, column=4)  

        # validateLogin = partial(validateLogin, username, password)

        #   login button
        loginButton = Button(self.master, text="Login", command=self.validateLogin).grid(row=4, column=3)  




    # Function to validate if user inputed the right username
    def validateLogin(self):
        global login
        print("Username Entered :", self.username.get())
        print ("Password Entered: ", self.password.get())
        data = {"username": self.username.get(), "password": self.password.get()}


#THe GUI
root = Tk()
root.geometry('400x150')
root.title('Login Form')
tkWindow = App(root)


# login = False


tkWindow.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM