Python Tkinter Browsing a File- Issue - python

I am experiencing some issues when displaying the location of the image selected. Is there a reason why it displays <_io.TextIOWrapper name =along with mode='r'encoding ='cp1252>? I just want it to display the location of the image along with the name of the image not those extra stuff. Is there something that I am doing that is causing this to occur? Please advise.
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Upload Image", command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfile(initialdir = "/", title = "Select a File", filetype = (("jpeg", "*.jpg"), ("All files", "*.")))
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)

filedialog.askopenfile gives file object, not file name.
You have to display self.filename.name instead of self.filename
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
file_object = filedialog.askopenfile(title="Select file")
print('file_object:', file_object)
print('file_object.name:', file_object.name)
#data = file_object.read()
label = tk.Label(root, text=file_object.name)
label.pack()
root.mainloop()
Or use askopenfilename instead of askopenfile and you get file name.
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
filename = filedialog.askopenfilename(title="Select file")
print('filename:', filename)
#data = open(filename).read()
label = tk.Label(root, text=filename)
label.pack()
root.mainloop()

Related

tkinter: AttributeError: 'Button' object has no attribute 'get' when trying to access file from filedialog.askopenfilename

So I have something like this:
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import pandas as pd
window = tk.Tk()
window.geometry('350x240')
def open_file():
temp_file = filedialog.askopenfilename(title="Open file", filetypes=[("Excel files", "*.csv")])
temp_file = open(temp_file, "r")
Proj_df = pd.read_csv(temp_file)
open_button = ttk.Button(text='Select File...', command=open_file)
open_button.grid(column=1, row=1)
def get_info():
x = open_button.get()
print (x)
button1 = ttk.Button(text='Get Information', command=get_info)
button1.grid(column=0, row=2)
What I'm trying to do is to store the DataFrame created in open_file() to use it in get_info(). I'm getting:
AttributeError: 'Button' object has no attribute 'get'
How could I access the DataFrame created in open_button?
This might help you along the way. You can set a tk.StringVar then use to retrieve, store, and access items that are input through various tk/ttk widgets. Also I suppose you might want to store your inbound file? I ran this attempt simply reading in the csv, not using pandas.
import tkinter as tk
from tkinter import filedialog, ttk
#import pandas as pd
window = tk.Tk()
window.geometry('350x240')
tkvar1 = tk.StringVar(window)
def open_file():
temp_file = filedialog.askopenfilename(title="Open file", filetypes=[("Excel files", "*.csv")])
temp_file = open(temp_file, "r")
tkvar1.set(temp_file.read())
#Proj_df = pd.read_csv(temp_file)
open_button = ttk.Button(text='Select File...', command=open_file)
open_button.grid(column=1, row=1)
def get_info():
x = tkvar1.get()
print (x)
button1 = ttk.Button(text='Get Information', command=get_info)
button1.grid(column=0, row=2)
window.mainloop()

Convert multiple images to pdf

