Filedialog print file path not properly - python-3.x

l am doing practice with Tkinter and its feature. l have been working on "filedialog". I have no problem with select the file. But, l would like to select an image and open on Tkinter. However, it keep giving error when l click on open the image.
When Printed out the path of file, io.TextIOWrapper name='D:/GIS/Python_Pro/Tkinter_lib/my_image/nature_1.jpg' mode='r' encoding='cp1254. How can l get only path as `'D:/GIS/Python_Pro/Tkinter_lib/my_image/nature_1.jpg'.
def Select_File():
root.filename =filedialog.askopenfile(initialdir='D:\GIS\Python_Pro\Tkinter_lib\my_image',title="Select a file",filetypes=(("png files","*.png"),("ico files","*.ico"),("All Files","*.*")))
path_file=Label(root,text=root.filename ).pack()
my_img=ImageTk.PhotoImage(Image.open(root.filename))
img_label=Label(root,image=my_img).pack()
#Buttons
Btn_1=Button(root,text="Select a file",command=Select_File).pack()

The function filedialog.askopenfile will return a IO object.You can use this when you need to revise this file.
If you just need to get the full path,use filedialog.askopenfilename,and it will return the file path you select.

try filedialog.askopenfilename instead of filedialog.askopenfile

Related

Python script output need to save as a text file

import os ,fnmatch
import os.path
import os
file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']
for root, dirs,files in os.walk( file_dir ):
for extension in ( tuple(file_type) ):
for filename in fnmatch.filter(files, extension):
filepath = os.path.join(root, filename)
if os.path.isfile( filepath ):
print(filename , 'executing...');
exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())
else:
print('Execution failure!!!')
Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?
Piggybacking off of the original answer since they are close but it isn't a best practice to open and close files that way.
It's better to use a context manager instead of saying f = open() since the context manager will handle closing the resource for you regardless of whether your code succeeds or not.
You use it like,
with open("file.txt","w+") as f:
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
try
Open file
f= open("file.txt","w+")
Insert data into file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Close the file
f.close()

Is there any way i can change browse a file button to it's file path?

i'm making a program which is need to browse a photo
and i've put browse a file button and everything is working well, but i want
when the user choose a file
to change the button name to that file's path
please help.
i've tried to use global inside the function so i can name a variable out the function " browse a file " and inside the function change it's name and insert it inside the button but it didn't work with me, maybe i didn't know how or it doesn't work this way
from tkinter import *
from tkinter import filedialog
window = Tk()
window.geometry('500x500')
def filename1():
window.filename1 = filedialog.askopenfilename(initialdir="/",title="Select file", filetypes=(
('jpeg', "*.jpeg"), ("jpg", "*.jpg"), ("all files", "*.*")))
print(window.filename1) # here it's print the file path
filebrowsebutton1 = Button(text="Browse a file",command=filename1).place(x=60, y=280)
window.mainloop()
First returning the filename from filename1() will not change the text of the browse button. Second filebrowsebutton1 will not assigned the instance reference of Button, but None because you have chained the function .place(...).
Below is an updated version of the code to solve the above issues:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.geometry('500x500')
def filename1():
filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('jpeg', '*.jpeg *.jpg'),('all files', '*.*')))
if filename:
# update button text with the selected filename
browsebutton['text'] = filename
browsebutton = tk.Button(text='Browse a file', command=filename1)
browsebutton.place(x=60, y=200)
window.mainloop()

adding a filename to a list in tkinter

