我正在处理密码生成器。我有一个按钮可以生成密码和一个将其复制到剪贴板的按钮。 问题是:每当我生成另一个密码时,然后将其添加到剪贴板中,它才会添加到其他密码中。 如果我有密码123ok并将其复制到剪贴板上,但随后生成了456ok并将其复制到剪贴板上,我将拥有123ok456ok。

那是我的代码:


import string
import random
import tkinter as tk

letters = string.ascii_letters
numbers = string.digits
symbols = string.punctuation

chars, nums, syms = True, True, True

evy = ""

if chars:
    evy += letters
if nums:
    evy += numbers
if syms:
    evy += symbols

length = 8

window = tk.Tk()
window.geometry("500x500")
window.title("Password Generator")
window.configure(background="black")


def generate():
    for x in range(1):
        global password
        password = "".join(random.sample(evy, length))
        pwd = tk.Label(text=password, foreground="green", background="black", font=16)
        pwd.pack()


genBtn = tk.Button(window, command=generate, text="Generate Password")
genBtn.pack()


def copy_clip():
    window.clipboard_append(password)
    window.clipboard_clear()


copyBtn = tk.Button(text="Copy the password", command=copy_clip)
copyBtn.pack()

window.mainloop()

分析解答

试试看

import random
import tkinter as tk

letters = string.ascii_letters
numbers = string.digits
symbols = string.punctuation

chars, nums, syms = True, True, True

evy = ""

if chars:
    evy += letters
if nums:
    evy += numbers
if syms:
    evy += symbols

length = 8

window = tk.Tk()
window.geometry("500x500")
window.title("Password Generator")
window.configure(background="black")

password = ""  # Initialize the password variable

def generate():
    global password  # Use the global password variable
    password = "".join(random.sample(evy, length))
    pwd = tk.Label(text=password, foreground="green", background="black", font=16)
    pwd.pack()

genBtn = tk.Button(window, command=generate, text="Generate Password")
genBtn.pack()

def copy_clip():
    if password:
        window.clipboard_clear()  # Clear clipboard
        window.clipboard_append(password)
        window.update()  # Update clipboard

copyBtn = tk.Button(text="Copy the password", command=copy_clip)
copyBtn.pack()

window.mainloop()```

Try this instead