I wanted to create a pdf converter app with python which converts images to pdf.
This is my code but it is only converting one image into pdf I tried many ways to fix it but none of them worked can anyone please help me because I want to convert multiple images into pdf but it is not working besides using for loop. I tried img2pdf but it giving alpha channel error and I am not able to solve that.
import PIL.Image
from tkinter import *
from tkinter import filedialog as fd
import PyPDF2
import img2pdf
from tkinter import ttk
root = Tk()
root.geometry('500x500')
root.resizable(0, 0)
filename = StringVar()
entry = Entry(root, width=50, textvariable=filename).place(x=115, y=250)
def Select_images():
global files
files = fd.askopenfilenames()
def select_dir():
global dir_name
dir_name = fd.askdirectory()
def submit():
global file_name
file_name = filename.get()
def create_pdf():
myfile=open(f'{dir_name}/{file_name}.pdf', 'wb+')
for image in files:
img=PIL.Image.open(image).convert('RGBA')
im1=img.convert('RGB')
im1.save(r'{}\{}.pdf'.format(dir_name,file_name))
myfile.close()
button = Button(root, text='Sumbit PDF Name', command=submit).place(x=200, y=300)
label = Label(root, text='Write PDF Name').place(x=210, y=215)
button1 = Button(root, text='Create File', command=create_pdf).place(x=215, y=335)
button2 = Button(root, text='Select Directory To Save File',command=select_dir).place(x=200, y=50)
button3 = Button(root, text='select Images', command=Select_images).place(x=235, y=100)
root.mainloop()
See if this helps you:
from tkinter import Tk, messagebox as mb, filedialog as fd
from tkinter.constants import DISABLED, NORMAL
from tkinter.ttk import Button, Label
from PIL import Image
import os
root = Tk()
root.title("Image to PDF converter")
root.geometry("500x500")
imglist = [] # For creating a list of images
fimgl = [] # List for storing multiple image names
png = True # If the image chosen is a .png file
def askfile():
global files, fimg, order, imglist, tm, png
files = fd.askopenfilenames(title="Choose images", filetypes=(("PNGs", "*.png"), ("JPGs", "*.jpg"), ("All Files", "*.*")))
for i in files:
fimgl.append(i)
if files:
for j in fimgl:
if j.endswith(".png"): # If the image is a PNG:
png = True
fnl = Label(root, text=j)
fnl.pack()
img = Image.open(j)
fimg = img.convert('RGB')
imglist.append(fimg)
p.config(state=NORMAL)
def convert_pdf():
global png
try:
if png:
imglist.pop()
saveloc = fd.asksaveasfilename(title="Save the PDF file")
if saveloc:
if saveloc.endswith(".pdf"):
pass
else:
saveloc = saveloc + ".pdf"
if os.path.exists(saveloc):
yn = mb.askyesno("Confirm Save As", f"{os.path.basename(saveloc)} already exists.\nDo you want to replace it?")
if yn:
os.remove(saveloc)
else:
convert_pdf()
fimg.save(saveloc, save_all=True, append_images=imglist)
mb.showinfo("Done!", "PDF file saved! Click 'OK' to open it")
os.startfile(saveloc)
root.quit()
except Exception as err:
mb.showerror("Error", err)
root.quit()
cb = Button(root, text="Add Files", command=askfile)
cb.pack(pady=20)
p = Button(root, text="Convert", command=convert_pdf, state=DISABLED)
p.pack(pady=20)
root.mainloop()

Update Label in Tkinter to prevent overlapping text

I'm new to Tkinter and I'm trying to create a simple Button that opens a file dialog box, where the user chooses which CSV file to open. Under the button there is a label that should display the file path for the file that was opened.
When I click on the button once, everything works as expected. However, if I click on it a second time and select a different file, the new filepath overlaps with the previous one, instead of replacing it.
Here is the code for the implementation function (please let me know if you need more bits of code for context):
def open_csv_file():
global df
global filename
global initialdir
initialdir = r"C:\Users\stefa\Documents\final project models\Case A"
filename = filedialog.askopenfilename(initialdir=initialdir,
title='Select a file', filetypes = (("CSV files","*.csv"),("All files","*.*")))
df = pd.read_csv(os.path.join(initialdir,filename))
lbl_ok = tk.Label(tab2, text = ' ') #tab2 is a ttk.Notebook tab
lbl_ok.config(text='Opened file: ' + filename)
lbl_ok.grid(row=0,column=1)
Here is how to do it with .config(), create the label instance just once (can then grid as much as you want but probably just do that once too), then just configure the text:
from tkinter import Tk, Button, Label, filedialog
def open_file():
filename = filedialog.askopenfilename()
lbl.config(text=f'Opened file: {filename}')
root = Tk()
Button(root, text='Open File', command=open_file).grid()
lbl = Label(root)
lbl.grid()
root.mainloop()
You can use a StringVar for this. Here is an example that may help you:
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.geometry('200x200')
def openCsv():
csvPath.set(askopenfilename())
csvPath = StringVar()
entry = Entry(root, text=csvPath)
entry.grid(column=0, row=0)
btnOpen = Button(root, text='Browse Folder', command=openCsv)
btnOpen.grid(column=1, row=0)
root.mainloop()

changing extensions of all images in a folder with tkinter

