Browsing file and getting filepath in entrybox in Tkinter - python

I am trying to make a simple GUI using Tkinter in python2, in which I need to make an entry box and a button besides that. The button browses the file and shows the filepath in the entrybox. How can I do that.
I used the tkFileDialog.askopenfilename that allows to browse the path but how can I make the gui to show that path in an entry box.
I tried it as follows:
import tkinter as tk
import tkFileDialog
root=tk.Tk()
def browsefunc():
filename =tkFileDialog.askopenfilename(filetypes=(("tiff files","*.tiff"),("All files","*.*")))
ent1=tk.Entry(frame,font=40)
ent1.grid(row=2,column=2)
b1=tk.Button(frame,text="DEM",font=40,command=browsefunc)
b1.grid(row=2,column=4)
root.mainloop()
Attached a screenshot of what I needs.

Are you really sure, that you are using python2? Because you wrote tkinter with a lowercase t and not with an uppercase T or did you just write it wrong?.
Anyway, you can easily insert a little text (in your case a path) into your Entry-widget by using the insert method of the Entry-widget. In your case it would be:
import Tkinter as tk
import tkFileDialog
root=tk.Tk()
ent1=tk.Entry(root,font=40)
ent1.grid(row=2,column=2)
def browsefunc():
filename =tkFileDialog.askopenfilename(filetypes=(("tiff files","*.tiff"),("All files","*.*")))
ent1.insert(tk.END, filename) # add this
b1=tk.Button(root,text="DEM",font=40,command=browsefunc)
b1.grid(row=2,column=4)
root.mainloop()
The tk.END parameter gives the last index of the entry-string back.
If you already wrote something into the Entry-Widget like that:
This is my path:
and you add your path, than it will looks like that:
This is my path:/usr/bin/...
As you can see it adds the string in the end of the "entry-string".
The other option would be 0 for the index than your path will be in the beginning of the entry-widget:
/usr/bin...HI
I'm sorry if my english is horrible! Feel free to edit it!

