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
  function in new window (tkinter) Dale22 7 160 Nov-24-2020, 11:28 PM
Last Post: Dale22
  [Tkinter] tkinter global variable chalao_adda 6 184 Nov-14-2020, 05:37 AM
Last Post: chalao_adda
Star [Tkinter] How to perform math function in different page of Tkinter GUI ravaru 2 158 Oct-23-2020, 05:46 PM
Last Post: deanhystad
  Tkinter function to clear old canvas and start a fresh "operation" zazas321 5 240 Oct-01-2020, 04:16 AM
Last Post: zazas321
  tkinter get method is not accepting value when called by function jagasrik 1 214 Sep-16-2020, 05:28 AM
Last Post: Yoriz
  [Tkinter] Use function from other class (Tkinter) zarize 8 498 Aug-17-2020, 09:47 AM
Last Post: zarize
  [Tkinter] updating tkinter chart from within function mikisDW 1 302 Jul-02-2020, 03:33 AM
Last Post: deanhystad
  [Tkinter] Override the paste function(copy from excel file - paste in separate tkinter entryes) AndreiV 3 536 Jun-05-2020, 04:46 PM
Last Post: AndreiV
  [Tkinter] Tkinter wouldn't work with python3.8.3 shay_xs 2 623 May-24-2020, 11:48 PM
Last Post: Larz60+
  Passing arguments into function, tkinter nanok66 3 638 Apr-18-2020, 11:53 PM
Last Post: nanok66

Forum Jump:

User Panel Messages

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