Python GUI登录程序

时间:2014-03-08 12:59:51

标签: python user-interface

我和我的朋友正在制作一个需要在开始时登录的程序。我们设法让用户输入详细信息,并让程序创建一个名为(用户名)的文本文件,其中包含详细信息。每个文件的格式如下:

(名称)

(用户名)

(密码)

当您想要登录时,程序会询问您的姓名,并找到包含姓名(无论他们输入的是什么)个人资料的文件。 如果它存在,程序然后打开一个GUI窗口并询问用户名和密码,如果你输入它打开的文件的正确详细信息,它说明细节是错误的。我们认为它与变量有关,但是我们已经尝试了很多不同的方法来解决e.t.c并且找不到问题。有人可以帮忙吗? (我所包含的代码只是GUI部分,包括不起作用的位,其余的都没问题。

# Log in
def LogIn():
    name=input("Please enter your name: ")
    file = open(name.lower() + " profile.txt", "r")
#+=========GUI===========GUI============GUI===========+

    #mport modules
    import tkinter
    import time

    #---Window---#
    #make window
    window = tkinter.Tk()
    #change title
    window.title("Python Games Login")
    #change size
    window.geometry("270x210")
    #change window icon
    window.wm_iconbitmap("Login icon.ico")
    #change window colour
    window.configure(bg="#39d972")

    #---Commands---#
    #go
    def callback():
        line = file.readlines()
        username = user.get()
        password = passw.get()
        if username == line[1] and password == line[2]:
            message.configure(text = "Logged in.")
        else:
            message.configure(text = "Username and password don't match the account \n under the name;\n \'" + name + "\'. \nPlease try again.")
    #---Widgets---#
    #labels
    title1 = tkinter.Label(window, text="--Log in to play the Python Games--\n", bg="#39d972")
    usertitle = tkinter.Label(window, text="---Username---", bg="#39d972")
    passtitle = tkinter.Label(window, text="---Password---", bg="#39d972")
    message = tkinter.Label(window, bg="#39d972")

    #text entry windows
    user = tkinter.Entry(window)
    passw = tkinter.Entry(window, show='*')

    #buttons
    go = tkinter.Button(window, text="Log in!", command = callback, bg="#93ff00")

    #pack widgets
    title1.pack()
    usertitle.pack()
    user.pack()
    passtitle.pack()
    passw.pack()
    go.pack()
    message.pack()

    #start window
    window.mainloop()

#+===================GUI END=====================+

2 个答案:

答案 0 :(得分:2)

我会使用python的 pickle 模块来保存数据。它比将其保存在文本文件中要高得多。在我的例子中,我腌制了一个词典列表。

import pickle
def LogIn():
    name=input("Please enter your name: ").lower()
    #data.pickle should be a list of dictionaries representing a user
    usernames= pickle.load('data.pickle')
    for userdata in usernames:
        if userdata['name']== name:
            return userdata
    #didn't find the name
    print('could not find '+ name+ ' in data.pickle')
    return None

来自the docs pickle 的说明:

  

警告:

     

pickle模块并非旨在防止错误或恶意构造的数据。切勿取消从不受信任或未经身份验证的来源收到的数据。

同时查看搁置 marshal ,它们会执行类似的结果,或者考虑将其保存为json文件格式(python有一个 json 模块)

答案 1 :(得分:1)

请注意readlines不会从行中删除行尾字符:

In [57]: f = open('data','r')

In [58]: f.readlines()
Out[58]: ['index,value\n', '0,16714217840939775\n', '1,16714217840939776 \n']

所以username == line[1]可能失败,因为username不包含行尾字符。 password == line[2]也是如此。

一个简单的解决方法是使用

username == line[1].strip()