python file dialog accessing file name - python

Im trying to use tkinter to open a file dialog, once this file dialogue is open how do i get the file object that is returned by the function. As in how do i access it in main?
basically how do i handle return values by functions that are invoked by command
import sys
import Tkinter
from tkFileDialog import askopenfilename
#import tkMessageBox
def quit_handler():
print "program is quitting!"
sys.exit(0)
def open_file_handler():
file= askopenfilename()
print file
return file
main_window = Tkinter.Tk()
open_file = Tkinter.Button(main_window, command=open_file_handler, padx=100, text="OPEN FILE")
open_file.pack()
quit_button = Tkinter.Button(main_window, command=quit_handler, padx=100, text="QUIT")
quit_button.pack()
main_window.mainloop()

Instead of returning the file variable, just handle it there (I also renamed the file variable so you do not override the built-in class):
def open_file_handler():
filePath= askopenfilename() # don't override the built-in file class
print filePath
# do whatever with the file here
Alternatively, you can simply link the button to another function, and handle it there:
def open_file_handler():
filePath = askopenfilename()
print filePath
return filePath
def handle_file():
filePath = open_file_handler()
# handle the file
Then, in the button:
open_file = Tkinter.Button(main_window, command=handle_file, padx=100, text="OPEN FILE")
open_file.pack()

the easiest way I can think of is to make a StringVar
file_var = Tkinter.StringVar(main_window, name='file_var')
change your callback command using lambda to pass the StringVar to your callback
command = lambda: open_file_handler(file_var)
then in your callback, set the StringVar to file
def open_file_handler(file_var):
file_name = askopenfilename()
print file_name
#return file_name
file_var.set(file_name)
Then in your button use command instead of open_file_handler
open_file = Tkinter.Button(main_window, command=command,
padx=100, text="OPEN FILE")
open_file.pack()
Then you can retrieve the file using
file_name = file_var.get()

Related

Picture won't open in File Dialog, Tkinter, Pillow

I have written this.
Its short and supposed to open a file dialog window, with buttons "open a file, turn, save, exit."
I want to open a jpeg, turn it 180° and then save it and quit.
The program starts, but doesnt open the picture in the file dialog window after I select it in the browser.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import filedialog
from tkinter.filedialog import askopenfilenames
root = Tk() ##pro Tkinter
root.title('Image Browser')
root.geometry('100x100')
def open():
global my_image
root.filename = filedialog.askopenfilenames(initialdir='/gui/pillow', filetypes=[('Images','*.jpg *.jpeg *.png')])
#my_label = Label(root, text = root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_image_label = Label(image=my_image).pack()
def turn():
return
my_image = my_image.transpose(Image.FLIP_RIGHT_LEFT)
def save():
return
my_image.save('somepic.jpg')
button = Button (root, text = 'Select a File', command = open)
button.pack()
button4 = Button (root, text = 'Turn', command = turn)
button4.pack()
button2 = Button (root, text = 'Save', command = save)
button2.pack()
button3 = Button(root, text = 'Exit', command = jadro.quit)
button3.pack()
root.mainloop()
After I select and try to open the file, it says this
AttributeError: 'tuple' object has no attribute 'seek'
I feel like I've tried everything, but cant seem to solve it.
Thanks for any help
askopenfilenames return a tuple.
Try this instead
my_image = ImageTk.PhotoImage(Image.open(root.filename[0]))
From Python DOC
tkinter.filedialog.askopenfilename(**options)
tkinter.filedialog.askopenfilenames(**options)
The above two functions create an Open dialog and return the selected filename(s) that correspond to existing file(s).
Therefore askopenfilenames() returns a tuple of filenames, instead Image.open(fp) requires a file pointer as argument, not a tuple.
From Pillow DOC:
PIL.Image.open(fp, mode='r', formats=None)
fp – A filename (string), pathlib.Path object or a file object. The file object must implement file.read, file.seek, and file.tell methods, and be opened in binary mode.

Use variable outside of function or in other function?

