简体   繁体   English

Tkinter 输入框总是空的?

[英]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.该程序首先允许用户使用他们的用户名和密码登录,如果验证成功,那么他们可以在四个选项之间进行选择,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.主要问题是当用户尝试在输入框中输入特定讲师的 ID 时,当我将 id 变量传递给 function make_get_call(instructorid) 时,instructorid 始终为空。 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.起初我认为它与延迟有关,例如主循环部分,但我确保将.get() 放在一个方法中,以便它应该在主循环之后执行。 I also tried declaring id as a global variable, but that also didn't work.我也尝试将 id 声明为全局变量,但这也没有用。 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.试试这个代码,它应该是您应用程序的 rest 的良好启动器。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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