filedialog, tkinter and opening files - python

I'm working for the first time on coding a Browse button for a program in Python3. I've been searching the internet and this site, and even python standard library.
I have found sample code and very superficial explanations of things, but I haven't been able to find anything that addresses the problem I'm having directly, or a good enough explanation so I can customize code to my needs.
Here is the relevant snippet:
Button(self, text = "Browse", command = self.load_file, width = 10)\
.grid(row = 1, column = 0, sticky = W) .....
def load_file(self):
filename = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
if filename:
try:
self.settings["template"].set(filename)
except:
messagebox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)
return
The method is a hybrid of some code I found along the way with my own customizations. It seems like I finally got it to work (kinda), though its not exactly how I need it.
I get this error when I activate the 'Browse' button: NameError: global name 'filedialog' is not defined.
I've found fairly similar issues along the way but all the solutions suggested I have covered. I went into the 'filedialog' help section of IDLE but didn't glean anything from there either.
Would someone mind providing a break down and a little guidance on this; none of my books address it specifically, and I've checked all the solutions provided to others—I'm lost.

The exception you get is telling you filedialog is not in your namespace.
filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()

I had to specify individual commands first and then use the * to bring all in command.
from tkinter import filedialog
from tkinter import *

Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.
...
def load_file(self):
self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
...

Tkinter is actually a python package, or a folder of python files. Check python source to find it. "tkinter.filedialog" is part of "tkinter.messagebox" Try "from tkinter.messagebox import filedialog" to get filedialog [python 3.7].

Related

Problem with open() function with tkinter in python

I'm doing a python course and I'm learning to use tkinter here, and as part of the course they send me to make a text editor (a notepad), and I'm defining the functions of the menubar, but in the open one at the time of opening a file (obviously txt) gives me this error, could someone please help me, anyway... Thanks in advance.
from tkinter import *
from tkinter import filedialog as FileDialog
from io import open
rute = ""
def new():
global rute
message.set("New File")
rute = ""
text.delete(1.0, "end")
root.tittle(rute + " - MEditor")
def open():
global rute
message.set("Open File")
rute = FileDialog.askopenfilename(
initialdir='.',
filetype=( ("Text Files", "*.txt"), ),
title="Open a text file" )
if rute != "":
file = open(rute,'r')
content = file.read()
text.delete(1.0,'end')
text.insert('insert', content)
file.close()
root.tittle(rute + " - MEditor")
def save():
message.set("Save File")
def save_as():
message.set("Save File As...")
root = Tk()
root.title("MEditor")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New",command=new)
filemenu.add_command(label="Open",command=open)
filemenu.add_command(label="Save",command=save)
filemenu.add_command(label="Save As",command=save_as)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(menu=filemenu, label="File")
text = Text(root)
text.pack(fill='both', expand=1)
text.config(bd=0, padx=6, pady=4, font=("Consolas",12))
message = StringVar()
message.set("Welcome to MEditor!")
monitor = Label(root, textvar=message, justify='left')
monitor.pack(side='left')
root.config(menu=menubar)
root.mainloop()
throws me this error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\anaconda3\envs\spyder-cf\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\luisc\Desktop\CursoPython\Fase 4 - Temas avanzados\Tema 13 - Interfaces graficas con tkinter\editor.py", line 24, in open
file = open(rute,'r')
TypeError: open() takes 0 positional arguments but 2 were given
It should be said that I used anaconda for the jupyter notebook but to write scripts I am now using VSCode.
You named your own function open, shadowing the definition of the built-in open with a global scope definition (global scope names are always found before built-in names, you only find the latter if the former doesn't exist). Don't name-shadow built-ins, it only leads to pain.
Change:
def open():
to some other name and change all the places that call it to match.
A list of the built-ins can be found in the docs here:
https://docs.python.org/3/library/functions.html

How to get a user-selected file and feed it to a python program in Tkinter

I am currently messing about with Tkinter creating an interface for a project I created. The program takes in a bunch of file paths as inputs for it to run. I'm trying to create a tkinter interface where I can upload the 4 files I need or at least somehow get the filepaths and the. feed those to the program. Here is what I have:
import sys
import os
import comparatorclass
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
root=Tk()
root.geometry('1000x1000')
def open_file():
file = askopenfile(mode ='r', filetypes =[('Python Files', '*.py')])
if file is not None:
content = file.read()
print(content)
def run_comparator():
comparatorclass.main()
button2 = Button(root, text ='Open', command = lambda:open_file())
button2.pack(side = TOP, pady = 10)
button1 = Button(root,text="hello",command= run_comparator)
button1.pack()
root.mainloop()
as you can see, I have two buttons. The issue I'm having is how to connect my openfile function to my run_comparator function such that the 4 files I need to open are passed on to the run_comparator

Pygame image.save: Is it possible to have the user choose save location? [duplicate]

I'm working for the first time on coding a Browse button for a program in Python3. I've been searching the internet and this site, and even python standard library.
I have found sample code and very superficial explanations of things, but I haven't been able to find anything that addresses the problem I'm having directly, or a good enough explanation so I can customize code to my needs.
Here is the relevant snippet:
Button(self, text = "Browse", command = self.load_file, width = 10)\
.grid(row = 1, column = 0, sticky = W) .....
def load_file(self):
filename = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
if filename:
try:
self.settings["template"].set(filename)
except:
messagebox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)
return
The method is a hybrid of some code I found along the way with my own customizations. It seems like I finally got it to work (kinda), though its not exactly how I need it.
I get this error when I activate the 'Browse' button: NameError: global name 'filedialog' is not defined.
I've found fairly similar issues along the way but all the solutions suggested I have covered. I went into the 'filedialog' help section of IDLE but didn't glean anything from there either.
Would someone mind providing a break down and a little guidance on this; none of my books address it specifically, and I've checked all the solutions provided to others—I'm lost.
The exception you get is telling you filedialog is not in your namespace.
filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
I had to specify individual commands first and then use the * to bring all in command.
from tkinter import filedialog
from tkinter import *
Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.
...
def load_file(self):
self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
...
Tkinter is actually a python package, or a folder of python files. Check python source to find it. "tkinter.filedialog" is part of "tkinter.messagebox" Try "from tkinter.messagebox import filedialog" to get filedialog [python 3.7].

