Python Forum
Call local variable of previous function from another function with Python3 & tkinter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Call local variable of previous function from another function with Python3 & tkinter
#1
Hi Smile

I am building password generator with python and tkinter as GUI. The function copy should copy paStr variable which reside in another function called def output. I couldn't find any workaround to reach paStr variable and make it possible for the copy function to copy paStr to clipboard.
Any help and hints are veeeery appreciated.

Using Python 3.8, VS Code, OS: Windows 10 pro

copy_pass button is in relation with def copy
paStr variable holds the generated passwords and it's the variable of def output

I deleted 2/3 of the code and pasted the needed part only.

For smooth troubleshooting in chars length insert 8 and in how many password insert 3.

I suggest to try the code on your preferable interpreter, it is impossible to troubleshoot it from your smartphone or with random thoughts without testing.

Thank you very much
Stay Safe

My code:

import tkinter as tk
import tkinter.font as tkFont
from tkinter import *
from tkinter import ttk
import random
import string



root = tk.Tk()
root.title("P-GEN")

width=600
height=550
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)

passLen = IntVar()
passNum = IntVar()


def randompassword():

    uchars = int(passLen.get() / 4)

    lchars = int(passLen.get() / 4)

    dchars = int(passLen.get() / 4)

    schars = int(passLen.get() / 4)

    str_uchars, str_lchars, str_dchars, str_schars = '', '', '', ''

    for i in range(uchars):
        str_uchars += random.SystemRandom().choice(string.ascii_uppercase)

    for i in range(lchars):
        str_uchars += random.SystemRandom().choice(string.ascii_lowercase)

    for i in range(dchars):
        str_uchars += random.SystemRandom().choice(string.digits)

    for i in range(schars):
        str_uchars += random.SystemRandom().choice(string.punctuation)

    random_str = str_uchars + str_lchars + str_dchars + str_schars

    random_str = ''.join(random.sample(random_str, len(random_str)))

    l = list(random_str)

    random.shuffle(l)

    result = ''.join(l)

    return str(result)
    
def output():
  n = 0
  while n < passNum.get():
    paStr = randompassword() + '\n'
    print(paStr)
    n=n+1
    generated_pass.insert('1.0', paStr)

    
'''
def copy():
    # Iam stucked here, any hints please to return the paStr varaible from the previous function (def output) so I can make it possible to be copied to clipboard.
  I tried this but as I said, could not find how to reach local variable of the previous function.

  copy_pass.clipboard_clear()
  copy_pass.clipboard_append(paStr)
  copy_pass.update()
'''


title_bar=tk.Label(root)
title_bar["bg"] = "#393d49"
ft = tkFont.Font(family='Times',size=18)
title_bar["font"] = ft
title_bar["fg"] = "#33ed3f"
title_bar["justify"] = "center"
title_bar["text"] = "P-GEN"
title_bar["relief"] = "flat"
title_bar.place(x=0,y=0,width=600,height=31)


enter_chars=tk.Label(root)
ft = tkFont.Font(family='Times',size=10)
enter_chars["font"] = ft
enter_chars["fg"] = "#333333"
enter_chars["justify"] = "left"
enter_chars["text"] = "Enter Chars Length"
enter_chars["relief"] = "flat"
enter_chars.place(x=20,y=160,width=169,height=30)

pass_length=tk.Entry(root)
pass_length["bg"] = "#d2f4d4"
pass_length["borderwidth"] = "3px"
ft = tkFont.Font(family='Times',size=10)
pass_length["font"] = ft
pass_length["fg"] = "#333333"
pass_length["justify"] = "center"
pass_length["text"] = "Entry"
pass_length["relief"] = "sunken"
pass_length.place(x=220,y=160,width=142,height=30)
pass_length["textvariable"] = passLen

enter_passN=tk.Label(root)
ft = tkFont.Font(family='Times',size=10)
enter_passN["font"] = ft
enter_passN["fg"] = "#333333"
enter_passN["justify"] = "left"
enter_passN["text"] = "Enter How Many Passwords"
enter_passN["relief"] = "flat"
enter_passN.place(x=20,y=210,width=169,height=31)

