I have a function to choose an excel file through the file explorer in tkinter:
import pandas as pd
from tkinter import *
from tkinter import filedialog
def fileopen():
filepath = filedialog.askopenfilename(filetypes=(("xlsx", "*.xlsx"), ("all files", "*.*"))) #windows file explorer
label = Label(window, text=filepath) #label to return file's directory path
label.pack()
label.place(x=200, y=80)
df = pd.read_excel(filepath)
This process is extremely slow. I click on the excel file and have to wait for 10-15 seconds for the path to show on my label. But when I removed the pd.read_excel() part:
def fileopen():
filepath = filedialog.askopenfilename(filetypes=(("xlsx", "*.xlsx"), ("all files", "*.*")))
label = Label(window, text=filepath)
label.pack()
label.place(x=200, y=80)
it would return the path of my excel file in an instant, so the slowness lies in the pandas function. But I can't remove it or my program won't work at all. How can I get around this?
Related
im a beginner at python and im trying to created a program using tkinter that view and edit text. i used pyinstaller to make an .exe file to view text, but when i used "open with" to a text file and select my text viewer program nothing shows.
then i noticed that how is my program supposed to open the file and display its contents. because originally i have this button "open file" that when clicked it, it will ask me what to open, but now that opening the file comes first before the program runs, i cannot click the button so my program does not know what to do. is there any way for my program to know what am i trying to open? do i have to import something?
thanks for the answer
from tkinter import *
from tkinter import filedialog
root=Tk()
def openfile():
textname=filedialog.askopenfilename(title="Open File", filetypes=(("Text", "*.txt"), ("Python", "*.py"), ("Html", "*.html"), ("All Files", "*.*")))
openedfile=open(textname,'r')
content=openedfile.read()
n_text.insert(END,content)
openedfile.close()
n_text=Text(root, font=11, relief=FLAT)
n_text.pack()
btn=Button(root, text="open", command=openfile).pack()
root.mainloop()
Not sure if I understood your question well. Do you need to know the path of the file you are opening?
from os.path import split
textname=filedialog.askopenfilename(title="Open File", filetypes=(("Text", "*.txt"), ("Python", "*.py"), ("Html", "*.html"), ("All Files", "*.*")))
pathname = split(textname)
#This print is just to show your path and filename
print("path:", pathname[0], "file:",pathname[1])
Based on your comments I add a new answer it take the full path from arguments on scripts.
from tkinter import *
from tkinter import filedialog
import sys
root=Tk()
def openfile():
textname=filedialog.askopenfilename(title="Open File", filetypes=(("Text", "*.txt"), ("Python", "*.py"), ("Html", "*.html"), ("All Files", "*.*")))
openedfile=open(textname,'r')
content=openedfile.read()
n_text.insert(END,content)
openedfile.close()
n_text=Text(root, font=11, relief=FLAT)
n_text.pack()
btn=Button(root, text="open", command=openfile).pack()
if len(sys.argv) == 2:
openedfile=open(sys.argv[1],'r')
content=openedfile.read()
n_text.insert(END,content)
openedfile.close()
root.mainloop()
I added the path in this format:
c:/Users/user/Python/pruebas.py "C:\Users\user\Desktop\text_file.txt"
It is possible to open a file in tkinter from pc using right click->Open with->My Program.
I just want the file path when using this method.
You can't open a file using the method you are asking for( right-click > Open with > My Program) but you can create a program to open and edit files within a GUI using the Tkinter file dialog library and the open() function.
An example of the Method I am talking about:
from tkinter import *
from tkinter.filedialog import askopenfilename
windows = Tk()
windows.title("File Dialog Example")
windows.geometry("500x500")
def file_open():
text_window.delete('1.0', END)
filePath = askopenfilename(
initialdir='C:/', title='Select a File', filetype=(("Text File", ".txt"), ("All Files", "*.*")))
with open(filePath, 'r+') as askedFile:
fileContents = askedFile.read()
text_window.insert(INSERT, fileContents)
print(filePath)
open_button = Button(windows, text="Open File", command=file_open).grid(row=4, column=3)
text_window = Text(windows, bg="white",width=200, height=150)
text_window.place(x=50, y=50)
windows.mainloop()
And in order to save the changes to the file, you can read the contents in the Text Box and then write the contents to the Opened file.
Thanks
So I am trying to have the user upload an image for a flag, but I keep getting the same error "type object 'Image' has no attribute 'open'".
I have looked this up and I can't seem to find the answer. I have tried importing Image as IMG and I get the error "'module' object is not callable". I have tried
import PIL.Image
and I get the same error.
# Imports
from tkinter import * # Tkinter is a GUI toolkit used for Python. This toolkit allows me to create the window and many of the UI options
import Pmw # Pmw stands for 'Python mega widgets'. I imported this primarily for tooltips so the user knows what everything means
from tkinter import Image
from tkinter import filedialog
Function the file browser is opened
def flagOpener():
global flagIMG
flagPath = filedialog.askopenfilename(initialdir="/", title="Select an Image File", filetypes=(("Png Files", "*.png"), ("Jpeg Files", "*.jpg; *.jpeg"), ("All Files", "*.*")))
flagIMG = Image(Image.open(flagPath))
flagLabel = Label(image=flagIMG)
and the button
flagSelect = Button(politicalframe, text = "Select Flag", command=flagOpener())
flagSelect.pack()
Your import statement is messing it up, python is confused between Image from PIL and Image from tkinter. What you should do is:
import PIL
....
def flagOpener():
global flagIMG
flagPath = filedialog.askopenfilename(initialdir="/", title="Select an Image File", filetypes=(("Png Files", "*.png"), ("Jpeg Files", "*.jpg; *.jpeg"), ("All Files", "*.*")))
flagIMG = Image(PIL.Image.open(flagPath))
flagLabel = Label(image=flagIMG)
Plus, I don't think you should be using Image from tkinter, use ImageTk.PhotoImage from PIL and with that all the problems might go away:
from PIL import Image, ImageTk
...
def flagOpener():
global flagIMG
flagPath = filedialog.askopenfilename(initialdir="/", title="Select an Image File", filetypes=(("Png Files", "*.png"), ("Jpeg Files", "*.jpg; *.jpeg"), ("All Files", "*.*")))
flagIMG = ImageTk.PhotoImage(Image.open(flagPath))
flagLabel = Label(image=flagIMG)
then your button should be:
flagSelect = Button(politicalframe, text = "Select Flag", command=flagOpener) # Remove the () so your not calling it immediately
flagSelect.pack()
Also on a side note, if at all you plan on making an exe later with this code, then Pmw will give you all the uncalled errors, so I recommend you make your own tooltip like mentioned here or tackle the error by following the answer to this post: How can I convert a .py to .exe using pmw?
I am very new to Python so apologizing up front for a stupid question. I am building a small application that allows me to first seach for an excel file (with filedialog) from my computer, imports it into the program and then I could do something with it.
So the application has a button "search file" and "save file", but the save_file function doesnt work. It works if I put it inside the open_file function.
Am I going completely to wrong way here? I tried to google like crazy, but didnt find an answer for this
Thanks a lot for your support!
-KV
""" IMPORT AND SAVE XLSX FILE """
def open_file():
filename = filedialog.askopenfilename(title="Select file", filetypes=(("Excel files", "*.xlsx"),("Excel files", ".xls")))
file_entry.insert(END, filename)
def save_file():
file_data = pd.read_excel(filename)
print(file_data)
""" UI SETUP """
file_entry = Entry(width=60)
file_entry.grid(row=1, column=1)
file_button = Button(text="Select File", width=13, command=open_file)
file_button.grid(row=1, column=2)
file_button = Button(text="Save File", width=13, command=save_file)
file_button.grid(row=1, column=3)
In save_file() the variable filename isn't defined. You have to call the function with an argument e. g. save_file(filename) or define it inside the function.
I want to read the content of the selected file by opening with tk filedialog. When i select the file and click on open button the file doesn't open but rather close the dialog box .How can i open the selected file with notepad so i can be able to read the content in the file.
from tkinter import *
from tkinter import filedialog
def my_file():
filename = filedialog.askopenfile(mode="r", initialdir="/", title="select file",
filetypes=(("text files", "*.txt"), ("all files", "*.*")))
root = Tk()
root.geometry("300x300")
#open the selected txt file with notepad to read the content
b = Button(root, text="open text file", command = my_file).pack()
root.mainloop()
EDIT
With hint from #PM 2RING and #Erik i changed the filedialog.askopenfile to filedialog.askopenfilename to return it to open with notepad.exe when i select the file.
THis is the code:
from tkinter import *
from tkinter import filedialog
import os
def my_file():
filename = filedialog.askopenfilename( initialdir="C:/", title="select
file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
for f in filename:
return f
os.system(r"C:/notepad.exe" + f)
root = Tk()
root.geometry("300x300")
#open the selected txt file with notepad to read
the content
b = Button(root, text="open text file", command = my_file).pack()
root.mainloop()
it output this error :
Blockquote'C:/notepad.exet' is not recognized as an internal or external command,
operable program or batch file.
Blockquote
but when i changed the return to print it print the directory to terminal.I tried to open with subprocess
subprocess.Popen([r'C:\Program Files (x86)\Notepad.exe' + f])
it also doesn't open with this one to.
There's a few things which need to be amended here.
First of all, C:/notepad.exe is not the location of Notepad (At least not on any Windows machine with a default setup), you can simply use notepad.exe which should make it more compatible with systems that have moved Notepad to another location (citation needed).
Secondly, executing . . .
for f in filename:
return f
os.system(r"C:/notepad.exe" + f)
Doesn't do what you seem to think it does. What's actually happening here is that your program is loading the string into the loop, evaluating the first character (Probably "C") and then returning the string to the Button widget which doesn't receive any returned values. This then breaks your function, so it never actually reaches your declaration of os.system(r"C:/notepad.exe" + f).
You also need to include a space between the statement used to open Notepad notepad.exe and the actual file declaration f, otherwise you're running something like notepad.exeC:/text.txt which is going to throw an error at you.
What you should be doing is something like the below:
from tkinter import *
from tkinter import filedialog
import os
def my_file():
filename = filedialog.askopenfilename( initialdir="C:/", title="select file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
os.system(r"notepad.exe " + filename)
root = Tk()
root.geometry("300x300")
b = Button(root, text="open text file", command = my_file).pack()
root.mainloop()
I'd like to add that I have no clue why you're doing this, why not simply display the text in a Text widget? What you're doing here is adding one extra step for people to open files in Notepad, instead of opening file explorer, finding the file and then opening it they have to open your program, then open file explorer, then find the file and then open it. It's adding at least one extra click not to mention the load time of your program.
As mentioned by PM 2Ring, I would use the os.system function. As mentioned in its description, "os.system(command)" let's you execute the command as if you had written it in the command prompt, so os.system("Notepad c:/users/yourName/junk.txt) would open a file named junk.txt if it were at that location.
In other words, once you have the filename from your filedialog.askopenfilename call, do something like this:
import os
os.system("Notepad " + filename) # where filename is the string that filedialog.askopenfilename returns
The implementation into your code shouldn't be too bad, but if you need a more complete example, let let me know.
The following code will display a button and a text widget. The button will load in your file, and the text widget will display it. I assume this is what you had in mind?
from tkinter import *
from tkinter import filedialog
def my_file():
file = filedialog.askopenfile(mode="r", initialdir="/", title="select file",
filetypes=(("text files", "*.txt"), ("all files", "*.*")))
t.insert(END, file.read())
file.close()
root = Tk()
root.geometry("300x300")
#open the selected txt file with notepad to read the content
t = Text(root)
t.grid(row=0, column=0)
b = Button(root, text="open text file", command = my_file)
b.grid(row=1, column=0)
root.mainloop()