在python中调用变量

时间:2011-12-21 05:15:59

标签: python

Hii我需要在函数中调用变量,它在另一个函数中有声明和定义。可以请任何人帮助我。

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

这里,我在start()函数中遇到错误。给我接受src和des变量的问题。

4 个答案:

答案 0 :(得分:3)

我更新了您的代码(并在阅读完反馈后进行了更正)以使用类变量/属性并修复了您的错误消息,请将其检出。请注意,使用类变量意味着您只能将此类用作单例,一次只能使用其中一个类,因为每个实例都使用相同的Copy.src,Copy.des, Copy.textboxsrc和Copy.textboxdsc变量。

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

答案 1 :(得分:1)

Python提供了嵌套作用域(可能就是你所使用的),但它确实提供了一个函数,可以访问同一级别的另一个函数的局部变量。如果后者是您所需要的,请考虑使用全局变量。

有关范围界定的讨论,请参阅tutorial。另外,有关global declarations的讨论,请参阅语言参考。

在以下示例中, global 用于声明可以访问和写入两个不同函数的变量:

def f():
    global x
    x = 1

def g():
    global x
    x = 2

这是一个嵌套作用域的示例,其中内部函数可以读取但不能在封闭函数中写入变量:

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

在Python 3中,添加了 nonlocal 关键字以支持从内部函数写入 x

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

答案 2 :(得分:1)

相反,感谢使用global关键字,你的类方法需要绑定到父对象。看起来你真的需要完成有关python的范围规则的教程。

  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

答案 3 :(得分: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()