我正试图用一个非常简单的GUI创建一个密码生成器。如果需要的话,我想为欧盟提供排除字符的能力。任何帮助都将不胜感激。
以下是我迄今为止所拥有的;TypeError:只能将str(而不是"int"(连接到str;我一辈子都无法处理为什么。。。
import os, random, string
from tkinter import *
# Password generation based on ascii letters, digits, and punctuation.
def gen_password(password_length):
initial_chars = string.ascii_letters + string.digits + string.punctuation
characters = []
for char in initial_chars:
if char not in excluded_chars:
characters += char
else:
print('Excluded characters: ' + char)
# Seed the password with a random seed
random.seed = (os.urandom(1024))
random_str = ''.join(random.choice(characters) for _ in range(password_length))
return random_str
# This will update the length of the password we generate based on whatever input number is entered
def update_password():
try:
count_chars = int(pass_len.get())
except ValueError:
return
pass_box.config(state=NORMAL)
pass_box.delete(0, 'end')
pass_box.insert(0, gen_password(count_chars))
pass_box.config(state=NORMAL)
mainWindow = Tk()
mainWindow.title('Griffin Password Generator 2.0')
mainWindow.resizable(0,0)
frame = Frame(mainWindow)
frame.pack(side=TOP, pady=10, padx=10, fill=X, expand=1)
Label(frame, text="Password Length: ", anchor=E).grid(row=0, column=0, sticky=E)
default_value = 16
pass_len = Entry(frame)
pass_len.insert(0, default_value)
pass_len.grid(row=0, column=1)
Label(frame, text="Excluded Characters: ", anchor=E).grid(row=1, column=0, sticky=E)
default_exclusions = ''
excluded_chars = Entry(frame)
excluded_chars.insert(0, default_exclusions)
excluded_chars.grid(row=1, column=1)
btn = Button(frame, text="Generate Password")
btn['command'] = lambda: update_password()
btn.grid(row=0, column=2, rowspan=2, padx=10, ipadx=10)
Label(frame, text="Generated Password: ", anchor=E).grid(row=2, column=0, sticky=E)
pass_box = Entry(frame)
pass_box.grid(row=2, column=1)
update_password()
# Open main window
mainWindow.mainloop()
问题来自以下行:
if char not in excluded_chars:
此时,excluded_chars
是一个Tkinter Entry小部件。您可能想要参考小部件中显示的字符/文本。因此,将以上内容更改为:
if char not in excluded_chars.get():
并且您的代码将在不引发该异常的情况下运行。
我终于发现了错误(在一些聪明的朋友的帮助下(:
行excluded_chars = Entry(frame)
似乎将条目保存为内存值或其他什么。因此,为了适应这种情况,我将第10行和第13行改为excluded_chars.get((,从而解决了这个问题。