我不知道我的代码有什么问题?它没有标出我的期望

时间:2019-06-15 13:46:04

标签: python user-interface tkinter

所以基本上,我不知道这段代码是什么问题。我正在尝试完成一堂课的作业。我在我的工具上进行了编码,该编码根据用户打勾的复选框和用户编写的条目生成密码。运行此命令时,没有任何回溯,但是当我选择复选框并在输入框中键入内容,然后单击“生成”时,它不会标记出密码。另外,我也无法标记输入框。 因此,请你们帮我解决我的代码有什么问题吗? 附言我的代码有点长,但是希望您的专家能理解。 你们可以将其复制并粘贴到IDLE上并运行以进行查看。

import random
import sys
import string
from tkinter import *
# Start Window
class Window(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()
    def initialize(self):
        self.geometry("1200x500+130+200")

    def OnButtonClick(classGUIProgram):
        classGUIProgram.top = Toplevel()
        master = Tk()
        b = classGUIProgram.HappyButton(master)
        master.mainloop()

if __name__ == "__main__":
    window = Window(None)

window.title("Python Password Generator")
#window end

#title
w = Label(text="Secure Password Generator") 
w.pack()

w.config(font=("Courier", 70))
#title end

#value
rnum = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
rsl = list(string.ascii_lowercase[0:26])
rbl = list(string.ascii_uppercase[0:26])
rs = ['!', '@', '#', '$', '%', '^', '&', '*']
#value end

#label the password
def gpass():
    mtext = v.get()
    password = Label(text=mtext).pack()
    return
#label password end

#Checkbuttons
#checkbutton1
var1 = IntVar()
w1 = Checkbutton(text="Use Small Letters     e.g. abcde", 
variable=var1)
w1.pack()

#checkbutton2
var2 = IntVar()
w2 = Checkbutton(text="Use Big Letters        e.g. ABCDE", 
variable=var2)
w2.pack()

#checkbutton3
var3 = IntVar()
w3 = Checkbutton(text="Use Symbols            e.g. !@#$%", 
variable=var3)
w3.pack()

#checkbutton4
var4 = IntVar()
w4 = Checkbutton(text="Use Numbers          e.g. 12345", 
variable=var4)
w4.pack()
#checkbuttons end

length = StringVar()
var = StringVar()
v = StringVar()

#title label
l = Label(text="Type the password length you want below:")
l.pack()

t = Entry(textvariable=length).pack()
#title lable end

#button
button = Button(text = "Click To Generate Your Password", command = 
gpass, fg = 'Red').pack()
#button end

#generate random value according to the checkbuttons
def getin():
    a = []
    if w1.config(state=NORMAL):
         a.append(rsl[random.randint(*26/1)])
    elif w2.config(state=NORMAL):
        a.append(rbl[random.randint(*26/1)])
    elif w3.config(state=NORMAL):
        a.append(rs[random.randint(*8/1)])
    elif w4.config(state=NORMAL):
        a.append(rnum[random.randint(*9/1)])
    v = random.choices(getin(var(a)), k=str(length))
#generate value end


window.mainloop()

2 个答案:

答案 0 :(得分:0)

在开始之前,我应该指出不要使用tkinter,所以,如果我撒谎,请原谅。
我不知道您打算如何使用random
我建议不要使用random.sample(list, number_required)
我还建议您使用RadioButton而不是CheckButton,因为这将确保只选择一个选项(我在下面没有做过)。
您的“生成”按钮的回调已设置为gpass,而无需调用实际上会生成密码的getin
希望下面的代码可以为您指明正确的方向。

import random
import sys
import string
from tkinter import *
# Start Window
class Window(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()
    def initialize(self):
        self.geometry("1200x500+130+200")

    def OnButtonClick(classGUIProgram):
        classGUIProgram.top = Toplevel()
        master = Tk()
        b = classGUIProgram.HappyButton(master)
        master.mainloop()

if __name__ == "__main__":
    window = Window(None)

window.title("Python Password Generator")
#window end

#title
w = Label(text="Secure Password Generator")
w.pack()

w.config(font=("Courier", 20))
#title end

#value
rnum = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
rsl = list(string.ascii_lowercase[0:26])
rbl = list(string.ascii_uppercase[0:26])
rs = ['!', '@', '#', '$', '%', '^', '&', '*']
passW = "None"
#value end

#generate random value according to the checkbuttons
def getin():
    try:
        l = int(length.get())
    except:
        l = 0
    if var1.get():
        passW = random.choices(rsl,k=l)
    elif var2.get():
        passW = random.choices(rbl,k=l)
    elif var3.get():
        passW = random.choices(rs,k=l)
    elif var4.get():
        passW = random.choices(rnum,k=l)
    password.configure(text=passW)
#generate value end

#Checkbuttons
#checkbutton1
var1 = IntVar()
w1 = Checkbutton(text="Use Small Letters     e.g. abcde",
variable=var1)
w1.pack()

#checkbutton2
var2 = IntVar()
w2 = Checkbutton(text="Use Big Letters        e.g. ABCDE",
variable=var2)
w2.pack()

#checkbutton3
var3 = IntVar()
w3 = Checkbutton(text="Use Symbols            e.g. !@#$%",
variable=var3)
w3.pack()

#checkbutton4
var4 = IntVar()
w4 = Checkbutton(text="Use Numbers          e.g. 12345",
variable=var4)
w4.pack()
#checkbuttons end

length = StringVar()
var = StringVar()
v = StringVar()

#title label
l = Label(text="Type the password length you want below:")
l.pack()

t = Entry(textvariable=length).pack()
#title lable end

#button
button = Button(text = "Click To Generate Your Password", command =
getin, fg = 'Red').pack()
#button end
password = Label(text=passW)
password.pack()

window.mainloop()

enter image description here

考虑将CheckButtons替换为RadioButtons

编辑后包括@ user10987432所标识的random.choices的使用,这比sample更好的“选择”,并就地更新了密码标签。

答案 1 :(得分:0)

我将从这个简单的基础开始:

import tkinter as tk

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Python Password Generator")
        self.geometry("320x240")
        self.resizable(width=False, height=False)

def main():

    application = Application()
    application.mainloop()

    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main())

tkinter窗口,无法调整大小。真好另外,具有主要功能有助于理解程序流程。

然后,添加其余部分。注意,我将IntVars和StringVars以及tkinter GUI元素本身移到了 init 的主体中。我还确保每个元素的父元素是一个Frame(以保持元素的有序性)或Application实例本身。就生成密码而言,我不会使用random.randint或random.sample(因为random.sample必须抓住唯一的项目,直到没有剩余的为止,这意味着您将无法生成任意长度的密码)。

import tkinter as tk

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Python Password Generator")
        self.geometry("320x240")
        self.resizable(width=False, height=False)

        self.var_lower = tk.IntVar()
        self.var_upper = tk.IntVar()
        self.var_symbols = tk.IntVar()
        self.var_digits = tk.IntVar()
        self.var_password_length = tk.StringVar()

        frame = tk.Frame(self)
        frame.pack()

        check_lower = tk.Checkbutton(
            frame,
            text="Use lowercase letters (a-z)",
            variable=self.var_lower)
        check_lower.pack(side=tk.TOP, anchor=tk.W)

        check_upper = tk.Checkbutton(
            frame,
            text="Use uppercase letters (A-Z)",
            variable=self.var_upper)
        check_upper.pack(side=tk.TOP, anchor=tk.W)

        check_symbols = tk.Checkbutton(
            frame,
            text="Use symbols (e.g. !@#$%)",
            variable=self.var_symbols)
        check_symbols.pack(side=tk.TOP, anchor=tk.W)

        check_digits = tk.Checkbutton(
            frame,
            text="Use digits (0-9)",
            variable=self.var_digits)
        check_digits.pack(side=tk.TOP, anchor=tk.W)

        entry_frame = tk.Frame(self)
        entry_frame.pack()

        label = tk.Label(
            entry_frame,
            text="Password length:")
        label.pack(side=tk.TOP, anchor=tk.W)

        entry = tk.Entry(
            entry_frame,
            textvariable=self.var_password_length,
            width=16)
        entry.pack(side=tk.TOP, anchor=tk.W)

        button = tk.Button(
            entry_frame,
            text="Generate password",
            command=self.generate_password)
        button.pack(side=tk.TOP, anchor=tk.W, pady=(10, 10))

        self.password_entry = tk.Entry(
            self,
            width=32)
        self.password_entry.configure(state="readonly")
        self.password_entry.pack()

    def generate_password(self):
        from random import choices
        from string import ascii_lowercase, ascii_uppercase, digits

        try:
            password_length = int(self.var_password_length.get())
        except ValueError:
            return

        variables = [
            self.var_lower,
            self.var_upper,
            self.var_symbols,
            self.var_digits]

        character_sets = [
            ascii_lowercase,
            ascii_uppercase,
            "!@#$%^&*",
            digits]

        character_selection = "".join([charset for var, charset in zip(variables, character_sets) if var.get()])

        if not character_selection:
            return

        password = "".join(choices(character_selection, k=password_length))
        self.password_entry.configure(state="normal")
        self.password_entry.delete(0, tk.END)
        self.password_entry.insert(0, password)
        self.password_entry.configure(state="readonly")

def main():

    application = Application()
    application.mainloop()

    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main())