tags:

views:

19

answers:

2

Is there a way to return something when a button is pressed?

Here is my sample program. a simple file reader. Is the global variable to hold text contents the way to go since I can't return the contents?

from Tkinter import *
import tkFileDialog

textcontents = ''

def onopen():
    filename = tkFileDialog.askopenfilename()
    read(filename)

def onclose():
    root.destroy()

def read(file):
    global textcontents
    f = open(file, 'r')

    textcontents = f.readlines()
    text.insert(END, textcontents)

root = Tk()
root.title('Text Reader')
frame = Frame(root)
frame.pack()
text = Text(frame, width=40, height=20)
text.pack()
text.insert(END, textcontents)

menu = Menu(root)
root.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open...", command=onopen)
filemenu.add_command(label="Exit", command=onclose)

mainloop()
A: 

If you meant signal back to the user, here's some sample code:

import Tkinter
import tkMessageBox

top = Tkinter.Tk()

def helloCallBack():
   tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
top.mainloop()

and the source: Python - Tkinter Button tutorial

Michael Goldshteyn
posted code at the top
shawn
+1  A: 

Tk(inter) is event-based, which means, that you do not return values, but bind callbacks (functions) to actions.

more info here: http://effbot.org/tkinterbook/button.htm

mykhal