Ive rewritten this for more context, in a logical order this is what i want the program to do
1 by pressing open file it needs to open a specified file and put it into the text widget (done)
2 by pressing the extract file it needs to extract something from a specified subtree(in an xml file)
3 export the extracted data to a text file
but lets go back to point nr 2 as i have not yet written the extractor(easy part) first i need to refference a file i want to edit, and that is where i run into my problem. inside extract it cant acess vars in openfile and i dont want to reopen the file again.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import tkinter as tk
interface = tk.Tk()
interface.geometry("500x500")
interface.title("Text display")
def openfile():
filename = filedialog.askopenfilename()
print(filename)
file = open(filename)
txt = file.read()
print(txt)
T = tk.Text(interface, height=10, width=50)
T.insert(tk.END, txt)
T.grid(column=1, row=2)
return txt
def extract():
print(txt)
button = ttk.Button(interface, text="Open text File", command=openfile) # <------
button.grid(column=1, row=1)
buttonex = ttk.Button(interface, text="Extract subtitles", command=extract) # <------
buttonex.grid(column=2, row=1)
interface.mainloop()
NameError: name 'txt' is not defined (when i press extract)
As the edit of the initial questions shows that a GUI is planned I would suggest to move your TK widgets into an interface class as in the tkinter documentation. Further, if you plan to do more complex manipulations you should make an own class to hold your data resp. manipulate it.
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
# Create your buttons and connect them to the methods
self.button_load = tk.Button(self)
self.button_load["command"] = self.loadTextFromFile()
self.button_load["text"] = "Load Data"
self.button_load.gird(column=1, row=1)
self.buttonex = tk.Button(self)
self.buttonex["text"] = "Extract subtitles"
self.buttonex["command"] = self.extract()
self.buttonex.grid(column=2, row=1)
# Create the text widget
self.text_widget = tk.Text(self, height=10, width=50)
self.text_widget.grid(column=1, row=2)
def loadTextFromFile(self):
filename = filedialog.askopenfilename()
print(filename)
try:
file = open(filename)
txt = file.read()
file.close()
self.text_widget.insert(tk.END, txt)
except Exception:
# If anything went wrong, close the file before reraising
file.close()
raise
def extract(self):
# Now you have access to self.text_widget and it holds your read in text
do_something(self.text_widget)
# Maybe at the following functions to make your file importable without directly executing it. Could come in handy later on.
def run():
# create the application
myapp = App()
#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)
# start the program
myapp.mainloop()
if __name__ == '__main__':
run()
Have a look at the tkinter documentation for further examples: https://docs.python.org/3/library/tkinter.html
The additional if clause checks if your module is the main module and executes the run function. This defines an entry point if you directly run your module and prevents functions from execution at import time if you intend to import the module into another module. A more detailed explanation can be found here:
What does if __name__ == "__main__": do?
---------- Old Answer --------------
As pointed out in the comment you need to somehow return your local variables back to the calling function in order to be able to use them somewhere else. This could be achieved by a simple return statement:
def openfile():
""" It is the responsibility of the caller to close the return value """
filename = filedialog.askopenfilename()
print(filename)
try:
file = open(filename)
txt = file.read()
T = tk.Text(interface, height=10, width=50)
T.insert(tk.END, txt)
T.grid(column=1, row=2)
return file
except Exception:
# If anything went wrong, close the file before reraising
file.close()
raise
would for example return the open fileid for further manipulation. E.g.:
def extract():
with openfile() as file:
txtex = file.read()
print (txtex)
If your goal is howeer, to manipulate the file content and read it later you would need to save your manipulations back into the file otherwise your second read would not see the changes. Dont forget to close your file again.
I changed three lines where I believe to have come across typos:
From: self.button_load["command"] = self.loadTextFromFile() to: self.button_load["command"] = self.loadTextFromFile
From: self.button_load.gird(column=1, row=1) to: self.button_load.grid(column=1, row=1)
From: self.buttonex["command"] = self.extract() to: self.buttonex["command"] = self.extract
Thank you for this example!

NameError: global name 'name' is not defined when using multiple files and Tkinter