i have a method that opens a file and then calls another method,
which opens up a window (i am using tkinter) that asks the user whether he would like to open another file. Now, each time a file gets opened i want to add the filename to a list, but in my case when i look at the result the list only contains the last selected filename.
I will include my stripped down code:
def fileopening(self):
from tkinter.dialog import askopenfilename
import os.path
self.inputfilenamelist = []
self.fileopenname.set(askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")]))
basename = os.path.basename(self.fileopenname.get())
self.inputfilenamelist.append(basename)
self.askforanotherinput()
def askforanotherinput(self):
inputwindow = tk.Toplevel(root)
inputwindow.title("Inputselection")
inputwindow.minsize(400,200)
asklabel = tk.Label(inputwindow,text="Select another inputfile?")
asklabel.pack()
answeryesbutton = tk.Button(inputwindow,text="Yes")
answeryesbutton.pack()
answeryesbutton["command"]=lambda:[inputwindow.destroy(),self.fileopening()]
answernobutton = tk.Button(inputwindow,text="No")
answernobutton.pack()
answernobutton["command"]=lambda:[inputwindow.destroy(),self.fileopeningcounter.set(0)]
Can anyone help me ? The thing is i need this "method-calling-loop" since i am using the opened files in further data conversion as a whole.

How to type text in wxPython FilePickerCtrl text box without getting an error?

I have a wxPython-based program where I create a file selection interface using FilePickerCtrl:
class MainFrame (wx.Frame):
...
def __init__(self, parent):
self.filePicker = wx.FilePickerCtrl(self, wx.ID_ANY, path = wx.EmptyString,
message = "Select a file", wildcard = "*.m",
pos = wx.DefaultPosition,
size = wx.DefaultSize,
style = wx.FLP_OPEN|wx.FLP_USE_TEXTCTRL)
self.Bind(wx.EVT_FILEPICKER_CHANGED, self.onFilePicker,
id = self.filePicker.GetId())
...
def onFilePicker(self, event):
self.resetOnOpen(event)
path = self.filePicker.GetPath()
self.openFile(event, path)
self.modifyHistory(event, path)
The button to select a file works fine, and I can select a file as expected. But as soon as I type even a single character in the text box next to the button, I get an exception: [Errno 2] No such file or directory. It appears that it's trying to find the file immediately, rather than waiting for the user to finish typing a path. (This happens on macOS 10.13, in case the OS is relevant.)
What is the proper way to let the user type a path in the box (if they prefer to type a path instead of clicking the file browsing button)?
I'm new to wxPython and obviously doing something wrong here, but can't seem to find an example of how to do this the right way.
At least on Linux, the wx.FLP_USE_TEXTCTRL causes an event to fire for each key depression and I suppose that it is the same for other operating systems.
Ensure that you import os then change your onFilePicker routine to check for the files existence.
def onFilePicker(self, event):
self.resetOnOpen(event)
path = self.filePicker.GetPath()
if not os.path.isfile(path):
return
self.openFile(event, path)
self.modifyHistory(event, path)

Remove letter from python text widget using bind function

I have just started to create a simple text editor. I have already bound a couple of functions to certain keypresses and now I'm trying to add a function that operates on the Return delete being pressed. The aim is to remove the last character entered into the text widget. Here is my code:
from tkinter import *
from tkinter import filedialog
import os
root = Tk()
root.geometry('{}x{}'.format(500, 500))
def addchar(event):
w.insert(END, event.char)
def deletechar(event):
current = w.get()
new = current[:-1]
w.delete(0,END)
w.insert(END, new)
def savefile(event):
file = filedialog.asksaveasfilename(defaultextension=".txt")
if file is None:
return
text2save = str(w.get())
file.append(data)
file.close()
w = Entry(root, bd=1)
w.pack()
w.place(x=0, y=0, width=500)
root.bind("<Key>", addchar)
root.bind("<BackSpace>", deletechar)
root.bind("<Control-s>", savefile)
root.bind("<Return>", newline)
root.mainloop()
The issue I'm having is that nothing is removed upon pressing delete to remove the last character entered. Any help appreciated. P.S. Ive tried adding a savefile function to save the text to a file but it doesn't work if anyone can help there also, it would again be appreciated :)
I didn't try to run your code right know because I'm running out of time. However, first of all, you should not use pack and place geometry manager in the same Toplevel, you should only use one. Second, in your savefile function, you did not open the file, so your file variable is only a string. You should use something like file = open(file).

Resources