简体   繁体   English

从 Tkinter,我如何将字符串转换为整数以用于潜在的随机密码生成器

[英]From Tkinter, how do i convert a string to an integer for potentially a random password generator

So I'm trying to create a GUI, i think, where it creates a random password.所以我想创建一个 GUI,我想,它会在其中创建一个随机密码。 the number that is typed in the entry box will determine the amount of digits the password will have.在输入框中输入的数字将决定密码的位数。 Example: the number 12 will be a 12 digit password.示例:数字 12 将是 12 位密码。 I'm having trouble with making the number into an integer value where i can then use it for the random password function.我无法将数字转换为整数值,然后我可以将它用于随机密码功能。 The function 'generate' cant generate a random password and i dont know why. “生成”功能无法生成随机密码,我不知道为什么。

here is the code这是代码

import random
import string
import tkinter

root = tkinter.Tk()

root.title('Random Password generator')
root.geometry("200x200")

def generatepassword():
    password =''
    for a in range(num):
        a = random.randint(1, 50)
        password += string.printable[a]
    return password


def generate():
    new_number = Entry1.get()
    generate_text = tkinter.Label(root, text="Password is: " + generatepassword(new_number))
    generate_text.pack()


Message = tkinter.Label(root, text="Enter an number:").pack()

Entry1 = tkinter.Entry(root, font="calibra")
Entry1.pack()

Button = tkinter.Button(root, height=1, width=6, text='Submit', command=generate).pack()

root.mainloop()

The Entry1.get() method will always return a string. Entry1.get() 方法将始终返回一个字符串。 If you want to use it as a integer or a float you will need to cast it before you do so.如果要将其用作整数或浮点数,则需要在执行此操作之前对其进行转换。 The built in int() function is one of your options.内置的int()函数是您的选择之一。

  new_number = int(Entry1.get())

Because get() will always return a string from an Entry field you need to have some way to make use when you use int() that the value is actually an integer.因为get()将始终从 Entry 字段返回一个字符串,所以当您使用int() ,您需要有某种方法来利用该值实际上是一个整数。 The quick and easy way is to use a try/except statement.快速简便的方法是使用try/except语句。 That said there are a few things I would change.也就是说,我会改变一些事情。

1st.第一。 We do not need 2 functions here.我们在这里不需要 2 个函数。 Everything can be done in one function.一切都可以在一个函数中完成。

2nd.第二。 Updated your code to follow PEP8 a bit more closely.更新了您的代码以更紧密地遵循 PEP8。

3rd.第三。 added a focus() and bind() to make this more user friendly.添加了focus()bind()以使其更加用户友好。

4th. 4. Moved the label for passwords to be created in the global namespace and changed it so we are only updating the password instead of adding new lines.移动了要在全局命名空间中创建的密码标签并对其进行了更改,因此我们只更新密码而不是添加新行。

Lastly I added a try/except statement so we can handle the case if someone tries to submit a non-int as well as added in the missing argument and a conversion to integer.最后,我添加了一个try/except语句,这样我们就可以在有人尝试提交非整数以及添加缺少的参数和转换为整数时处理这种情况。

See below code and let me know if you have any questions.请参阅下面的代码,如果您有任何问题,请告诉我。

import tkinter as tk
import random
import string


def generate_password():
    try:
        password = ''
        for _ in range(int(entry1.get())):
            a = random.randint(1, 50)
            password = '{}{}'.format(password, string.printable[a])
        generate_text.config(text="Password is: {}".format(password))
    except BaseException as e:
        print('{}'.format(e))


root = tk.Tk()
root.title('Random Password generator')
root.geometry("200x200")

message = tk.Label(root, text="Enter an number:")
entry1 = tk.Entry(root, font="calibra")
button = tk.Button(root, height=1, width=6, text='Submit', command=generate_password)
generate_text = tk.Label(root, text="")

message.pack()
entry1.pack()
button.pack()
generate_text.pack()

entry1.focus()
entry1.bind('<Return>', generate_password)

root.mainloop()

在此处输入图片说明

Use IntVar() to accept an integer directly.使用IntVar()直接接受一个整数。

Since you want a all digits password, this code just does that.由于您想要一个全数字密码,此代码就是这样做的。

Code:代码:

import random
import string
import tkinter as tk

root = tk.Tk()

root.title('Random Password generator')

message = tk.Label(root, text="Enter an number:")
message.pack()

# take an integer input rather than a string
number = tk.IntVar()
entry1 = tk.Entry(root, font="calibra", textvariable=number)
entry1.pack()

def generatepassword(number):
    password = ''
    for i in range(number):
        # randint is inclusive at both ends
        digit = random.randint(0, 9)
        password += str(digit)
    return password

generate_text = tk.Label(root)
generate_text.pack()

def generate():
    pwd_len = number.get()
    password = generatepassword(pwd_len)
    generate_text.config(text="Password is: " + password)

button = tk.Button(root, height=1, width=6, text='Submit', command=generate)
button.pack()

root.mainloop()

NOTE: IntVar() has a default value of 0 , you can enter any number in place of 0 and have your password.注意: IntVar()的默认值为0 ,您可以输入任何数字代替0并获得密码。

Output:输出:

随机密码生成器

Also, if you want a password that has both alphabets (uppercase & lowercase) and digits, replace the generatepassword() function with the following version:此外,如果您想要一个同时包含字母(大写和小写)和数字的密码,请将generatepassword()函数替换为以下版本:

def generatepassword(number):
    password = ''
    for i in range(number):
        password += random.choice(string.ascii_letters + string.digits)  
    return password

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM