Python \ Tkinter:使用存储在类外的类函数中的变量

时间:2014-07-30 09:44:08

标签: python python-2.7 tkinter

我试图制作我的程序的GUI版本。这是我第一次使用GUI管理器,特别是Tkinter。 基本上用户在Entry小部件中插入文本(url),单击按钮然后程序执行操作。 请考虑以下代码:

import Tkinter as tk
import urllib2

class Application(tk.Frame): 
    def __init__(self, master=None):
        tk.Frame.__init__(self, master) 
        self.grid() 
        self.createWidgets()
    def createWidgets(self):
        self.EntryText = tk.Entry(self, bg='red') 
        self.GetButton = tk.Button(self, text='Print',
                                command=self.GetURL) 
        self.GetButton.grid(row=0, column=1)
        self.EntryText.grid(row=0, column=0)

    def GetURL(self):
         url_target = ("http://www." + self.EntryText.get())
         req = urllib2.urlopen(url_target)
         print req.getcode()


app = Application() 
app.master.title('App') 
app.mainloop()

当我输入有效的网址并点击按钮时,我可以插入文字并创建传递给urllib2的真实网址。 但是,我如何使用变量" req"在函数和类之外的程序中的任何地方?

2 个答案:

答案 0 :(得分:1)

将变量存储在Application对象中:

def GetURL(self):
  url_target = ("http://www." + self.EntryText.get())
  self.req = urllib2.urlopen(url_target)

所以你可以在类的其他方法中使用它,例如

def do_something_with_req(self):
  print self.req.getcode()

如何调用方法do_something_with_req取决于您(可能通过另一个事件侦听器回调)。

答案 1 :(得分:-1)

使用全局变量(或者如果你想要持久存储pickle或shelve模块):

""" main.py """

import Tkinter as tk
import urllib2
from testreq import fromTestreq, fromTestreq2

reqtext = ""                # Declaration of global variable

class Application(tk.Frame): 
    def __init__(self, master=None):
        tk.Frame.__init__(self, master) 
        self.grid() 
        self.createWidgets()
    def createWidgets(self):
        self.EntryText = tk.Entry(self, bg='red')
        self.EntryText.insert(0,"google.com")
        self.GetButton = tk.Button(self, text='Print', command=self.GetURLApp) 
        self.GetButton.grid(row=0, column=1)
        self.EntryText.grid(row=0, column=0)

    def GetURLApp(self):
        global reqtext       # Declaration of local variable as the global one
        url_target = "http://www." + self.EntryText.get()
        req = urllib2.urlopen(url_target)
        print req.geturl()
        print req.getcode()
        reqUrlStr = str(req.geturl())
        reqCodeStr = str(req.getcode())
        reqtext = reqUrlStr
        #reqtext = reqCodeStr
        fromTestreq(reqtext)
        #print reqtext


if __name__ == '__main__':
    app = Application() 
    app.master.title('App') 
    app.mainloop()
    fromTestreq2(reqtext)


""" testreq.py """

def fromTestreq(text):
    print("From testreq: " + text)

def fromTestreq2(text):
    print("From testreq2: " + text)