Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter Return

Tags:

python

tkinter

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()
like image 486
shawn Avatar asked Jul 17 '26 12:07

shawn


1 Answers

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

like image 87
mykhal Avatar answered Jul 19 '26 02:07

mykhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!