Reputation: 129
I'm trying to make a GUI version of my program. This is the first time I use a GUI manager, specifically Tkinter. Basically the user insert a text (url) in an Entry widget, click a button and then the program does things. Consider the following code:
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()
when I enter a valid url and click the button, I can get the text inserted and create the real url to pass to urllib2. However, how can I use the variable "req" anywhere in my program outside the function and the class?
Upvotes: 0
Views: 902
Reputation: 49
Use a global variable (or if you want persistent storage the pickle or shelve modules):
""" 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)
Upvotes: -1
Reputation: 3947
Store the variable in the Application
object:
def GetURL(self):
url_target = ("http://www." + self.EntryText.get())
self.req = urllib2.urlopen(url_target)
So you can use it in other methods of the class, for example
def do_something_with_req(self):
print self.req.getcode()
How the method do_something_with_req
is invoked is up to you (perhaps via another event listener callback).
Upvotes: 1