I'm trying to show the filepath of an accessed file in an 'Entry' box in Tkinter. Because of the requirements of this task I have to define all the functions in one file, and all the Tkinter fields in another and import the functions into the Tkinter file.
I tried putting all the code in a single file to see if that was causing any issues, and it worked fine. The problem is the task requires that I use seperate .py files.
def open_file():
filePath = askopenfilename()
with open(filePath, 'rU') as anotherFile:
inputString = anotherFile.read()
filePathEntry.delete(0, END)
filePathEntry.insert(0, filePath)
And in the other file:
from AT3_Functions_v2 import *
main = Tk()
main.geometry("600x400")
openfile = Button(main, text="Open Scoresheet", command=open_file).grid(row=0, column=0)
filePathEntry = Entry(main)
filePathEntry.grid(row=0, column=1)
mainloop()
When I put both segments of code in a single file it works flawlessly, however when I seperate it again it gives me the error:
NameError: global name 'filePathEntry' is not defined
When you place all your code in one single file then your open_file function can find filePathEntry variable. But when you split the code in two script then open_file can not find filePathEntry because it is in different file.
To solve this then you need to pass an argument in your open_file function using lambda function then place pass filePathEntry variable from another file. I have done for you.
script_one.py
from tkinter import *
from script_two to import *
main = Tk()
main.geometry("600x400")
filePathEntry = Entry(main)
filePathEntry.grid(row=0, column=1)
openfile = Button(main, text="Open Scoresheet", command=lambda: (open_file(filePathEntry))).grid(row=0, column=0) # Passing arugument to open_file function which is in script_two.py
mainloop()
script_two.py
from tkinter import *
from tkinter import filedialog
def open_file(entry_box): # Passing argument to access filePathEntry variable from script_one.py
filePath = filedialog.askopenfilename()
with open(filePath, 'rU') as anotherFile:
inputString = anotherFile.read()
entry_box.delete(0, END)
entry_box.insert(0, filePath)

I want to use extensions list at the time of "save as" option in File Dialog for file write in Python 3

I want to use extensions list example : [".txt",".html",".css"] for save as option in file dialog popup window. when I use this method
file_opt = options = {}
options['defaultextension'] = '.txt',I can able to write any file with .txt as default extension without choose in save as option but I want to choose extensions for save as in file dialog popup window from using my extensions list.
I'm using Python 3.5 based Anaconda IDE
If you look at the documentation here you can see that you can pass in the filetypes keyword which specifies a list of tuples that have the name, and file extension respectively for the different types of filetypes you want to be able to save as.. So you can do something along the lines of:
import tkinter as tk
from tkinter import filedialog as fd
def save_file():
filename = fd.asksaveasfilename(defaultextension='.txt',
filetypes= [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')])
if filename:
print("User saved the filename with extension:", filename.split(".")[-1])
root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
Or if you really want to use a dictionary for this:
import tkinter as tk
from tkinter import filedialog as fd
SAVE_OPTS = {'defaultextension':'.txt',
'filetypes': [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')]}
def save_file():
filename = fd.asksaveasfilename(**SAVE_OPTS)
if filename:
print("User saved the filename with extension:", filename.split(".")[-1])
root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "Text File (*.txt)|*.txt|PNG File (*.txt)|*.png"|...;
if(sd.ShowDialog() == DialogResult.OK) {
richTextBox1.SaveFile(sd.FileName, RichTextBoxStreamType.PlainText);
}

Python's tkinter Buttons - How to get return values of functions from other buttons?

I am working on a tkinter interface for an assignment that opens a file, reads and modifies it, then outputs it to a new file. I have buttons that, when clicked, let the user browse their computer for the appropriate files. Those separate functions return the filename ("randomInputFile.txt").
My problem is that I have a third button that should take those two values and then use them in the reading/writing process. I'm not sure how to pass the input/output filenames as parameters to the read/write function.
Should I just pass the filenames as global variables within the respective function?
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
def openGUI():
wn = Tk()
wn.title("Homework 10 - CSIS 153")
openFileButton = Button(wn, text="Open", command = openFile)
openFileButton.pack()
openFileButton.place(bordermode=OUTSIDE, height=90, width=90)
saveFileButton = Button(wn, text="Save to...", command = saveFile)
saveFileButton.pack()
saveFileButton.place(bordermode=OUTSIDE, height=90, width=90, x=110, )
executeButton = Button(wn, text="Run Program", command = splitSentences(****SOMETHING, SOMETHING****))
executeButton.pack()
executeButton.place(bordermode=OUTSIDE, height=90, width=123, x=40, y=115)
wn.mainloop()
def openFile():
inputFile = askopenfilename()
msg = "You are opening:\n\n" + str(inputFile)
messagebox.showinfo("File Location", msg)
return inputFile
def saveFile():
outputFile = asksaveasfilename()
return outputFile
def splitSentences(inFile, outFile):
with open(inFile) as myFile:
#etc etc
You can't return anything to a Button, so there's no use in those lines at the end of the functions. And yes, the easiest thing to do would be to make inputFile and outputFile global variables. Then, you also wouldn't need to pass them as an argument to splitSentences(), that function would just access them directly.
However, the better way to do it would be to make your GUI a class, and those variables as instance variables. You should also provide some way to disable the executeButton until you have values for the inputFile and outputFile variables, otherwise that function will throw an error.

Categories

Resources