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()
Related
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.)
I have a csv file Cars.csv. It contains a list of cars: Ferrari, Lamborghini, Mercedes...
With my script if I change Ferrari with AlfaRomeo in csv, combobox doesn't update in the opened tkinter app.
My question is how I can create a function to read csv values in combobox in real time.
import csv
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("1250x750")
root.resizable(False, False)
with open('Cars.csv') as csv_file:
csv_reader = csv.reader(csv_file)
list_cars = list(csv_reader)
def car_changed(event):
global car_selected
car_selected = car_cb.get()
selected_car = tk.StringVar()
car_cb = ttk.Combobox(root, textvariable=selected_car, width=15, font=("Bold",15))
car_cb['values'] = list_cars
car_cb['state'] = 'readonly' # normal
car_cb.place(x=185,y=90)
car_cb.bind('<<ComboboxSelected>>', car_changed)
root.mainloop()
File watcher
You can use a library like watchdog to get notified when the file changes.
Polling
You can have a loop running forever. In this loop, you read the file and look for changes. If there was a change you update your gui.
This loop must run in a separate thread and you should add a sleep after each iteration.
An improvement may be to only read the last edit date and check if it updated.
Note: In both cases you need to save the file before it is updated.
Manual
Not automatic but the simplest option ist to add an button, that reloads the data.
Other solution
I don't know your application, but you may want to use other options than editing a csv file.
Notes
All these options only work, after the file is saved.
To make it really real time you would need an editor integration.
I'm running into this problem where whenever I import a file into my Listbox it makes the name of the item in the listbox C:\blahblah\blahblah\test.txt
which is annoying since I only want the "test" or test.txt" to be shown in the listbox but still not disturb the file directory, Is This Possible?
I'm using from tkinter import * btw
there isnt much ive tried since as soon as i change the name of the file, the file directory follows with it.
example :
window = Tk()
list = []
listbox = ListBox(window)
listbox.pack()
filedirectory = os.listdir("blahblah/")
for f in filedirectory:
listbox.inset("end", f"blahblah/{f}") #where it says blahblah is an example of where you could "potentially" change the name but that changes the file directory with it
window.mainloop()
The answer credit goes to Henry's comment but I have added what you are asking for in comment.
How to get rid of extensions?
Here's the complete solution:
from tkinter import *
import os.path
window = Tk()
listbox = Listbox(window)
listbox.pack()
filedirectory = os.listdir("<path>")
for f in filedirectory:
listbox.insert("end", f"{os.path.basename(f).split('.')[0]}")
window.mainloop()
There were some typos in your question, I have fixed those as well. First is ListBox which should be Listbox and second is insert not inset .
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.
I'm new to programming & new to python. I've just developed my first script, it prosesses file, but at the moment only from the commandline.
This is just a hobby to me so my job does not depend on it :-)
I've spent a few days now trying to get my head around python gui development & have come to the conclusion that I must be stupid.
I've looked at wxpython & Tkinter & do not understand either, although Tkinter seems to be the easier out of the two. I've even looked at wysiwyg tools like Boa Contrictor & wxglade. I do not even understand how to use those. I would prefer to just stick with my editor & code manually anyway.
My problem is this:
I would like to create a desktop window with either 1 or two objects, depending on what works best. If just one object then a text box of some sort, if 2 objects then a text box & an image.
I want to be able to drag file from a file manager & drop them on my script window, this is just to pass the filenames to my script.
I than want to redirect stdout to an object within my desktop window so that all script output appears within the desktop window.
I'm not sure if one object can do both things or not. If it can than just a text box would suffice, else drop files onto image & have redirected output going to the text box.
I have found drag & drop examples on the web but nothing which incorporates stdout redirect, & I've not been able to successfully modify any of the examples that I've come across.
If somee kind sole has the time to demonstrate how to achieve what I want & explain how its works I would greatfully appreciate it!
----EDIT ----
I've been playing around with 2 examples & have managed to hash the 2 together in order to get what I wanted working. Code is below. It's not cleaned up yet ( old comments etc... ), but it works.
#!/usr/bin/python
# The next two lines are not necessary if you installed TkDnd
# in a proper place.
import os
from Tkinter import *
os.environ['TKDND_LIBRARY'] = '/home/clinton/Python/tkdnd2.6/'
import Tkinter
from untested_tkdnd_wrapper import TkDND
class Redir(object):
# This is what we're using for the redirect, it needs a text box
def __init__(self, textbox):
self.textbox = textbox
self.textbox.config(state=NORMAL)
self.fileno = sys.stdout.fileno
def write(self, message):
# When you set this up as redirect it needs a write method as the
# stdin/out will be looking to write to somewhere!
self.textbox.insert(END, str(message))
root = Tkinter.Tk()
dnd = TkDND(root)
textbox = Tkinter.Text()
textbox.pack()
def handle(event):
event.widget.insert(END, event.data)
content = textbox.get("0.0",Tkinter.END)
filename = content.split()
dnd.bindtarget(textbox, handle, 'text/uri-list')
#Set up the redirect
stdre = Redir(textbox)
# Redirect stdout, stdout is where the standard messages are ouput
sys.stdout = stdre
# Redirect stderr, stderr is where the errors are printed too!
sys.stderr = stdre
# Print hello so we can see the redirect is working!
print "hello"
# Start the application mainloop
root.mainloop()
Examples are: python drag and drop explorer files to tkinter entry widget
And also the example provided kindly by Noelkd.
In order for this code to work you must create the wrapper from first example. Also currently code just displays dragged file in window, however variable is in place to be passed onto the script which runs behind the gui interface.
If you want to use Tkinter:
from Tkinter import *
import tkFileDialog
class Redir(object):
# This is what we're using for the redirect, it needs a text box
def __init__(self, textbox):
self.textbox = textbox
self.textbox.config(state=NORMAL)
self.fileno = sys.stdout.fileno
def write(self, message):
# When you set this up as redirect it needs a write method as the
# stdin/out will be looking to write to somewhere!
self.textbox.insert(END, str(message))
def askopenfilename():
""" Prints the selected files name """
# get filename, this is the bit that opens up the dialog box this will
# return a string of the file name you have clicked on.
filename = tkFileDialog.askopenfilename()
if filename:
# Will print the file name to the text box
print filename
if __name__ == '__main__':
# Make the root window
root = Tk()
# Make a button to get the file name
# The method the button executes is the askopenfilename from above
# You don't use askopenfilename() because you only want to bind the button
# to the function, then the button calls the function.
button = Button(root, text='GetFileName', command=askopenfilename)
# this puts the button at the top in the middle
button.grid(row=1, column=1)
# Make a scroll bar so we can follow the text if it goes off a single box
scrollbar = Scrollbar(root, orient=VERTICAL)
# This puts the scrollbar on the right handside
scrollbar.grid(row=2, column=3, sticky=N+S+E)
# Make a text box to hold the text
textbox = Text(root,font=("Helvetica",8),state=DISABLED, yscrollcommand=scrollbar.set, wrap=WORD)
# This puts the text box on the left hand side
textbox.grid(row=2, column=0, columnspan=3, sticky=N+S+W+E)
# Configure the scroll bar to stroll with the text box!
scrollbar.config(command=textbox.yview)
#Set up the redirect
stdre = Redir(textbox)
# Redirect stdout, stdout is where the standard messages are ouput
sys.stdout = stdre
# Redirect stderr, stderr is where the errors are printed too!
sys.stderr = stdre
# Print hello so we can see the redirect is working!
print "hello"
# Start the application mainloop
root.mainloop()
What this does is creates a window with a button and a text box, with stdout redirect.
Currently in Tkinter you can't drag and drop files on to the open tk window(you can if you use tkdnd), so I have included a different way of getting the path of a file.
The way I have included to select a file is the askopenfilename dialog from tkFileDialog, this opens up a file browser and the path file selected is returned as a string.
If you have any questions or this doesn't quite do what your looking for please leave a comment!
Have a look at GTK. It is a really powerful library. Not the simplest, that's a fact, but once you get to understand how things work, it becomes much easier.
Here's the official tutorial
If oyu are still using Python2, I think you should use PyGTK but it has been replaced by gl (which is described in the above tutorial). A good tutorial for PyGTK can be found here.
For a static interface, you can use glade which produces XML files that are then read by GTKBuilder to create the "real" interface. The first tutorial that I've found is available here