Oct-12-2020, 09:16 PM
You cannot get a variable from a function because the variables inside a function only exist as long as the function is running. If you want to use a value from a function you must return the value or save the value someplace where it can be accessed.
Using the return value is not going to work in your case, so you need to save the variable so others can see it. In a GUI application you could save the password string in a GUI display. Your output() function inserts the password into generated_pass. The copy() function could try to extract the password from there. However I think it would be easier to save the password in a module variable. In this example I made paStr a module variable that can be seen by any function in the module. The output() function saves the generated password in paStr. Notice the use of "global" to indicate that output() will not create a local variable named paStr, but will look outside the scope of output() for a variable with that name.
Using the return value is not going to work in your case, so you need to save the variable so others can see it. In a GUI application you could save the password string in a GUI display. Your output() function inserts the password into generated_pass. The copy() function could try to extract the password from there. However I think it would be easier to save the password in a module variable. In this example I made paStr a module variable that can be seen by any function in the module. The output() function saves the generated password in paStr. Notice the use of "global" to indicate that output() will not create a local variable named paStr, but will look outside the scope of output() for a variable with that name.
from tkinter import * import randompaStr = '' root = Tk()def randompassword(): return ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10)) def output(): global paStr paStr = randompassword() print(paStr) def copy(): generated_pass.config(text=paStr) frame = Frame(root) frame.pack(fill = BOTH, expand = True) gen_pass = Button(frame, command=output, text='Generate Password') gen_pass.pack(fill = BOTH, expand = True) copy_pass = Button(frame, command=copy, text='Copy Password') copy_pass.pack(fill = BOTH, expand = True) generated_pass = Label(frame, text='The password') generated_pass.pack(fill = BOTH, expand = True)root.mainloop()