如何从函数到另一个函数获取变量?

时间:2015-02-15 12:12:16

标签: python tkinter

我正在尝试创建一个简单的Tkinter用户注册应用,但遇到了问题。我希望从Entry获取输入到另一个函数。

截至目前我的代码:

from Tkinter import *

def addUsr():
    username = sv.get()              #here
    password = sv1.get()             #here
    page = open("Users.txt", 'r+')
    contents = page.read()
    page.write("--->")
    page.write("\n")
    page.write("username: " + username) 
    page.write("\n")
    page.write("password: " + password)
    page.write("\n")
    page.write("<---")
    page.write("\n")
    page.close()
    print contents


def reg():
    usrs = Tk()
    usrs.title("Text")
    usrs.geometry('450x300+200+200')
    sv = StringVar()
    sv1 = StringVar()
    ent1 = Entry(usrs, textvariable=sv).pack()
    ent2 = Entry(uses, textvariable=sv1).pack
    button1 = Button(usrs, text="submit", command=addUsr).pack(side='bottom', padx=15, pady=15)
    usrs.mainloop()

我想将svsv1放入addUsr函数,但此代码会返回错误消息:

username = sv.get()
NameError: global name 'sv' is not defined

当构建代码以使第二个函数不是函数时,此代码可以正常工作。我只是想找到一种方法来获得相同的结果,但使用这种结构。你怎么想我这样做?

1 个答案:

答案 0 :(得分:0)

我认为这是一个结构性问题。您通常会使用类来创建应用程序并将所有内容放在该类下。然后从任何地方访问函数和变量都很简单。我创建了一个简单的例子,因为我没有时间重写你的所有代码!

from Tkinter import *

class Application(Frame): # create a class to hold the application within

    def __init__(self, master): # boot it up
        """ Initialize the frame. """
        Frame.__init__(self, master) 
        self.grid()
        self.create_widgets()
        self.var1 = "var1"
        self.var2 = "var2"

    def create_widgets(self): # create the GUI interface

        self.lbl = Label(self, text = "xxxx")
        self.lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W, pady = 4)
        self.input = Text(self, width = 35, height = 5, wrap = WORD)
        self.input.grid(row = 1, column = 0, columnspan = 2, sticky = W)
        self.submit_button = Button(self, text = "submit", command = self.functionX)
        self.submit_button.grid(row = 2, column = 0, columnspan = 2, sticky = W)

    def functionX(self):

        print "do some stuff"
        self.var3 = "yet another variable" # create a variable in one function for access in another
        self.functionY() # call one function from another function

    def functionY(self):

        print "do something else"
        print self.var1 # access some class variables
        print self.var2
        print self.var3

root = Tk() 
root.title("xxxxxxxxxxxx")
root.geometry("330x310")
app = Application(root)

我希望这会有所帮助,当您运行代码并阅读它以了解正在发生的事情时,它是非常自我解释的。 (顺便说一句,我最终使用PyQt / Pyside和QtDesigner而不是Tkinter,你可能想要检查一下,如果你还不知道它。)