简体   繁体   English

将随机生成的字符串从python复制到剪贴板

[英]Copying a randomly generated string from python to the clipboard

I'm working on a "Password Generator" that will generate a string of random characters. 我正在研究“密码生成器”,它将生成一串随机字符。 I would like to add a 'Copy' button that when clicked will take that random string and add it to the clipboard so that it can be pasted elsewhere. 我想添加一个“复制”按钮,单击该按钮将获取该随机字符串并将其添加到剪贴板,以便可以将其粘贴到其他位置。

I thought I had it worked out with my current code as I stopped getting error messages but whenever I try to paste the password I get something like "< function genpass at 0x029BA5F0 >". 我以为我已经用当前的代码解决了这个问题,因为我不再收到错误消息,但是每当我尝试粘贴密码时,我都会得到类似“ < function genpass at 0x029BA5F0 >”的信息。

import random
from swampy.Gui import *
from Tkinter import *
import string
#--------Globals-------
pcha = string.ascii_letters + string.punctuation + string.digits
g = Gui()
#--------Defs---------
def genpass():

    return "".join(random.choice(pcha) for i in range (10))

def close():
    g.destroy()

def copy():
    g.withdraw()
    g.clipboard_clear()
    g.clipboard_append(genpass)


#--------GUI----------

g.title("Password Helper")
g.la(text="Welcome to Password Helper! \n \n Choose from the options below to continue. \n")


rndpass = StringVar()
update = lambda:rndpass.set(genpass())

btna = g.bu(text="Generate a New Password", command=update)
btna.pack(padx=5)

pbox = g.en(textvariable = rndpass)
pbox.config(justify='center')
pbox.pack( padx = 5)

btnb=g.bu(text ="Copy to Clipboard", command=copy)

btnc=g.bu(text ="Exit", command=close)

g.mainloop()

I feel like I'm missing just one little thing that would solve my problem but I just can't guess what it is. 我觉得我只是想解决一个小问题而已,但我只是无法猜测是什么。 I've been searching around and found a few possible solutions (even pyperclip) but no matter how I try them I always end up with the same outcome. 我一直在搜索,发现了一些可能的解决方案(甚至是pyperclip),但是无论我如何尝试,我总是会得到相同的结果。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

This line: 这行:

g.clipboard_append(genpass)

is adding the function genpass , rather than its return value 正在添加函数 genpass ,而不是其返回值

You need to call the function with () : 您需要使用() 调用函数:

g.clipboard_append(genpass())

Edit: It looks like you're storing the password in rndpass . 编辑:看来您要将密码存储在rndpass So to get that back out, you need to call rndpass.get() : 因此,要恢复该状态,您需要调用rndpass.get()

g.clipboard_append(rndpass.get())

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

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