Python随机密码生成脚本,去重复字符,可自定义长度和字符集,AI代写的。
import random import string import tkinter as tk def generate_random_string(): try: length = int(entry_length.get()) if length <= 0: label_result.config(text="错误:长度必须是正整数") return "" except ValueError: label_result.config(text="错误:请输入一个整数") return "" allowed_chars = "" if var_upper.get(): allowed_chars += string.ascii_uppercase if var_lower.get(): allowed_chars += string.ascii_lowercase if var_digit.get(): allowed_chars += string.digits if var_punct.get(): allowed_chars += string.punctuation if not allowed_chars: label_result.config(text="错误:请至少选择一种字符集") return "" random_string = "".join(random.choice(allowed_chars) for _ in range(length)) def has_duplicates(s): return len(s) != len(set(s)) def replace_duplicates(s): new_s = "" for ch in s: if s.count(ch) > 1: new_ch = random.choice(allowed_chars) new_s += new_ch else: new_s += ch return new_s def remove_duplicates(s): while has_duplicates(s): s = replace_duplicates(s) return s rs = remove_duplicates(random_string) return rs def show_and_copy_random_string(): random_string = generate_random_string() if random_string: label_result.config(text=random_string) window.clipboard_clear() window.clipboard_append(random_string) window = tk.Tk() window.title("随机字符串生成器") window.geometry("400x300") label_welcome = tk.Label(window, text="欢迎使用随机字符串生成器!") label_welcome.pack() label_length = tk.Label(window, text="请输入你想要生成的字符串长度(正整数):") label_length.pack() entry_length = tk.Entry(window) entry_length.pack() var_upper = tk.BooleanVar() var_lower = tk.BooleanVar() var_digit = tk.BooleanVar() var_punct = tk.BooleanVar() check_upper = tk.Checkbutton(window, text="大写字母", variable=var_upper) check_upper.pack() check_lower = tk.Checkbutton(window, text="小写字母", variable=var_lower) check_lower.pack() check_digit = tk.Checkbutton(window, text="数字", variable=var_digit) check_digit.pack() check_punct = tk.Checkbutton(window, text="特殊字符", variable=var_punct) check_punct.pack() button_generate = tk.Button(window, text="一键生成并复制", command=show_and_copy_random_string) button_generate.pack() label_result = tk.Label(window, text="") label_result.pack() window.mainloop()