Create directory in a selected path using Python Tkinter 2.7

I would like to create a class in Tkinter Python 2.7 that creates a new directory using the name introduced by the user in a field after the directory location was chosen from filedialog.
As an example I would like something like this:
User introduces the name of the directory and the following structure should be created:
$HOME\a\<name_introduced_by_the_user_in_the_field>\b
$HOME\a\<name_introduced_by_the_user_in_the_field>\c
I was thinking to start simple and create a simple directory, but I am getting an error.
Here is what I have tried:
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self,text="Insert the name of your project",font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
self.projectnamevar=tk.StringVar()
projectname=tk.Entry(self,textvariable=projectnamevar)
projectname.pack()
button1 = tk.Button(self, text="Create the directory", command=self.create_dir)
button1.pack()
def create_dir(self):
call(["mkdir",projectnamevar.get()])
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
return self.func(*args)
File "program.py", line 118, in create_dir
call(["mkdir",self.projectnamevar.get()])
AttributeError: PageThree instance has no attribute 'projectnamevar'
How can I accomplish the whole stuff?
P.S. I am quite new to programming
Your Variable projectnamevar cannot be found in the class as you have not saved it as such, try it with
self.projectnamevar = tk.StringVar()
Also, you might want to use the os module instead of calling it on the system, you can use it like this
import os
path = "~/my/path/"
os.mkdir(path)
import os, sys
if sys.version_info[0] == 3:
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import *
elif sys.version_info[0] == 2:
print ("The Script is written for Python 3.6.4 might give issues with python 2.7, let the author know")
print ("Note Python 2.7 CSV has a empty line between each result. couldn't find a fix for that")
from Tkinter import *
import tkMessageBox as messagebox
import tkFileDialog as filedialog
from ttk import Combobox
class temp:
def __init__(self):
self.top = Tk()
self.lab = Label(self.top, text='UserFiled')
self.en = Entry(self.top, width =25)
self.but = Button(self.top, text='Submit',command = self.chooseFolder)
self.lab.grid(row=0, column=0)
self.en.grid(row=0, column=1)
self.but.grid(row=0, column=2)
self.top.mainloop()
def chooseFolder(self):
directory = filedialog.askdirectory()
print(directory)
newPath = os.path.join(directory, self.en.get())
if not os.path.exists(newPath):
os.chdir(directory)
os.mkdir(self.en.get())
obj = temp()

askopenfilenames selecting multiple files

Using python 3.3 on a unix platform. I have seen many examples where the following code works but I am having an issue. When I select multiple files, I get an error message dialog box: "File /python/input_files/file1.txt file2.txt" does not exist. The error makes sense (tries to open a string of multiple files) but don't understand why others don't see it and how do I correct it. selectFiles is called via a button select. Appreciate any help.
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilenames
def selectFiles(self):
files = askopenfilenames(filetypes=(('Text files', '*.txt'),
('All files', '*.*')),
title='Select Input File'
)
fileList = root.tk.splitlist(files)
print('Files = ', fileList)
Here is the complete code:
#!/usr/local/bin/python3.3
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilenames
class multifilesApp(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
def initializeUI(self):
self.master.title('Select Files Application')
self.grid(row=0, column=0,sticky=W)
# Create the button to select files
self.button1 = Button(self.master, text='Select Files', command=self.selectFiles, width=10)
self.button1.grid(row=30, column=0)
def selectFiles(self):
files = askopenfilenames(filetypes=(('Text files', '*.txt'),
('All files', '*.*')),
title='Select Input File'
)
InputFileList = root.tk.splitlist(files)
print('Files = ', InputFileList)
# Begin Main
if __name__ == "__main__":
root = Tk()
root.minsize(width=250, height=400)
root.geometry("1200x800")
# Call the parser GUI application
app = multifilesApp(master=root)
app.initializeUI()
app.mainloop()
Maybe there is problem with Tcl/Tk on Sun4u
Try to run example in Tcl/Tk (example.tcl)
package require Tk
set filename [tk_getOpenFile -multiple true]
puts $filename
Run (probably):
tclsh example.tcl

Categories

Resources