May be try this code it might work
from tkinter import *
from tkinter.filedialog import askopenfilename
root=Tk()
ent1=Entry(root,font=40)
ent1.grid(row=2,column=2)
def browsefunc():
filename = askopenfilename(filetypes=(("jpg file", "*.jpg"), ("png file
",'*.png'), ("All files", "*.*"),))
ent1.insert(END, filename) # add this
b1=Button(root,text="DEM",font=40,command=browsefunc)
b1.grid(row=2,column=4)
root.mainloop()

Related

Assigning tkinter filedialog value to a different variable

I wish to save the filepath we get from filedialog() in a variable outside the defined function openfile().
Below is the code snippet I am using:
import tkinter as tk
from tkinter import filedialog, Button
root = tk.Tk()
def openfile():
path = filedialog.askopenfilename()
return path
Button(root, text = "click to open the stock file", command=openfile).pack(pady=20)
file_path = openfile() # this seems to be causing the issue
The problem is that the filedialog() is getting executed without even getting clicked on.
You're correct about the cause of the filedialog getting executed. Callback functions like openfile() can't return values because it's tkinter that calls them (and it ignores whatever they return). GUI programs require a different programming paradigm than you're probably used to utilized — they're event-driven. This means that they (mostly) only do things as a result of processing user input. For that reason you will need to save the result of calling the askopenfilename() function in a global variable for use later if the value isn't going to be used immediately.
tkinter provides several different kinds of variable classes — BooleanVar, DoubleVar, IntVar, and StringVar — that are good for this sort of thing. In the code below, I show how to use a StringVar to store the path.
The next step will be adding code that does something with the value getting stored in file_path. One possibility would be to add another GUI element, like a Button, that calls another function that does something with the value.
import tkinter as tk
from tkinter import filedialog, Button
root = tk.Tk()
file_path = tk.StringVar()
def openfile():
path = filedialog.askopenfilename()
file_path.set(path) # Save value returned.
Button(root, text="click to open the stock file", command=openfile).pack(pady=20)
root.mainloop()
Here’s what you can do:
def open_file():
global path
path = filedialog.askopenfilename()
And then you can access the path variable wherever you want in the program(after the function is ran, obviously.)

root = tkinter.Tk() or root = Tk()?

I have two scripts that both work:
import tkinter
root = tkinter.Tk()
root.configure(bg='blue')
root.mainloop()
and
from tkinter import *
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello world!")
text.pack()
root.mainloop()
I want to combine the two scripts to print the text on a blue background, but moving anything from one script to another seems to break it.
I can't figure out if it's about root = tkinter.Tk() vs root = Tk(), or import tkinter vs from tkinter import *, or something entirely different. I can't find a successful combination.
I'm using Ubuntu and Python 3.6.9.
Because you use two different styles when importing tkinter, you will need to modify the code from one file when moving to the other. The code in your first example is the preferred way to do it because PEP8 discourages wildcard imports.
When when you copy the code from the second example, you'll need to add tkinter. to every tkinter command (tkinter.Tk(), tkinter.Text(root), tk.INSERT, etc.
Personally I find import tkinter as tk to be a slight improvement. I find tk.Tk() to be a little easier to type and read than tkinter.Tk().
You should know that:
from tkinter import *
will import all the attribute in the tkinter.But if you also define some variable in your script.It will be covered by your new variable.So we don't recommend you to use that.(If you used both from tkinter.ttk import * and from tkinter import *.Some default widgets of tkinter will be covered by ttk widgets.)
Just like Mr.Bryan said,I'd like to use import tkinter as tk,too.

Tkinter button open another window that i don't want

as I say in the title, when I click on a button (analyse) another windows open and I don't want it. The problems is, in the analyse function, the first line is an import of my tkinter file.
Thanks in advance for any help.
I tried to delete the import and the second windows does not pop up, so I am pretty sure it is the problem. Moreover I need to do this import in the analyse function because I already import the other module in my tkinter file
tkinter file :
import fileb
def analyser():
output=fileb.analyse(name)
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
fileb :
def analyse(name):
import tkinter_essais
When you import your Tkinter file, you are running that file. This means that the code is run twice and so you have two windows opened up. A way to bypass this is by putting your tkinter setup into a function, and having that run if it is the main program only using something like this:
import fileb
def analyser():
output=fileb.analyse(name)
def tkSetup():
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
if "__name__" == "__main__":
tkSetup()
The if name == main checks if the program is being run originally (best way I can think to describe it) and so it wont be run if you import the file.

tkinter askdirectory syntax

I have a question about the askdirectory() in tkinter. Is it posible to use that function and also se what´s inside the folder that i want to select the directory from?
Because now when i use the function i can open the explorer and get the directory path to the folder i need but i can´t se what the folder contains (I just now that now before hand for now)... With the askdirectory function the folder says "No items match your search.". So i came up with this:
filepath_ask = filedialog.askdirectory(
initialdir=os.path.dirname(filedialog.askopenfilename(title ="Pick a folder in directory with .log files")),
title = "Press 'Select Folder'")
But it´s not that "user friendly". First it opens a window with askopenfilename so that i can see the content in the folder, then it closes when i select a file and opens a new window with askdirectory to "Select Folder" that has the content/file i chose in the window before. There must be a better way? I have been reding upp on the dokumentatin but can´t find anything that works. Help would be appreciated! Thanks
If you think that it isn't as much of a bother to have the user select a file in the askopenfilename dialog, then why not just run with that (and skip askdirectory altogether):
import tkinter as tk
from tkinter import filedialog
import pathlib
root = tk.Tk()
ask = filedialog.askopenfilename(title="Select a directory", filetypes = [("log",".log"),("All Files",".*")])
print(f"User selected Directory: {pathlib.Path(ask).resolve().parent}")
root.destroy()

Create a simple app in tkinter for displaying map

I am new to Tkinter,
I have a program which takes CSV as input containing, outlet's geo-location,
display it on a map, saving it as HTML.
format of my csv:
outlet_code Latitude Longitude
100 22.564 42.48
200 23.465 41.65
... and so on ...
Below is my python code to take this CSV and put it on a map.
import pandas as pd
import folium
map_osm = folium.Map(location=[23.5747,58.1832],tiles='https://korona.geog.uni-heidelberg.de/tiles/roads/x={x}&y={y}&z={z}',attr= 'Imagery from GIScience Research Group # University of Heidelberg — Map data © OpenStreetMap')
df = pd.read_excel("path/to/file.csv")
for index, row in df.iterrows():
folium.Marker(location=[row['Latitude'], row['Longitude']], popup=str(row['outlet_code']),icon=folium.Icon(color='red',icon='location', prefix='ion-ios')).add_to(map_osm)
map_osm
This will take display map_osm
Alternate way is to save map_osm as HTML
map_osm.save('path/map_1.html')
What I am looking for is a GUI which will do the same thing.
i.e prompt user to input the CSV, then execute my code below and display result
or at least save it in a location.
Any leads will be helpful
You question would be better received if you had provided any code you attempted to write for the GUI portion of your question. I know (as well as everyone else who posted on your comments) that tkinter is well documented and has countless tutorial sites and YouTube videos.
However if you have tried to write code using tkinter and just don't understand what is going on, I have written a small basic example of how to write up a GUI that will open a file and print out each line to the console.
This won't right out answer your question but will point you in the right direction.
This is a non-OOP version that judging by your existing code you might better understand.
# importing tkinter as tk to prevent any overlap with built in methods.
import tkinter as tk
# filedialog is used in this case to save the file path selected by the user.
from tkinter import filedialog
root = tk.Tk()
file_path = ""
def open_and_prep():
# global is needed to interact with variables in the global name space
global file_path
# askopefilename is used to retrieve the file path and file name.
file_path = filedialog.askopenfilename()
def process_open_file():
global file_path
# do what you want with the file here.
if file_path != "":
# opens file from file path and prints each line.
with open(file_path,"r") as testr:
for line in testr:
print (line)
# create Button that link to methods used to get file path.
tk.Button(root, text="Open file", command=open_and_prep).pack()
# create Button that link to methods used to process said file.
tk.Button(root, text="Print Content", command=process_open_file).pack()
root.mainloop()
With this example you should be able to figure out how to open your file and process it within a tkinter GUI.
For a more OOP option:
import tkinter as tk
from tkinter import filedialog
# this class is an instance of a Frame. It is not required to do it this way.
# this is just my preferred method.
class ReadFile(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
# we need to make sure that this instance of tk.Frame is visible.
self.pack()
# create Button that link to methods used to get file path.
tk.Button(self, text="Open file", command=self.open_and_prep).pack()
# create Button that link to methods used to process said file.
tk.Button(self, text="Print Content", command=self.process_open_file).pack()
def open_and_prep(self):
# askopefilename is used to retrieve the file path and file name.
self.file_path = filedialog.askopenfilename()
def process_open_file(self):
# do what you want with the file here.
if self.file_path != "":
# opens file from file path and prints each line.
with open(self.file_path,"r") as testr:
for line in testr:
print (line)
if __name__ == "__main__":
# tkinter requires one use of Tk() to start GUI
root = tk.Tk()
TestApp = ReadFile()
# tkinter requires one use of mainloop() to manage the loop and updates of the GUI
root.mainloop()

Categories