I want to convert the image formats of all images in a folder using tkinter. all extensions I want in a combobox but I don't know why this code doesn't work .no error is displayed.
from tkinter import filedialog, StringVar
from tkinter import ttk
root=tkinter.Tk()
root.geometry("800x600")
#defining functions
def get_folder():
global folder_path
folder_path = filedialog.askdirectory(initialdir='./', title="Select Folder")
print(folder_path)
def get_extension():
change_to = com.get()
change_from = "py"
files=os.listdir(folder_path)
for file in files:
if (".%s"%change_from) in file:
newfile=file.replace((".%s"%change_from),".%s"%change_to)
os.rename((folder_path+'/'+file),(folder_path+'/'+newfile))
#defining widgets for frames
folder_label = tkinter.Label(from_frame)
browse_button = tkinter.Button(from_frame, text="Browse", command=get_folder)
change_button = tkinter.Button(button_frame, text="Change Extension", command=get_extension)
change_button.pack()
#defining combobox
com = StringVar()
list_combo = ['.png','.jpg','.jpeg', '.svg', '.tif','.bmp','.gif','ppm']
combox = ttk.Combobox(root, width = 25, font = 'arial 19 bold', value = list_combo, state = 'r', textvariable = com)
combox.place(x= 190, y= 190)
combox.set('select type')
root.configure(bg = 'coral1')
root.mainloop()```
Is this what You want:
from tkinter import Tk, Button, Label, StringVar, Frame
from tkinter.ttk import Combobox
from tkinter.filedialog import askdirectory
import os
def convert_extensions():
path = dir_lbl.cget('text')
from_ = from_var.get()
to_ = to_var.get()
files_from = [f'{path}/{file}' for file in os.listdir(path) if file.split('.')[-1] == from_]
files_to = ['.'.join(file.split('.')[:-1]) + '.' + file.split('.')[-1].replace(from_, to_) for file in files_from]
for from_file, to_file in zip(files_from, files_to):
os.rename(from_file, to_file)
print(f'{"-" * 100}\n'
f'{"From:": <10} {from_file}\n'
f'{"To:": <10} {to_file}\n')
root = Tk()
root.geometry('500x200')
Button(root, text='Choose Directory', command=lambda: dir_lbl.config(text=askdirectory())).pack(pady=5)
dir_lbl = Label(root, text='')
dir_lbl.pack(pady=5)
options_frame = Frame(root)
options_frame.pack(pady=5)
from_var = StringVar(value='Convert from')
list_combo = ['png', 'jpg', 'jpeg', 'svg', 'tif', 'bmp', 'gif', 'ppm']
Combobox(options_frame, value=list_combo,
textvariable=from_var, state='r').pack(side='left', padx=5, pady=5)
to_var = StringVar(value='Convert to')
Combobox(options_frame, value=list_combo,
textvariable=to_var, state='r').pack(side='left', padx=5, pady=5)
Button(root, text='Convert', command=convert_extensions).pack(pady=5)
root.mainloop()
This however allows more control in that You can choose both the extension to convert and to which one convert.
This is pretty basic so if You have any questions, ask. I will probably add a detailed explanation later but for now this is all I can do. Oh and btw that three line print function is not necessary at all and it probably should be made to display that in tkinter window or sth but otherwise it can be removed.

Saving file path in a variable using tkinter

I'm using tkinter to create a GUI for an old script I have, but I'm stuck right now.
I want to click a button to open the "Search File" window, choose a specific file and save its path in a variable.
The code I have is able to open the window, then I can select the file and display it's path, but I couldn't find a way to save this path in a variable.
This is what I have:
from tkinter import *
from tkinter import filedialog
def get_file_path():
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
Does anyone know a good way to do this?
Use global variable:
from tkinter import *
from tkinter import filedialog
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
print(file_path)
Once your windows closed, you'll get your file_path.
You could declare file_path as global variable in get_file_path
def get_file_path():
global file_path
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
l1 = Label(window, text = "File path: " + file_path).pack()
Then you can access that variable from anywhere in the script
------Edit------
According to what you said in your comment, i say you could use tkinter.StringVar to save the file path, and then to access it later when calling count_frames as an argument.
It could be implemented as the following:
from tkinter import *
from tkinter import filedialog
file_path_var = StringVar()
def get_file_path():
# Open and return file path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("mov files", "*.png"), ("mp4", "*.mp4"), ("wmv", "*.wmv"), ("avi", "*.avi")))
file_path_var.set(file_path) #setting the variable to the value from file path
#Now the file_path can be acessed from inside the function and outside
file_path_var.get() # will return the value stored in file_path_var
l1 = Label(window, text = "File path: " + file_path).pack()
window = Tk()
# Creating a button to search the file
b1 = Button(window, text = "Open File", command = get_file_path).pack()
# will also return the value saved in file_path_var
file_path_var.get()
window.mainloop()
print(file_path)
So now where ever your count_frames function is, as long as you have selcted a file first you should be able to just do
count_frames(file_path_var.get())

Categories

Resources