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

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.

Related

Is there a way to add a button in an askopenfile dialog window?

So this is the code
from tkinter import *
from tkinter import filedialog
win = Tk()
win.geometry('200x100')
def printer():
print("hello")
In the browse function im creating an askopenfile dialog window that allows me to choose a file with the button "Open"
def browse():
file = filedialog.askopenfile(parent=win, mode='rb', title='Choose a file')
if file is not None:
file.close()
In this browse function i would like an extra button next to the "Open" button that would say "Print" for example and would trigger the printer function from above
browse_button = Button(win, text="Browse", command=browse)
browse_button.pack(pady=100 / 10)
win.mainloop()

How do I create an Import File Button with Tkinter?

So you know how when you use Notepad (on Windows), for example, and you want to open an old file? You click file, then open, then a file dialog opens ups and you can select the file you want, and the program will display its contents.
Basically, I want to make a button in Python that can do that exact thing.
Here's my function for the button-
def UploadAction():
#What to do when the Upload button is pressed
from tkinter import filedialog
When I click on the button assigned to this action, nothing happens, no errors, no crash, just nothing.
import tkinter as tk
from tkinter import filedialog
def UploadAction(event=None):
filename = filedialog.askopenfilename()
print('Selected:', filename)
root = tk.Tk()
button = tk.Button(root, text='Open', command=UploadAction)
button.pack()
root.mainloop()

Tkinter file dialog combining save and load dialogs

I have an entry widget where the user can type in a file location, and underneath that a "save" button and a "load" button. Depending on which button is clicked, the file specified in the entry widget is either opened for writing, or for reading.
This all works fine and dandy.
Now I want to add a "browse" button, which the user can click to open a file dialog to select a file. When a file is selected, the filename is copied into the entry. From there on, the save and load buttons should work fine.
However, I can't figure out how to get the file dialog to work for both reading a file and writing. I can't use tkFileDialog.asksaveasfilename because that's going to complain to the user if a file already exists (which, if the user intends to "load", it should) and the tkFileDialog.askloadasfilename function doesn't let the user select a file which doesn't exist yet (which, if the user intends to "save", should be fine as well).
Is it possible to create a dialog which displays neither of these functionalities?
Is this what you're looking for:
from tkinter import *
from tkinter.filedialog import *
root = Tk()
root.title("Save and Load")
root.geometry("600x500-400+50")
def importFiles():
try:
filenames = askopenfilenames()
global file
for file in filenames:
fileList.insert(END, file)
except:
pass
def removeFiles():
try:
fileList.delete(fileList.curselection())
except:
pass
def openFile():
try:
text.delete(END)
fob = open(file, 'r')
text.insert(0.0, fob.read())
except:
pass
def saveFile():
try:
fob = open(file, 'w')
fob.write(text.get(0.0, 'end-1c'))
fob.close()
except:
pass
listFrame = Frame(root)
listFrame.pack()
sby = Scrollbar(listFrame, orient='vertical')
sby.pack(side=RIGHT, fill=Y)
fileList = Listbox(listFrame, width=100, height=5, yscrollcommand=sby.set)
fileList.pack()
sby.config(command=fileList.yview)
buttonFrame = Frame(root)
buttonFrame.pack()
importButton = Button(buttonFrame, text="Import", command=importFiles)
importButton.pack(side=LEFT)
removeButton = Button(buttonFrame, text="Remove", command=removeFiles)
removeButton.pack(side=LEFT)
openButton = Button(buttonFrame, text="Open", command=openFile)
openButton.pack(side=LEFT)
saveButton = Button(buttonFrame, text="Save", command=saveFile)
saveButton.pack(side=LEFT)
text = Text(root)
text.pack()
root.mainloop()
"I want one dialog which returns a filename that can be used for both saving and loading."
You can import file names using a dialog window; remove the selected file name from the list (additional function); open the file you selected; and finally, write and save them.
P.S.: There may be some bugs in my code, but I think, the algorithm does what the question asks.

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);
}

"No such file or directory" when opening file from tkFileDialog.askopenfilename

I want to have the user select images to have the logo image pasted onto. The file dialog pops up and lets you choose the image files fine. The logo image also loads up and gets resized. And the New Image file is made.
My problem comes with opening the images that were selected. When it gets to "im = PIL.Image.open(img)" it gives me an IOError that says "No such file or directory".
import PIL
import os.path
import PIL.Image
from Tkinter import *
from Tkinter import Tk
from tkFileDialog import askopenfilename
import Tkinter, tkFileDialog
def logo():
imgs = tkFileDialog.askopenfilename(parent=root, title='Choose files', multiple = True)
logo = PIL.Image.open('logo.jpeg')
logo_new = logo.resize((125, 100))
newpath = r'C:\Users\Austin\Desktop\New Images'
if not os.path.exists(newpath):
os.makedirs(newpath)
for img in imgs:
im = PIL.Image.open(img)
width, height = im.size()
im.paste(logo_new, ((width-125), (height-100)), mask=logo_new)
im.save(newpath)
#GUI Code
root = Tk()
root.title("Ad Maker") #GUI title
root.geometry("250x250") #GUI size
app = Frame(root)
app.grid()
button1 = Button(app, text="Logo", command=logo)
button1.grid() #sets button for the logo function
button2 = Button(app, text = "Frame")
button2.grid() #sets button for the frame function
root.mainloop()
I know this code probably isn't the best as I'm still fairly new to programming, but any help in getting the logo() function finally working would be really appreciated.

Categories

Resources