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
  simple tkinter question function call not opening image gr3yali3n 5 317 Aug-02-2022, 09:13 PM
Last Post: woooee
  [PyQt] [Solved]Help getting variable from Function in PyQt Extra 6 277 Jul-06-2022, 10:19 PM
Last Post: Extra
  Tkinter won't run my simple function AthertonH 6 734 May-03-2022, 02:33 PM
Last Post: deanhystad
  [PyQt] Call a function in FormA from FormB panoss 3 1,005 Jan-30-2022, 07:45 PM
Last Post: panoss
  [Tkinter] tkinter best way to pass parameters to a function Pedroski55 3 1,479 Nov-17-2021, 03:21 AM
Last Post: deanhystad
  [Tkinter] Update variable using tkinter entry methon drSlump 6 2,258 Oct-15-2021, 08:01 AM
Last Post: drSlump
  Creating a function interrupt button tkinter AnotherSam 2 2,270 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Have tkinter button toggle on and off a continuously running function AnotherSam 5 1,771 Oct-01-2021, 05:00 PM
Last Post: Yoriz
  [Tkinter] Passing variable to function. KDog 2 1,290 May-25-2021, 09:15 PM
Last Post: KDog
  return a variable from a function snakes 3 1,768 Apr-09-2021, 06:47 PM
Last Post: snakes

Forum Jump:

User Panel Messages

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