Python 中的"未使用局部变量 'has_mastr_pass' 值"



我正试图在Python中使用Tkinter制作一个密码管理器。当我已经在if语句中使用了"本地变量"has_mastr_pass"值未使用"时,我不断收到警告。我正试图做到这一点,这样你就必须输入主密码才能使用应用程序的其余部分,但一旦我输入了主密码,我就很难运行其余的代码。我曾尝试在定义变量之前放入global has_mastr_pass,但没有成功。我完全被卡住了。

完整代码:

from tkinter import *
master = ''
passwords = []
has_mastr_pass = True
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
'5', '6',
'7', '8', '9']

def master_pass():
_input = mastr_entry.get()
# noinspection PyShadowingNames
has_mastr_pass = True

def enter_value(total_=0):
input_ = txt.get()
if input_ != '':
for i in input_:
total_ += 1
if total_ >= 4:
passwords.append(input_)
lbl2.configure(text='Password entered.')
elif total_ < 4:
lbl2.configure(text='Input 4+ digits/letters.')
else:
lbl2.configure(text='Input a password.')

def password():
separator = ", "
lbl3.configure(text=separator.join(passwords))

window = Tk()
window.geometry('500x300')
window.resizable(False, False)
window.title('Password Manager')
window.iconbitmap('./assets/lock.ico')
mastr_lbl = Label(text='Enter Master Password: ', font=('Times', 20))
mastr_lbl.grid(column=0, row=0)
mastr_entry = Entry(window, width=20)
mastr_entry.grid(column=0, row=1, sticky='w')
mastr_btn = Button(window, text='Enter', command=master_pass, activebackground='grey')
mastr_btn.place(x=126, y=34)
if has_mastr_pass:
lbl1 = Label(text='Enter Your Password:', font=('Times', 20))
lbl1.grid(column=0, row=0, sticky='w')
lbl2 = Label(text='', font=('Times', 15))
lbl2.grid(column=0, row=2, sticky='w')
lbl3 = Label(text='', font=('Times', 15))
lbl3.place(x=0, y=125)
txt = Entry(window, width=50)
txt.grid(column=0, row=1)
btn = Button(window, text='Enter', command=enter_value, activebackground='grey')
btn.grid(column=1, row=1)
btn2 = Button(window, text='See Stored Passwords', command=password, activebackground='grey')
btn2.place(x=0, y=100)
window.mainloop() 

我认为这是因为你在函数master_pass中分配了一个局部变量,然后对它不做任何操作。你已经有一个全局变量被称为相同的东西,但你没有在master_pass函数中更改它的值。

请参阅https://www.w3schools.com/python/python_variables_global.asp

如果您想在函数中更改它,那么在函数中将其声明为全局。参见答案在函数中使用全局变量

def master_pass():
_input = mastr_entry.get()
# noinspection PyShadowingNames
has_mastr_pass = True

在该函数内部,has_mastr_pass是一个从未使用过的局部变量。它不是全球性的。

如果希望此函数影响同名的全局变量,请将global has_mastr_pass放在函数的顶部。

最新更新