pass_num=tk.Entry(root)
pass_num["bg"] = "#d2f4d4"
pass_num["borderwidth"] = "3px"
ft = tkFont.Font(family='Times',size=10)
pass_num["font"] = ft
pass_num["fg"] = "#333333"
pass_num["justify"] = "center"
pass_num["text"] = "Entry"
pass_num["relief"] = "sunken"
pass_num.place(x=220,y=210,width=142,height=30)
pass_num["textvariable"] = passNum

gen_pass=tk.Button(root)
gen_pass["activebackground"] = "#7ff14e"
gen_pass["bg"] = "#efefef"
ft = tkFont.Font(family='Times',size=10)
gen_pass["font"] = ft
gen_pass["fg"] = "#000000"
gen_pass["justify"] = "center"
gen_pass["text"] = "Generate Passwords"
gen_pass["relief"] = "raised"
gen_pass.place(x=20,y=270,width=142,height=30)
gen_pass["command"] = output

generated_pass=tk.Text(root)
generated_pass["bg"] = "#d2f4d4"
generated_pass["borderwidth"] = "3px"
ft = tkFont.Font(family='Times',size=10)
generated_pass["font"] = ft
generated_pass["fg"] = "#333333"
generated_pass["relief"] = "sunken"
generated_pass.place(x=220,y=270,width=346,height=192)

copy_pass=tk.Button(root)
copy_pass["activebackground"] = "#7ff14e"
copy_pass["bg"] = "#efefef"
ft = tkFont.Font(family='Times',size=10)
copy_pass["font"] = ft
copy_pass["fg"] = "#000000"
copy_pass["justify"] = "center"
copy_pass["text"] = "Copy Passwords"
copy_pass["relief"] = "raised"
copy_pass.place(x=20,y=320,width=142,height=30)
#copy_pass["command"] = copy 



if __name__ == "__main__":
    
    root.mainloop()
Reply
#2
You could call def_copy from within  def_output, passing the pw as an argument ?

paul
Reply
#3
(Oct-12-2020, 03:03 PM)DPaul Wrote: You could call def_copy from within  def_output, passing the pw as an argument ?

paul

Thanks for replying. Would you please show me a concrete example or a concrete implementation coz I tried few scenarios but I failed, showing me a concrete implementation is much appreciated.
Reply
#4
OK, i have used pyperclip to copy things to the clipboard:
import pyperclip

def output():
  password = 'pw'
  copy(password)

    
def copy(pw):
    pyperclip.copy(pw)
 

output()
Paul
Reply
#5
thank you bro but it's not what I am searching for.
Reply
#6
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.
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() 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pass a variable between tkinter and toplevel windows janeik 10 2,140 Jan-24-2024, 06:44 AM
Last Post: Liliana
  Using Tkinter inside function not working Ensaimadeta 5 4,863 Dec-03-2023, 01:50 PM
Last Post: deanhystad
  GUI Problem / call another function / fill QListwidget flash77 5 836 Jul-30-2023, 04:29 PM
Last Post: flash77
  simple tkinter question function call not opening image gr3yali3n 5 3,305 Aug-02-2022, 09:13 PM
Last Post: woooee
  [PyQt] [Solved]Help getting variable from Function in PyQt Extra 6 1,461 Jul-06-2022, 10:19 PM
Last Post: Extra
  Tkinter won't run my simple function AthertonH 6 3,743 May-03-2022, 02:33 PM
Last Post: deanhystad
  [PyQt] Call a function in FormA from FormB panoss 3 1,861 Jan-30-2022, 07:45 PM
Last Post: panoss
  [Tkinter] tkinter best way to pass parameters to a function Pedroski55 3 4,737 Nov-17-2021, 03:21 AM
Last Post: deanhystad
  [Tkinter] Update variable using tkinter entry methon drSlump 6 5,095 Oct-15-2021, 08:01 AM
Last Post: drSlump
  Creating a function interrupt button tkinter AnotherSam 2 5,419 Oct-07-2021, 02:56 PM
Last Post: AnotherSam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020