使用Tkin登录Python GUI

2024-04-19 16:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个首先提示用户登录数据库的接口。我无法使用Entry对象的get方法。对于'Login'按钮命令,我使用lambda,因为我正在调用接受参数的Login函数。因为我将入口对象传递到我的登录函数中,所以我调用用户.get()和pw.get公司()在这些功能中。在

但是,在运行此代码时,它表示用户.get(), pw.get公司()是没有属性get的非类型对象。我不明白为什么条目是Nonetype,因为logintoDB应该在创建按钮之后调用。在

谢谢你的帮助。在

以下是我的代码:

import Tkinter as tk
import tkFileDialog as tkfd
import tkMessageBox as tkmb
import xlrd

def openFile():
    #returns an opened file
    fname = tkfd.Open(filetypes = [("xls files","*.xls")])
    fpath = fname.show()
    if fname:
        try:
            TLA_sheet = xlrd.open_workbook(fpath).\
                    sheet_by_name('TLA - TOP SKUs')
            tk.Button(root, text = "Import TLAs", command = lambda: importTLAtoDB(TLA_sheet)).pack()
        tkmb.showinfo("Success!", "Spreadsheet successfully loaded. \n\
        Click Import TLAs to load TLA info into RCKHYVEDB database.")
        except:
            tkmb.showerror("Error", "Failed to read file\n '%s'\n\
            Make sure file is a type .xls" % fpath)

def enter(event):
    return logintoDB

def logintoDB(user, pw):
    #request login for database access
    print user.get(), pw.get()
    try:
        db = MySQLdb(config.server_link, user.get(), pw.get(), config.database)
        tkmb.showinfo("Success!","Database login successful.\n\
        Click Browse to load TLA spreadsheet.")
        tk.Button(root, text = "Browse", command = openFile, width = 10).pack()
        return True
    except:
        tkmb.showerror("Error", "Login failed. Try again.")
        return False

#GUI setup
root = tk.Tk()
root.title("TLA Database Tool")

user_label = tk.Label(root, text = "username").pack()
user = tk.Entry(root, textvariable = tk.StringVar()).pack()
pw_label = tk.Label(root, text = "password").pack()
pw = tk.Entry(root, show = "*", textvariable = tk.StringVar()).pack()
login_button = tk.Button(root, text = "Login", command = lambda: logintoDB(user,pw)).pack()
root.mainloop()

Tags: 对象text用户importgetloginrootpack
1条回答
网友
1楼 · 发布于 2024-04-19 16:28:19

以下代码行错误:

user = tk.Entry(root, textvariable = tk.StringVar()).pack()
pw = tk.Entry(root, show = "*", textvariable = tk.StringVar()).pack()

显然,上面的变量userpw指向的是Entry小部件对象,而不是与这些对象关联的textvariable。在

相反,您应该使用textvariable属性设置一个新变量,并使用lambda运算符将其作为参数传递。在

下面是一个从Text小部件获取文本的简单示例。在

^{pr2}$

请注意我是如何设置一个单独的变量svalue,并将其传递给Entry小部件的textvariable属性。在

回复您的评论

事实上,现在我仔细观察一下你的widget创建过程,你在创建widget并将其打包在同一行中,然后保持对它的引用,如下所示:

usr = Entry().pack()

由于pack()返回null,因此留给您usrnull值。在

相反,请执行以下操作:

usr = Entry(root,textvariable=svalue) # create here
usr.pack() # now pack

现在,usr将引用Entry小部件。在

实际上,我只需将行更改为:

user = tk.Entry(root, textvariable = tk.StringVar())
user.pack()
pw_label = tk.Label(root, text = "password").pack()
pw = tk.Entry(root, show = "*", textvariable = tk.StringVar())
pw.pack()

相关问题 更多 >