尝试使用Tkinter对密码检查器和生成器进行编码

时间:2017-11-23 11:07:20

标签: python tkinter

到目前为止,我有生成器工作但我无法让tkinter显示生成的密码的变量,它只出现在控制台中。一旦我的密码检查工作正常,我需要能够更改变量,请帮助,这是我的代码的副本

from tkinter import *
import tkinter as tk
from tkinter import font as tkfont
import random
import time

global strength
global gen
strength = 0;
gen = '[password will be here]';
global mypw
mypw = '';


def generate():
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    pw_length = 8
    mypw = ""

    for i in range(pw_length):
    next_index = random.randrange(len(alphabet))
    mypw = mypw + alphabet[next_index]

    # replace 1 or 2 characters with a number
    for i in range(random.randrange(1,3)):
        replace_index = random.randrange(len(mypw)//2)
        mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:]

    # replace 1 or 2 letters with an uppercase letter
    for i in range(random.randrange(1,3)):
        replace_index = random.randrange(len(mypw)//2,len(mypw))
        mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:]

    print(mypw)
    gen = mypw;




class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="Passowrd program", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Check your password strength",
                        command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Generate a new password",
                        command=lambda:[generate(),time.sleep(0.1),controller.show_frame("PageTwo")])
        button3 = tk.Button(self, text="quit", command=close)

        button1.pack()
        button2.pack()
        button3.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label1 = tk.Label(self, text="Check your password", font=controller.title_font)
        label1.pack(side="top", fill="x", pady=10)
        entry = tk.Entry(self, bd =6)
        button2 = tk.Button(self, text="Back",
                       command=lambda: controller.show_frame("StartPage"))
        label2 = tk.Label(self, text="Strength:", font=controller.title_font)
        label3 = tk.Label(self, text=strength, font=controller.title_font)
        entry.pack()
        button2.pack()
        label2.pack()
        label3.pack()

        password = list(entry.get())


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):

        '''while 0 == 0:
            gen = mypw;'''

        var = StringVar()
        var.set(gen)

        tk.Frame.__init__(self, parent)
        self.controller = controller
        label1 = tk.Label(self, text="Generate a password", font=controller.title_font)
        label1.pack(side="top", fill="x", pady=10)
        label2 = tk.Label(self, textvariable=var, font=controller.title_font)
        button = tk.Button(self, text="Back",
                       command=lambda: controller.show_frame("StartPage"))
        label2.pack()
        button.pack()



def close():
    messagebox.showinfo("BYE", "Thank you")
    time.sleep(1)
    app.destroy()

#def check_generate():

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

generate()

所以,这是我的代码,我希望有人能提供帮助,这将非常有用,谢谢

1 个答案:

答案 0 :(得分:0)

问题是您没有更新用于显示生成密码的var StringVar。这是你的代码的一个版本,修复了它,但它有点乱。您的代码还有其他一些问题,但我会让您发现这些问题。 ;)

from tkinter import *
import tkinter as tk
from tkinter import font as tkfont
import random
import time

global strength
global gen
strength = 0
gen = '[password will be here]'
global mypw
mypw = ''

def generate(pwvar):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    pw_length = 8
    mypw = ""

    for i in range(pw_length):
        next_index = random.randrange(len(alphabet))
        mypw = mypw + alphabet[next_index]

    # replace 1 or 2 characters with a number
    for i in range(random.randrange(1,3)):
        replace_index = random.randrange(len(mypw)//2)
        mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:]

    # replace 1 or 2 letters with an uppercase letter
    for i in range(random.randrange(1,3)):
        replace_index = random.randrange(len(mypw)//2,len(mypw))
        mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:]

    print(mypw)
    gen = mypw
    pwvar.set(gen)

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="Password program", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Check your password strength",
                        command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Generate a new password",
                        command=lambda:[generate(self.controller.frames['PageTwo'].var),time.sleep(0.1),controller.show_frame("PageTwo")])
        button3 = tk.Button(self, text="quit", command=close)

        button1.pack()
        button2.pack()
        button3.pack()

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label1 = tk.Label(self, text="Check your password", font=controller.title_font)
        label1.pack(side="top", fill="x", pady=10)
        entry = tk.Entry(self, bd =6)
        button2 = tk.Button(self, text="Back",
                       command=lambda: controller.show_frame("StartPage"))
        label2 = tk.Label(self, text="Strength:", font=controller.title_font)
        label3 = tk.Label(self, text=strength, font=controller.title_font)
        entry.pack()
        button2.pack()
        label2.pack()
        label3.pack()

        password = list(entry.get())

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        self.var = StringVar()
        self.var.set(gen)

        tk.Frame.__init__(self, parent)
        self.controller = controller
        label1 = tk.Label(self, text="Generate a password", font=controller.title_font)
        label1.pack(side="top", fill="x", pady=10)
        label2 = tk.Label(self, textvariable=self.var, font=controller.title_font)
        button = tk.Button(self, text="Back",
                       command=lambda: controller.show_frame("StartPage"))
        label2.pack()
        button.pack()

def close():
    messagebox.showinfo("BYE", "Thank you")
    time.sleep(1)
    app.destroy()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
    generate()

这是一种稍微好一点的方法。我们没有将这个狡猾的列表作为PageTwo中的回调函数,而是制作了一个正确的方法generate_password。不仅更容易阅读和阅读调试,通过这种方式我们不需要将密码StringVar传递给generate,而是我们可以让generate返回新密码,然后在{{1}内设置StringVar }}。

我也摆脱了无用的generate_password全局。我删除了凌乱的mypw,然后添加了from tkinter import *,以便您的tkinter.messagebox功能正常运行。

close