2
from Tkinter import *
from tkFileDialog import askopenfilename
from PIL import Image
def main():
    filename = askopenfilename(filetypes=[("Jpeg","*.jpg")])
return filename
root = Tk()
button = Button(root,text="Open",command=main)
button.pack()
root.title("Image Manipulation Program")
root.mainloop()

I am kind of a newbie at programming in general, but I am trying to make an imaging program through the Tkinter GUI library. What I need to be able to do in the code above is return the string that is stored in filename so it is in the global scope of the program and I am able to use it. The problem is I don't know how to do this when calling the function with a button. I cannot find the answer to this problem on any website so I would appreciate anybody's help with this problem.

Brian Hauger
  • 490
  • 1
  • 4
  • 22

2 Answers2

6

If you use the class based approach to Tk applications, instead of returning values from event handlers, you can assign them to instance variables. This the best approach, as function-based GUI applications don't scale well precisely because the need to place stuff at module scope.

from Tkinter import *

class Application(Frame):

    def main(self):
        self.filename = askopenfilename(filetypes=[("Jpeg","*.jpg")])

    def createWidgets(self):
        self.button = Button(root,text="Open",command=self.main)
        self.button.pack()

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.filename = None
        self.pack()
        self.createWidgets()

root = Tk()
root.title("Image Manipulation Program")
app = Application(master=root)
app.mainloop()
Apalala
  • 9,017
  • 3
  • 30
  • 48
2

Generally, it is bad practice to use global variables to pass information around your program. However, if you really must do this, use a mutable data type (such as a list or a dict) as your global variable and change its contents from your callback function, main.

returned_values = {}    # Create an empty dict.
def main():
    returned_values['filename'] = askopenfilename(filetypes=[("Jpeg","*.jpg")])
    # returned_values['filename'] may now be accessed in the global scope.

If you intend to do this frequently, consider implementing your own class to pass information around.

Adeel Zafar Soomro
  • 1,492
  • 9
  • 15