1

Hii I have a requirement of calling the variable in function which is having it declaration and definition in another function.Could any one help me please.

import sys
import os
import tkMessageBox
from Tkinter import *
from tkCommonDialog import Dialog
import shutil
import tkFileDialog
import win32com.client

win = Tk()
win.title("Copying the Directory to specified location")
win.geometry("600x600+200+50")
win.resizable()
global src
global des
class Copy():
    #global src
    #global des
    def __init__(self):
        def srce():
            src = tkFileDialog.askdirectory(title = "The source folder is ")
            textboxsrc.delete(0,END)
            textboxsrc.insert(0,src)
            print src
            return src

        textboxsrc = Entry(win, width="70")
        textboxsrc.insert(0,'Enter master file name')
        textboxsrc.pack()
        textboxsrc.place(relx=0.40, rely=0.06, anchor=CENTER)
        bu = Button(text = "Source",font = "Verdana 12 italic bold",bg = "Purple",fg= "white", command= srce)
        bu.pack(fill =X, expand=YES)
        bu.place(relx=0.85, rely=0.06, anchor=CENTER)

        def dest():
            des = tkFileDialog.askdirectory(title = "TheDestination folder is ")
            textboxdes.delete(0,END)
            textboxdes.insert(0,des)
            print des
            return des

        textboxdes = Entry(win, width="70")
        textboxdes.insert(0,'Enter master file name')
        textboxdes.pack()
        textboxdes.place(relx=0.40, rely=0.13, anchor=CENTER)
        bu1 = Button(text = "Destination",font = "Verdana 12 italic",bg = "Purple",fg= "white", command= dest)
        bu1.pack(fill =X, expand=YES)
        bu1.place(relx=0.85, rely=0.13, anchor=CENTER)

        def start():
            #global src
            #global des
            #abc = os.path.dirname(src)
            #dgh = os.path.dirname(des)
            try:
                shutil.copy(src,des)
            except :
                tkMessageBox.showwarning("Copying file",  "Error while copying\n(%s)" )

        bn =Button(text = "Copy",font = "Verdana 12 italic", bg = "Purple",fg= "white",command=start)
        bn.pack(fill =X, expand = YES)
        bn.place(relx=0.50, rely=0.25, anchor=CENTER)

obj= Copy()
#obj.source(win)
#obj.destination(win)
win.mainloop()

Here,I get an error in the start() function. giving me the problem of accepting src and des variable.

5
  • What do you mean by "calling a variable"? Does the variable contain a reference to a function? Can you post some example code of what you're trying to do? Commented Dec 21, 2011 at 5:17
  • Actually I want the string that got assigned to a variable in another function. Commented Dec 21, 2011 at 5:19
  • You should probably be using a global variable. Or have your first function return the value of this variable, and pass it in to the second function that requires it. Commented Dec 21, 2011 at 5:21
  • I will give my code and please check it out. Commented Dec 21, 2011 at 5:23
  • @wim I was completely pleased by your ans.May be that might the problem.Please give me solution that aovids my problem. Commented Dec 21, 2011 at 5:38

4 Answers 4

3

i updated your code (and made the corrections needed after reading your feedback) to use class variables/attributes and fixed your error message, check it out. Please note, using class variables means you can only use this class as a singleton, only one of these classes can be used at a time because every instance would use the same Copy.src, Copy.des, Copy.textboxsrc and Copy.textboxdsc variables.

import sys
import os
import tkMessageBox
from Tkinter import *
from tkCommonDialog import Dialog
import shutil
import tkFileDialog
import win32com.client

win = Tk()
win.title("Copying the Directory to specified location")
win.geometry("600x600+200+50")
win.resizable()

# force "new" Python class by inheriting from "object"
class Copy(object):

    # use class attributes for shared variables
    src = None
    des = None
    textboxsrc = None
    textboxdes = None

    def srce():
        # access the class attributes via "Copy." syntax
        Copy.src = tkFileDialog.askdirectory(title = "The source folder is ")
        Copy.textboxsrc.delete(0,END)
        Copy.textboxsrc.insert(0,Copy.src)
        print Copy.src
        return Copy.src

    textboxsrc = Entry(win, width="70")
    textboxsrc.insert(0,'Enter master file name')
    textboxsrc.pack()
    textboxsrc.place(relx=0.40, rely=0.06, anchor=CENTER)
    bu = Button(text = "Source",font = "Verdana 12 italic bold",bg = "Purple",fg= "white", command= srce)
    bu.pack(fill =X, expand=YES)
    bu.place(relx=0.85, rely=0.06, anchor=CENTER)

    def dest():
        # access the class attributes via "Copy." syntax
        Copy.des = tkFileDialog.askdirectory(title = "TheDestination folder is ")
        Copy.textboxdes.delete(0,END)
        Copy.textboxdes.insert(0,Copy.des)
        print Copy.des
        return Copy.des

    textboxdes = Entry(win, width="70")
    textboxdes.insert(0,'Enter master file name')
    textboxdes.pack()
    textboxdes.place(relx=0.40, rely=0.13, anchor=CENTER)
    bu1 = Button(text = "Destination",font = "Verdana 12 italic",bg = "Purple",fg= "white", command= dest)
    bu1.pack(fill =X, expand=YES)
    bu1.place(relx=0.85, rely=0.13, anchor=CENTER)

    def start():
        # access the class attributes via "Copy." syntax
        print "copy src(%s) to des(%s)" % (Copy.src,Copy.des)
        try:
            shutil.copy(Copy.src,Copy.des)
        except:
            tkMessageBox.showwarning("Copying file",  "Error while copying\n(%s) to (%s)\n%s\n%s"
            % (Copy.src,Copy.des, sys.exc_info()[0], sys.exc_info()[1]) )


    bn =Button(text = "Copy",font = "Verdana 12 italic", bg = "Purple",fg= "white",command=start)
    bn.pack(fill =X, expand = YES)
    bn.place(relx=0.50, rely=0.25, anchor=CENTER)

