我正在創建一個簡單的密碼生成器,每次按下按鈕時它都會生成一個新密碼。我該怎么做?每次我這樣做時,它都會列印/顯示相同的密碼。我想我明白為什么它沒有按照我想要的方式作業,但我不知道如何解決它。謝謝你。
from tkinter import *
import random
def password_generator():
numbers = "1234567890"
upper_case_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower_case_letters = "abcdefghijklmnopqrstuvwxyz"
special_chars = "!@#$%^&*()[];:"
password_length = random.randint(9, 15)
combo = numbers upper_case_letters lower_case_letters special_chars
password = "".join(random.sample(combo, password_length))
return password
def printSomething():
label = Label(window, text = password)
label.pack()
password = password_generator()
window = Tk()
window.geometry("400x250")
window.title("Password Generator")
window.config(background = "black")
button = Button(window, text = "Generate")
button.pack()
button.config(command = printSomething)
button.config(font = ("", 50, "bold"))
window.mainloop()
uj5u.com熱心網友回復:
此行正在運行該函式并回傳一個生成的密碼:
password = password_generator()
因此,在您運行用戶界面之前已經生成了密碼。
相反,洗掉這一行,并在每次呼叫該函式時生成一個新密碼printSomething(),即該函式應該是
def printSomething():
label = Label(window, text = password_generator())
label.pack()
請注意,我將password已經呼叫該函式并生成了一個密碼的 替換為password_generator(),它每次呼叫該函式時都會呼叫該函式printSomething()。這樣,每次用戶單擊按鈕時都會生成一個新密碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504271.html
