Right now, I have a GUI program that allows you to change parameters and stuff like that. I want to make it so you can choose a picture instead of only having one for the whole thing.
I have this:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
When I try to use this, it will just say that it cannot import filedialog.
EDIT:
Okay, so I just fixed that error by using:
import tkFileDialog as filedialog
Now I just need help making the file I choose be the one that appears on the canvas. Right now, I have this:
__dir__ = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(__dir__, root.filename)
img = PIL.Image.open(filename)
shrek= img.resize((100,100))
root = Tk() # create main window; must be done before using ImageTk
root.filename = filedialog.askopenfilename(initialdir = "E:/Images",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
I am trying to make the file that I choose from the explorer replace the current file.
This is for Python 2.x import tkFileDialog as filedialog
I guess you use Python 2.x..
Related
When I run my code, I can get any file filepath for further use and put it in the Entry box. When I try to get a filepath of a shortcut, another window opens up, saying "catastrophic error". The console remains quiet all the time. Here's my code:
from tkinter import *
from PIL import *
import os
from tkinter import filedialog
root = Tk()
def create_game():
# Defining the function for choosing the filepath
def add_data():
root.filename = filedialog.askopenfilename(initialdir="",title="Select A File",filetypes=((".EXE files", "*.exe"),("all", "*.*")))
enter_filepath.insert(0,str(root.filename))
enter_filepath = Entry(root,width=30)
enter_filepath.pack()
btn_filepath = Button(root,text="Choose file",command=add_data)
btn_filepath.pack()
create_game()
root.mainloop()
This is what I'm getting:
I need help on how to make a button after I choose a folder in dropdown list.
For Example: I have 3 folders name "Folder 1","Folder 2" & "Folder 3". Inside "Folder 1", I have 5 excel(.xlsx) files. So I need help on how to read and display the data in 1 excel(.xlsx) file.
My current situation: I choose "Folder 1" in the dropdown menu. The next thing that I need is a button which can open the "Folder 1" and display the other list of 5 excel(.xlsx) files. And then, I can choose one of the excel(.xlsx) file and display the data inside the gui.
Here is my code.... Help me :'(
import os
import tkinter as tk
from tkinter import ttk
#import tkinter as tk
from tkinter import filedialog, messagebox, ttk
folder = r'C:\Users\test folder'
filelist = [fname for fname in os.listdir(folder)]
master = tk.Tk()
master.geometry('1200x800')
master.title('Select a file')
optmenu = ttk.Combobox(master, values=filelist, state='readonly')
optmenu.pack(fill='x')
master.mainloop()
You cannot just select and read a file's contents from tkinter. You have to write some other scripts for that reading part.
What the selection of filename does from tkinter combo box, is nothing but, get the particular file name as a string type.
However, in Python it's pretty straight forward to read a .xlsx file.
You can use Pandas module for that.
I have written the code for you to read the file, (but you have to install pandas)
from functools import partial
import os
import tkinter as tk
from tkinter import ttk
#import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import pandas
def get_selected_file_name(file_menu):
filename = file_menu.get()
print("file selected:", filename)
reader = pandas.read_excel(filename) # code to read excel file
# now you can use the `reader` object to get the file data
folder = os.path.realpath('./test_folder')
filelist = [fname for fname in os.listdir(folder)]
master = tk.Tk()
master.geometry('1200x800')
master.title('Select a file')
optmenu = ttk.Combobox(master, values=filelist, state='readonly')
optmenu.pack(fill='x')
button_select = tk.Button(master, text="Read File",
width=20,
height=7,
compound=tk.CENTER,
command=partial(get_selected_file_name, optmenu))
button_select.pack(side=tk.RIGHT)
master.mainloop()
The window should look somewhat like this:
I'd explore using the filedialog module in tkinter.
import tkinter as tk
from tkinter import filedialog
def load_file():
f_in = filedialog.askopenfilename( filetypes = [ ( 'Python', '*.py' ) ]) # Change to appropriate extension.
if len( f_in ) > 0:
with open( f_in, 'r' ) as file:
filedata = file.read()
print( filedata ) # printed to the terminal for simplicity.
# process it as required.
root = tk.Tk()
tk.Button( root, text = 'Find File', command = load_file ).grid()
root.mainloop()
askopenfilename allows a user to navigate the folder tree to find the correct file. Basic documentation
I have a tkinter window and need to press a button to open a csv file. For example:
root = Tk()
def open_file():
# show the csv file to the user
open_button = Button(root, text="Open", command=open_file)
open_button.pack()
Is there a way to do this, or something similar? I have tried using askopenfilename, but this doesn't seem to work for me, as it only opens the home directory.
Have a look at this link. As you can see from the link, the approaches differ a bit for python 2.7 and 3. Since python 2.7 is reaching the end of its life, I will demonstrate for python 3:
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)
If you correctly installed tkinter using pip and filled all the arguments correctly it should work. Make sure the root directory actually exists and you specified syntactically correct (types of slashes matter).
You can also open the file picker even though it starts in the wrong directory. You can browse to the correct root directory and click ok and have the program print the directory. Then you'll know how to specify the root directory.
The following code show tkinter window with a button. When the user click the button and point to a CSV file, it would show the first few lines into a message box for show. I use pandas to open the CSV file.
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox as msgBox
import os
import pandas as pd
def open_file():
filename = filedialog.askopenfilename(initialdir=os.getcwd())
if(filename!=''):
df = pd.read_csv(filename, encoding = "ISO-8859-1", low_memory=False)
mR,mC=df.shape
cols = df.columns
num=5
pd.options.display.float_format = '{:.2f}'.format
msg=str(df.iloc[:num,:]) + '\n' + '...\n' + \
df.iloc[-num:,:].to_string(header=False) + '\n\n' + \
str(df.describe())
msgBox.showinfo(title="Data", message=msg)
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, text="Open", command=open_file)
button.pack(side = tk.LEFT)
root.mainloop()
I want to create a simple TKinter file selection dialog with a function that I will use from other scripts and not a wider GUI.
My current code is:
# Select a single file and return the full path as a string
def select_file(data_dir):
chdir(data_dir)
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
return file_path
When I run this the file dialog is always behind other windows. If I have Spyder maximised, it opens behind it so I have to minimise.
There are a few questions related to this, but I've been unable to get any of the suggested code to work, so apologies if this is viewed as a duplicate question.
Ben
Just have to use root.deiconify() after file_path = tkFileDialog.askopenfilename()
But it's a bad idea to create a new Tk here.
Use root.focus_force() to make the root window on top and the fileDialog should also be on top:
from Tkinter import *
import tkFileDialog
def select_file(data_dir):
root = Tk()
root.withdraw()
root.focus_force()
return tkFileDialog.askopenfilename(parent=root, initialdir=data_dir)
select_file(data_dir)
We're trying to store a directory path in a variable using Tkinter's tkFileDialog, and it won't work (details later).
from Tkinter import *
import os
from tkFileDialog import askopenfilename, askdirectory
# Create the window
root = Tk()
# Application title & size
root.title("Title")
root.geometry("1000x600")
# Creating frame to add things to
app = Frame(root)
app.grid() # Adding app frame to grid
# Method that opens file chooser
# Gets used when button is clicked (command)
def openFileBox():
directoryPicked = tkFileDialog.askdirectory()
#easygui.fileopenbox()
for filePicked in os.listdir(directoryPicked):
if filePicked.lower().endswith(".jpg") or filePicked.lower().endswith(".gif") or filePicked.lower().endswith(".png"):
print filePicked
#TODO: add button 'Select Folder'
loaderButton = Button(app)
loaderButton["text"] = "Select Folder"
loaderButton["command"] = openFileBox
loaderButton.grid()
# Tells the program to run everything above
root.mainloop()
So what needs to happen? The way we see it (and we're beginners looking for feedback here), it should be running the openFileBox method when the button is pressed. When the method runs, it should store a selected directory to directoryPicked and print it to the console just to be sure it's working, but when we press the button it simply says 'tkFileDialog' is not defined.
Any thoughts?
It's because you're only importing askopenfilename, askdirectory from tkFileDialog you're not actually importing tkFileDialog itself
So you need to change directoryPicked = tkFileDialog.askdirectory() to directoryPicked = askdirectory()