obj= Copy()
win.mainloop()
Sign up to request clarification or add additional context in comments.

5 Comments

Dude I am getting the error as ::"self is not defined at self.src = tkFileDialog.askdirectory(title = "The source folder is ")"
And when pass the self parameter to srce function it is giving me the error as follows srce() takes exactly 1 argument (0 given)
Sorry for the error, i've corrected the code. Although I tested my original solution, I made a mistake when posting the code, apologies. I have tested the above code and it works as is for me on Windows x86 using the ActiveState Python v2.7.2 distribution: activestate.com/activepython/downloads.
@ Richard Logwod Thanks for the answer dude. Dis too worked out
@ Bharath Gupta I updated your class instance variable solution below to include initialization in init for "self.src = None" and "self.des = None", I think it's better to use instance variables here. your code below works for me with the edits i made, also synced error message with code in my example
1

Python provides nested scopes (which may be what you're after) but it does provide one function with access to local variables of another function at the same level. If the latter is what you need, consider using a global variable.

See the tutorial for a discussion of scoping. Also, see the language reference for a discussion of global declarations.

In the following example, global is used to declare a variable that can be accesses and written in two different functions:

def f():
    global x
    x = 1

def g():
    global x
    x = 2

Here is an example of a nested scope where an inner function can read but not write a variable in an enclosing function:

def f():
    x = 1
    def g():
        print(x)
    return g

In Python 3, the nonlocal keyword was added to support writing to x from the inner function:

def f():
    x = 1
    def g():
        nonlocal x
        x += 1
    g()
    print(x)

Comments

1

Rather thank mucking around with global keyword, your class methods need to be bound to the parent object. Looks like you really need to work through a tutorial about python's scoping rules.

  class Copy(object):
    def __init__(self):
      # don't define further methods in here!

    def srce(self):
      self.src = ...

    def dest(self):
      self.des = ..

    def start(self):
      #Here you can access self.des and self.src

1 Comment

Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in call return self.func(*args) TypeError: srce() takes exactly 1 argument (0 given) This is the exception that was raised when i have used self dude. What should i do now. I was totally blank in mind
0
import sys
import os
import tkMessageBox
from Tkinter import *
from tkCommonDialog import Dialog
import shutil
import tkFileDialog
import win32com.client

win = Tk()
win.title("Copying the Directory to specified location")
win.geometry("600x600+200+50")
win.resizable()


class Copy(object):


    def __init__(self):
        def srce():

            self.src = tkFileDialog.askdirectory(title="The source folder is ")
            textboxsrc.delete(0, END)
            textboxsrc.insert(0, self.src)
            print self.src
            return self.src

        textboxsrc = Entry(win, width="70")
        textboxsrc.insert(0, 'Enter master file name')
        textboxsrc.pack()
        textboxsrc.place(relx=0.40, rely=0.06, anchor=CENTER)
        bu = Button(text="Source", font="Verdana 12 italic bold", bg="Purple", fg="white", command=srce)
        bu.pack(fill=X, expand=YES)
        bu.place(relx=0.85, rely=0.06, anchor=CENTER)

        def dest():
            self.des = tkFileDialog.askdirectory(title="TheDestination folder is ")
            textboxdes.delete(0, END)
            textboxdes.insert(0, self.des)
            print self.des
            return self.des

        textboxdes = Entry(win, width="70")
        textboxdes.insert(0, 'Enter master file name')
        textboxdes.pack()
        textboxdes.place(relx=0.40, rely=0.13, anchor=CENTER)
        bu1 = Button(text="Destination", font="Verdana 12 italic", bg="Purple", fg="white", command=dest)
        bu1.pack(fill=X, expand=YES)
        bu1.place(relx=0.85, rely=0.13, anchor=CENTER)

        def start():


            try:
                shutil.copytree(self.src, self.des)
            except :
                tkMessageBox.showwarning("Copying file", "Error while copying\n(%s)")

        bn = Button(text="Copy", font="Verdana 12 italic", bg="Purple", fg="white", command=start)
        bn.pack(fill=X, expand=YES)
        bn.place(relx=0.50, rely=0.25, anchor=CENTER)

obj = Copy()
#obj.source(win)
#obj.destination(win)
win.mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.