Python save as/open - python

hello there
i am making a text editor in Tkinter (python)
and so i made a menu and wanted to know how i can call a function that will display the windows Save-as or open boxes that every program uses.
For example in notepad you can click file-save and then it opens the windows save box.
I already have the menu but how can i open the save box.
Thanks a lot.

Here is an example from http://www.daniweb.com/forums/thread39327.html:
import tkFileDialog
def open_it():
filename = tkFileDialog.askopenfilename()
print filename # test
def save_it():
filename = tkFileDialog.askopenfilename()
print filename # test
def save_as():
filename = tkFileDialog.asksaveasfilename()
print filename # test

Related

Tkinter window not closing despite quit() and destroy()

I'm running Tkinter to get a file path using the function filedialog.askopenfilename(). The program is getting the file path correctly but once I click "Open" on the file I want, the code destroy() does not destroy the GUI window that is open.
I've tried both the destroy() and the quit() functions, though I read that destroy() is preferred. I read that if I do root.destroy(), it is supposed to destroy the GUI that is open. What is happening is that, after the user picks a file, then clicks open, the finder window then becomes totally greyed out and unresponsive. I'm guessing this is the point at which we can execute a destroy, but it's not working for me.
I'm really not sure where I'm going wrong. Would really like to delete the Tkinter browser. My code does continue executing despite the browser being open, but it's unprofessional.
import tkinter
from tkinter import filedialog
import os
root = tkinter.Tk()
root.withdraw() #use to hide tkinter window
def search_for_file_path ():
currdir = os.getcwd()
tempdir = filedialog.askopenfilename(parent=root, initialdir=currdir, title='Please select a directory')
if len(tempdir) > 0:
print ("You chose: %s" % tempdir)
return tempdir
file_path_variable = search_for_file_path()
root = tkinter.Tk()
root.destroy()
print ("\nfile_path_variable = ", file_path_variable)
remove the second instance
import tkinter
from tkinter import filedialog
import os
root = tkinter.Tk()
root.withdraw() #use to hide tkinter window
def search_for_file_path ():
currdir = os.getcwd()
tempdir = filedialog.askopenfilename(parent=root, initialdir=currdir, title='Please select a directory')
if len(tempdir) > 0:
print ("You chose: %s" % tempdir)
return tempdir
file_path_variable = search_for_file_path()
# remove the second instance
root.destroy()
print ("\nfile_path_variable = ", file_path_variable)
If it were me than I would use root.mainloop() and then root.destroy(). There are other ways but I am not sure if they work.
Seem to have fixed the problem! When I execute the script from the terminal, instead of clicking "run" inside the python app, it works. I'm not sure why one works and not the other, but I'll take it.

How to avoid hidden files in file picker using tkinter filedialog.askopenfilename method?

I want to allow the users to select CSV files from the file manager. But it shows all hidden folders too, which is very inappropriate. How can I avoid hidden folders?
def importCSV(self):
self.file = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV files","*.csv"),("all files","*.*")))
After a bit of searching around I managed to find the answer here. I did some slight changes to the linked example so it will run on Python 3. To test it out, simply press ctrl+o after executing.
from tkinter import *
from tkinter import filedialog
root = Tk()
try:
# call a dummy dialog with an impossible option to initialize the file
# dialog without really getting a dialog window; this will throw a
# TclError, so we need a try...except :
try:
root.tk.call('tk_getOpenFile', '-foobarbaz')
except TclError:
pass
# now set the magic variables accordingly
root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')
except:
pass
# a simple callback for testing:
def openfile(event):
fname = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('CSV files', '*.csv'), ('all files', '*.*')))
print(fname)
root.bind('<Control-o>', openfile)
root.mainloop()
The showHiddenVar is used to select if the hidden files will be displayed by default or not. If you don't want to allow the users to toggle between displaying and hiding the hidden files, then simply set showHiddenBtn to '0'.
filedialog.askopenfilename This line just opens a file picker of the Operating System. This is not Python's file picker.
You can disable the option to show hidden files in your operating system and they will disappear in the file picker too.
For windows, This option is available in File Explorer options in the Control Panel.
For Ubuntu, This option is available at filemanager > top menu->View->Show hidden files

Python - How to read a file that was selected from Tkinter?

