0

Im writing this basic Tk program that can open text documents but i can seem to get it to work

Here is my code:

from Tkinter import *
from tkFileDialog import askopenfilename
def openfile():
   filename = askopenfilename(parent=root)
   f = open(filename)
   x = f.read()
   return x


root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)


text = Text(root)
text.insert(INSERT,(x))

text.pack()

root.config(menu=menubar)
root.mainloop()

im trying to input x into my tk window but its saying its not defined even though i returned x

why isnt this working im sure its something easy but i cant figure it out!

2 Answers 2

3

So you have two related problems here.

  1. You're trying to use x even though you haven't defined it yet
  2. Returning anything from openfile won't work in this situation since you can't set it as another variable (like x)

What you probably want to do is read the file and insert it in the Text widget all in the same function call. Try something like this,

from Tkinter import *
from tkFileDialog import askopenfilename

def openfile():
    filename = askopenfilename(parent=root)
    f = open(filename)
    x = f.read()
    text.insert(INSERT,(x,))

root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

text = Text(root)
text.pack()

root.config(menu=menubar)
root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

1

When you return a value from a function, you need to assign it to a variable like so (pseudocode):

myVariable = openfile()

And then you can use this variable in your arguments as:

text.insert(INSERT, (myVariable))

Variable x is defined within the function so its out of scope.

2 Comments

when i do it this way when i run the GUI it just opens up the file dialog instead of opening the GUI then waiting for the user to click Open
@ChristianCareaga Don't have python on this computer or I'd check the code for you. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.