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)
Related
im trying to make only the file name show up using filedialog
here's the example :
import tkinter as tk
import pygame
from tkinter import filedialog
root = tk.Tk()
controls_frame = tk.Frame(root)
controls_frame.pack()
def add_name():
name = filedialog.askopenfile()
names.insert(filedialog.END,name)
names = tk.Listbox(root,bg="black",fg="red",width=60,height=6)
names.pack(pady=0,side='bottom')
add_name_btn = tk.Button(controls_frame , text='add name' , command=add_name)
add_name_btn.grid(column=3,row=0,padx=20)
root.mainloop()
it shows the full directory to the file, which i dont want.
how do i remove the directory that it shows on box?
The module os can help with this:
import os
def add_name():
name = os.path.basename(str(filedialog.askopenfile()))
name = name.replace("' mode='r' encoding='UTF-8'>", "")
names.insert(filedialog.END,name)
You can do it like this.
I found this solution on another post.
import tkinter
from tkinter import filedialog
def filename123():
global filename1, nopath1
filename1 = filedialog.askopenfilename()
nopath1 = filename1.split("/")[len(filename1.split("/"))-1]
filename123()
I am looking to create a reminder that prompts the user to select a file if they've completed it. After selecting the file they want, I would like the script to save that file to a specific folder. This is what I have so far...
import tkinter
import time
import win32api
from tkinter import messagebox
dialog_title = 'Complaince calendar'
dialog_text = 'Have you completed the monthly spreadsheet?'
answer = messagebox.askquestion(dialog_title, dialog_text)
if answer == 'yes':
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
else: # 'no'
win32api.MessageBox(0, 'Make sure you get that done', 'Compliance calendar')
How can I save the file_path to a specified folder?
Thanks!!
I want to show a message box, but without the parent window behind it in Python. This is my code:
import Tkinter, tkFileDialog ,tkMessageBox
from fileManagerModule import fileManager
def load():
global myFile,flag,msg
flag=True
options = {}
options["title"] = "choose a text File"
options['initialdir'] = '~/'
fileName = tkFileDialog.askopenfilename(**options)
myFile = fileManager(fileName)
myText.delete("1.0", Tkinter.END)
try:
line = myFile.readFromFile()
myText.insert("1.0", line)
except:
msg=Tkinter.Tk()
msg=tkMessageBox.showerror("Error","please choose file to load")
screenshot
You can use the withdraw() function to remove the window being displayed in the background to just show the dialog box only.
try this:
import Tkinter, tkFileDialog ,tkMessageBox
from fileManagerModule import fileManager
def load():
global myFile,flag,msg
flag=True
options = {}
options["title"] = "choose a text File"
options['initialdir'] = '~/'
fileName = tkFileDialog.askopenfilename(**options)
myFile = fileManager(fileName)
myText.delete("1.0", Tkinter.END)
try:
line = myFile.readFromFile()
myText.insert("1.0", line)
except:
msg=Tkinter.Tk()
msg.withdraw()
msg=tkMessageBox.showerror("Error","please choose file to load")
Add the following to your code:
import Tkinter,tkMessageBox
.
.
at program initialisation add a global variable
msgWindow = None
at your code initialisation add the following lines:
.. before the very first call to tkMessageBox
def initialise():
global msgWindow
.
.
msgWindow = Tkinter.Tk()
msgWindow.withdraw()
in your code where you call tkMessageBox, just call
tkMessageBox the way you normally call it.
if not tkMessageBox.askyesno('What to do','Continue ?'):
.....
at any exit point where your program terminates, add
msgWindow.destroy()
That will do.
I'm trying to simply get a file name from the user by tkinter.filedialog.askopenfilename(). The function returns fine and the code below displays the file name okay but the dialog window doesn't close immediately after hitting 'open' or 'cancel', it freezes. I'm using python 3.3.3 or OSX 10.9.1 and tcl/tK 8.5.9.
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
top = Tk()
top.withdraw()
file_name = filedialog.askopenfilename()
print (file_name)
Adding root.update() after filedialog.askopenfilename() gets the open file dialog to close after the file is chosen.
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
root.update()
Refer to: Tkinter askopenfilename() won't close
A work around that I used for this is to "withdraw" the tkinter window AFTER selecting the file from file explorer. Here is the code snippet I used -
import tkinter
from tkinter import filedialog
def selectCustomerFileTK():
root = tkinter.Tk()
root.wm_attributes('-topmost', 1)
filename = filedialog.askopenfilename()
root.withdraw()
return filename
getfile = selectCustomerFileTK()
It opens a tkinter window while you are selecting the file, but the moment you select the file and press "Open", the tkinter window and file explorer both close because of the "root.withdraw()" command after.
You don't need to specify module name in
file_name = filedialog.askopenfilename()
Try
file_name = askopenfilename()
instead
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)