This is for my assignment.
I was given a template like this... def_choosefile() :
import tkinter
from tkinter import filedialog
root_window = tkinter.Tk()
root_window.withdraw()
return filedialog.askopenfilename()
So if i get this correct, it'll prompt a dialog window, asking to select a file. And when a file is selected, the program is supposed to tell what files did it pick. Using these:
selected_file = choose_file()
print ("Selected file: {}".format (selected_file))
after that, how do i make the program read the files normally? Normally i would use:
infile = open('text')
infile.readline()
import tkinter
from tkinter import filedialog
root_window = tkinter.Tk()
root_window.withdraw()
def choose_file():
return filedialog.askopenfilename()
selected_file = choose_file()
with open (selected_file,'r') as readfile:
lines = readfile.read().splitlines()
for line in lines[0:2]:
print (line)

Python - tkinter and glob.glob working togheter

Im new to tkinter and trying to open the explorer (on windows) so that i can chose what folder i want to use in my program. I found a template for tkinter and altered it to work with my function and how i need the filepath to be. Before i tried using tkinter to "select my folder", i had manually writen the directory in the glob.glob function like this glob.glob(r'C:\Users\Desktop\Spyder\*.log') (and it worked). So my new ide was to replace the pathname input from r'C:\Users\Desktop\Spyder\*.log' to a variabel that stored the same pathname but now it used tkinters askdirectory() to finde the directory inteed.
import glob
import os
from itertools import zip_longest
import tkinter as tk
from tkinter import filedialog
#-------------Connect to Access2013------------------
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_folder = tk.Button(self)
self.select_folder["text"] = "Open WindowsExplorer"
self.select_folder["command"] = self.ask_directory_to_folder
self.select_folder.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def ask_directory_to_folder(self):
clerdatabase() # a funktion that resets the autonumber and deleats all data from every table
print("Open!")
filepath = filedialog.askdirectory()
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
#--------------Scan selected folder for .log files and starts to scan files---------
def find_filenames(right_log_filepath): #finds every file in the chosen filepath
print(right_log_filepath) # r'C:\Users\Desktop\Spyder\*.log'
print("ok")
filenames = [] # list for all the found filenames
for filepath_search in glob.glob(str(right_log_filepath), recursive=True): #A for loop that opens every .log file in the chosen directory folder
print('run')
My problem ist that i don´t get the for loop filepath_search to work (it prints "ok"). But the word run inside the for loop dose not print, i guess it´s because it gets stuck somewhere before that? Someone who has more experience with tkinter that can help me? Thanks
I guess issue caused by what is passed to glob.glob since it doesn't find anything. It seems that it is mostly related to the fact that you add ' characters at the beggining and end of your right_log_filepath.
In ask_directory_to_folder function replace:
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
With:
from os import path # should be at the top of your file
log_filepath = path.join(filepath, "*.log")
find_filenames(log_filepath)

Browse files to open and run using GUI python

Hi i have some python scripts. I need to create a GUI with few buttons, to open those files by browsing. I have to run those scripts just by clicking the GUI button, and should write the output into a n excel sheet. I tried with the below code, but with that i can just read the file! please help?
Thank you
from Tkinter import *
from tkFileDialog
import askopenfilename
def callback():
r = open(askopenfilename(),'r')
a = Button(text='click me', command=callback)
a.pack()
mainloop()
inside the callback() instead of opening the file, execute the file using execfile("abc.py")
def callback():
abc = askopenfilename()
execfile("abc.py")
This code below is a simple example that reads each line from the selected input file and then writes it to a new excel file called output.xls. It use the excellent xlwt library for creating the excel file. You could also chose to create a csv file using the csv module that is part of the python standard library which is also readable by excel. The advantages of using xlwt is that you can apply formating, merge cells, formulas, and so many other features that are part of the xls file format.
import xlwt
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
filename = askopenfilename()
wb = xlwt.Workbook()
ws0 = wb.add_sheet('Sheet1')
with open(filename, 'r') as f:
for i, line in enumerate(f):
ws0.write(i, 0, line.strip())
wb.save('output.xls')
errmsg = 'Error!'
a = Button(text='click me', command=callback)
a.pack()
mainloop()
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname=tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
do something with dirname
print dirname
#This code for file selection:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

Categories

Resources