2017-06-06 46 views
1

我已经使用Python的tkinter模块编写了一个程序。前提是在给出密码后,它会根据它的强度产生响应。字典和函数如何共存而不会相互冲突? (Tkinter)

from tkinter import * 

def click(): 
    entered_text = entry.get() 
    if len(entered_text) < 9: 
     output.delete(0.0, END) 
     output.insert(END, 'This is too short')  #Click function 
    elif entered_text in pass_Type: 
     strength = pass_Type[entered_text] 
     output.delete(0.0, END) 
     output.insert(END, strength) 
    else: 
     output.delete(0.0, END) 
     output.insert(END, "This password is acceptable!") #When the password is ok 

Password = Tk() 
Password.title('Password tester') 

label = Label(Password, text="Password:") 
label.grid(row=0, column=0, sticky=W) #Entry label 

entry = Entry(width=20, bg='light blue') 
entry.grid(row=1, column=0, sticky=W)  #Entry box 

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W) #Button 

label = Label(Password, text='Strength:') 
label.grid(row=4, column=0, sticky=W)   #Output label 

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue') 
output.grid(row=5, column=0, columnspan=2, sticky=W)        #Output box 

pass_Type = { 
    'Password': 'This is a very predicatable password. You should incorporate numbers', 
    'password': 'This is a very predicatable password. You should incorporate numbers and capital letters', #Common password glossary 
    '12345': 'Try and incorporate some letters', 
    'qwerty': 'Try to jumble up your letters so the password is not so predictable.' 
    } 

Password.mainloop() 

此代码运行正常良好。但是,当我运行字典中的一个常用密码('pass_type')时,长度消息会运行。

因此,我试着将其与'def click()'的其余部分一起添加。

def click(): 
entered_text = entry.get() 
if len(entered_text) < 9: 
    output.delete(0.0, END) 
    output.insert(END, 'This is too short')  #Click function 
elif entered_text in pass_Type: 
    strength = pass_Type[entered_text] 
    output.delete(0.0, END) 
    output.insert(END, strength) 
elif strength and len(entered_text) < 9: } 
    output.delete(0.0, END)    } 
    output.insert(END, strength)   } #What I entered 
else: 
    output.delete(0.0, END) 
    output.insert(END, "This password is acceptable!") #When the password is ok 

这仍返回消息“这是过于短暂”从长度检查,尽管我赋予它力量的事实。

我怎样才能得到通用密码仍分配他们的属性字典句子?

+0

当您添加的“elif”运行时,“强度”未定义,这就是您遇到此错误的原因。 –

+0

在点击函数定义之前移动pass_Type声明。 –

回答

0

为了解决当您添加

elif strength and len(entered_text) < 9: 
    output.delete(0.0, END) 
    output.insert(END, strength) 

前面的代码从未穿过第一elif的语句,因此从来没有分配一个值的强度,因此在分配之前引用。

+0

我应该怎样移动/改变? –

+0

在开始任何if和elifs之前,您必须先声明这个陈述,然后您必须声明其实力。因此,在if语句上方移动'strength = pass_Type [entered_text]'应为其指定一个值。这可能是也可能不是您想要的值,但这将解决分配问题。 – Dorilds

+0

它解决了错误的问题,谢谢。 –