Simplest way to open a file in tkinter - python

trying to make a GUI with an 'open file' button. When I run the code shown below, the open file dialog opens straight away, and not when I press the button. Why? Is there a simple way to fix this that doesn't involve using classes? (I don't currently know anything about classes and am working on a time-pressured project)
from tkinter import *
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text = "Open", command = openfile())
button.grid(column = 1, row = 1)
interface.mainloop()

The code is passing the return value of the openfile function call, not the function itself. Pass the function itself by removing trailing () which cause a call.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
interface = Tk()
def openfile():
return filedialog.askopenfilename()
button = ttk.Button(interface, text="Open", command=openfile) # <------
button.grid(column=1, row=1)
interface.mainloop()

Related

Get the file path in global variable from browse button with tkinter

I'm using tkinter. And I am trying to get a file path from a button and use it as an input for an other function. I defined filepathforinfo as a global variable, but I am not getting the expected result.
I tried to follow the solution here.
Here is the main part of the code:
import tkinter.filedialog
import tkinter as tk
def get_pdf_file():
global filepathforinfo #can be avoided by using classes
filetypes=[('PDF files', '*.pdf')]
filepathforinfo = tk.filedialog.askopenfilename( title='Open a file',initialdir='/', filetypes=filetypes)
filepathforinfo='test'
# Toplevel object which will
# be treated as a new window
Information_Window = tk.Tk()
Information_Window.title("Information extraction")
Information_Window.resizable(True, True)
Information_Window['background']='#8c52ff'
info_button = tk.Button(Information_Window, text="Give the pdf file to extract information from", activebackground='purple',activeforeground='purple' ,command=get_pdf_file)
info_button.grid(row=0,column=0)
print(filepathforinfo)
#get_pdf_info(filepathforinfo)
Information_Window.mainloop()
After clicking the button and choosing the file, I get as an output only this :
Out[1]: 'test'
I dont know why I dont get the file path.
The closest answer I got is here, but it is still not satisfying.
The problem is your printing filepathforinfo before its even changed. I created a label to show it as it actually works.
import tkinter.filedialog
import tkinter as tk
def get_pdf_file():
global filepathforinfo
filetypes=[('PDF files', '*.pdf')]
filepathforinfo = tk.filedialog.askopenfilename( title='Open a file',initialdir='/', filetypes=filetypes)
info_label['text'] = filepathforinfo
filepathforinfo='test'
# Toplevel object which will
# be treated as a new window
Information_Window = tk.Tk()
Information_Window.title("Information extraction")
Information_Window.resizable(True, True)
Information_Window['background']='#8c52ff'
info_button = tk.Button(Information_Window, text="Give the pdf file to extract information from", activebackground='purple',activeforeground='purple' ,command=get_pdf_file)
info_button.grid(row=0,column=0)
info_label = tk.Label(Information_Window, text= filepathforinfo)
info_label.grid()
Information_Window.mainloop()

Getting file directory from tkinter function

I am running a simple python script that opens a window with a button inside of it. When the user clicks the button a dialog box opens and asks the user to select a file directory. I want to pull that directory location out of the function. This is what the code looks like:
from tkinter import *
from tkinter import filedialog
def openFile():
filePath= filedialog.askdirectory()
return filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
I would like the file directory to be saved in a variable inside the window. I am able to print the filepath inside the function but I am unable to bring it out of the function.
Any help will be greatly appreciated
You cannot use the return value for functions added to buttons, as there is no way of picking up whatever is returned.
So instead you can write the return to a global variable, or a class variable, instead. Example with global variable below;
from tkinter import *
from tkinter import filedialog
my_path = None
def openFile():
global my_path
filePath = filedialog.askdirectory()
my_path = filePath
window = Tk()
button = Button(text="open", command=openFile)
button.pack()
window.mainloop()
You will then be able to pick up the my_path variable later in your script after clicking the button.

Open a specific file from a tkinter window

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()

Tkinter Browse Button Self Deleting

I am trying to create a browse button in tkinter. I have created the open folder dialog box but when i set it to the button it will exit out of the window.
My ultimate goal is to:
1) click on the button and bring up the file dialogue box
2) select a file
3) insert the file name into an Entry Widget for later use
I should note that I am using multiple window frames for the code that follows is summed up.
import os
import sys
import Tkinter as tk
from tkFileDialog import askopenfilename
def openFile(entryWidgetName):
tk.Tk().withdraw()
filename = askopenfilename()
entryWidgetName.delete(0,tk.END)
entryWidgetName.insert(0,filename)
return
class Welcome():
def __init__(self,master):
self.buttonNewTemplate = tk.Button(self.master, text = 'Create a New Template', command = self.gotoNewTemplate).place(x=100, y=250)
def gotoNewTemplate(self):
root2 = tk.Toplevel(self.master)
newTemplate = NewTemplate(root2)
class NewTemplate():
def __init__(self, master):
#Entry Windows
self.uploadFile = tk.Entry(self.sectionFrame2, width = 80).grid(row=4, column = 1, sticky = 'w')
#Buttons
self.buttonBrowse=tk.Button(self.sectionFrame2, text='Browse', fg='blue', command=lambda:openFile(uploadFile)).grid(row=4, column = 0, padx = 10, sticky = 'w')
Every time I click the browse button the second window destroys itself bringing me back to the main page.
Does anyone have any suggestions?
A tkinter application can only have a single instance of Tk. You are creating at least two: one explicitly in openFile, and one from somewhere else in your code either implicitly or explicitly.
Since the only way to call openFile is from a button click, and the only way to have a button click is to have a button, and the only way to have a button is to already have a root window, you need to remove the statement tk.Tk().withdraw() since that is creating a new root window.
There may be other problems in your code, but it's impossible to know based on the incomplete code in the question.

Problems using Tkinter askopenfile

I want to launch an "Open File" dialog in Tkinter in Python 2.7.
My code starts with:
from Tkinter import Frame, Tk, BOTH, Text, Menu, END
import tkFileDialog as tkfd
import fileinput
root = Tk()
global strTab
strTab = ""
def openTab(event):
r = tkfd.askopenfilename()
strTab = unicodedata.normalize('NFKD', r).encode('ascii','ignore')
Later in the code I have:
btnLoadTab = Button(root,
text="Load Tab",
width=30,height=5,
bg="white",fg="black")
btnLoadTab.bind("<Button-1>", openTab)
btnLoadTab.pack()
root.mainloop()
When I press the button an "Open File" dialog is shown, but when I select a file it closes and the button remains "clicked".
If I later call to strTab outside of openTab, it remains equal to "".
You can find workable example here: http://www.python-course.eu/tkinter_dialogs.php

Categories