Python\Tkinter:在类的外部使用存储在类函数中的变量
我正在尝试为我的程序制作一个图形用户界面(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 个回答
-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)
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
这个方法,就看你自己了(可能是通过另一个事件监听器的回调来实现)。