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
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()

screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
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)


    result = ''.join(l)

    return str(result)
def output():
  n = 0
  while n < passNum.get():
    paStr = randompassword() + '\n'
    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.


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",y=0,width=600,height=31)

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",y=160,width=169,height=30)

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",y=160,width=142,height=30)
pass_length["textvariable"] = passLen

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",y=210,width=169,height=31)

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",y=210,width=142,height=30)
pass_num["textvariable"] = passNum

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",y=270,width=142,height=30)
gen_pass["command"] = output

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",y=270,width=346,height=192)

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",y=320,width=142,height=30)
#copy_pass["command"] = copy 

if __name__ == "__main__":
You could call def_copy from within  def_output, passing the pw as an argument ?

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


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.
OK, i have used pyperclip to copy things to the clipboard:
import pyperclip

def output():
  password = 'pw'

def copy(pw):

thank you bro but it's not what I am searching for.
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()
def copy():

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() 

Possibly Related Threads…
Thread Author Replies Views Last Post
  Using Tkinter inside function not working Ensaimadeta 3 203 Dec-23-2020, 02:57 PM
Last Post: deanhystad
  Stop import from executing function, but allow the function to execute from tk btn. MrBitPythoner 4 201 Dec-08-2020, 10:00 PM
Last Post: MrBitPythoner
  function in new window (tkinter) Dale22 7 352 Nov-24-2020, 11:28 PM
Last Post: Dale22
  [Tkinter] tkinter global variable chalao_adda 6 301 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 269 Oct-23-2020, 05:46 PM
Last Post: deanhystad
  Tkinter function to clear old canvas and start a fresh "operation" zazas321 5 383 Oct-01-2020, 04:16 AM
Last Post: zazas321
  tkinter get method is not accepting value when called by function jagasrik 1 288 Sep-16-2020, 05:28 AM
Last Post: Yoriz
  [Tkinter] Use function from other class (Tkinter) zarize 8 614 Aug-17-2020, 09:47 AM
Last Post: zarize
  [Tkinter] updating tkinter chart from within function mikisDW 1 371 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 706 Jun-05-2020, 04:46 PM
Last Post: AndreiV

Forum Jump:

User Panel Messages

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