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.
Related
the problem i am trying to solve is when the user starts the program , a file explorer opens. if the user exist the window i want to ask the user if they want to quit the program y or n.
from tkinter.filedialog import askdirectory
import pyinputplus as py
def get_location_path():
while True:
path = askdirectory(title='Select Folder') # shows dialog box and return the path to the folder the user picks
if path == '':
y = py.inputYesNo("would you like to quit the program? ")
if y == 'yes':
break
if y == 'no':
continue
else:
return path
y = get_location_path()
print(y)
when i run the program and i exist the window without picking a folder, it will ask me if i want to quit the program, if i type y it quits the program but if i type n it does nothing and i cant even exist the program by pressing CTRL + C
enter n:
would you like to quit the program? n
empyty space
I've had to add some code to get your code to work as a tkinter app - it seems like you want this to run as a command line app which isn't what tkinter is for; however, I've tried to come up with a solution that uses tkinter since that's how this question is tagged.
import tkinter as tk
# import pyinputplus as py # (you don't need this if using tkinter)
from tkinter import messagebox as tkm # use native tkinter dialogs instead
from tkinter.filedialog import askdirectory
class App(tk.Tk):
def __init__(self):
super().__init__(). # initialize tk
self.title('My App')
self.geometry('640x480')
self.path = '' # create a variable to store the path
self.get_location_path() # prompt the user for a path
def get_location_path(self):
self.path = askdirectory(title='Select Folder') # show file dailog
if self.path: # if a path is selected...
self.use_location_path() # do whatever needs to be done with the path
elif ( # no path selected; ask the user if they want to quit
tkm.askyesno(
title='Exit Program?',
message='Would you like to quit the program?'
)
):
self.destroy() # yes, quit
else:
self.get_location_path() # no, ask for path again
def use_location_path(self):
print(self.path) # do some work...
self.destroy() # quit once the work is done
if __name__ == '__main__':
App().mainloop() # run the app
I'm making an app in tkinter that has a start up/welcome screen. How could I check if the app has been opened before, so that the next time the person opens the app/runs the script, they don't get the welcome screen anymore. Also, I'd like for a reset option that would trigger the welcome screen again. I know this is achievable, but I just don't know how. Thanks for your time!
This is just a quick idea as there are many ways you could get creative with this. I love try and except for this type of behavior. It is a great tool for something like this IMO. Hopefully this gives you an idea of what I meant.
*UPDATED to add suggestions from comments
from pathlib import Path
import os
import tkinter as tk
# consider changing directory to avoid permission issues as stated in comments based on OS
file = Path("File.txt")
try:
with open(file, "r"): # try to open the file
print("Not first Launch, No welcome screen")
except FileNotFoundError:
with open(file, "x"): # "x" will create the file as pointed out in comments
print("First time launch, file was created, welcome screen activated")
def reset():
try:
os.remove(file) # remove the file if it is there
print("Reset perfomed, file deleted")
except FileNotFoundError:
print("Program already reset")
root = tk.Tk()
reset_button = tk.Button(root, text="Reset", command=reset)
reset_button.pack()
root.mainloop()
I have been using tkinter to supply a file dialog (in python 3.6) which allows users to select a directory. It works fine when it is a sub-function within the same module, but if I move that subfunction into a separate module and then try to import it from that module, it no longer works. Instead the code just hangs when the file dialog should pop up but it never appears.
working code:
This works if I run the main function
from tkinter import Tk
from tkinter.filedialog import askdirectory
def SelectDirectory():
# start up the tk stuff to have a file directory popup
print('start')
root = Tk()
print('postroot')
root.withdraw()
print('postwithdraw')
# let the user pick a folder
basepath = askdirectory(title='Please select a folder')
print('postselection')
root.destroy()
print('postdestroy')
return basepath
def main():
ans = SelectDirectory()
print(ans)
If I instead put this in another module and import it from that module, then it will print until 'postwithdraw' and then just hang.
submod.py:
from tkinter import Tk
from tkinter.filedialog import askdirectory
def SelectDirectory():
# start up the tk stuff to have a file directory popup
print('start')
root = Tk()
print('postroot')
root.withdraw()
print('postwithdraw')
# let the user pick a folder
basepath = askdirectory(title='Please select a folder')
print('postselection')
root.destroy()
print('postdestroy')
return basepath
and then run this:
from submod import SelectDirectory
def main():
ans = SelectDirectory()
print(ans)
It never gets past 'postwithdraw' and the file dialog never pops up.
Does anyone know what I am doing wrong here? I would think it has something to do with the tkinter window not appearing since its not the main module but is there some way to get past that?
Your both versions don't work. Both give 'module' object is not callable.
You have to use
root = Tk.Tk()
instead of
root = Tk()
and then both versions works.
Maybe two Tk in Tk.Tk() seems weird but usually we use lowercase tk instead of Tk in
import tkinter as tk
and then you have
root = tk.Tk()
I'm using jupyter notebook on mac, recently I need to write interactive dialog box, so after google, I use Tkinter to make an interactive window.
But I was bothered by this problem couples day ,and still can't find a solution way.
Fisrt example:
from Tkinter import *
from tkFileDialog import askopenfilename
import sys
import os,time
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Second example:
from Tkinter import *
import sys,os
class YourApp(Tk):
def quit_and_close(self):
app.quit()
#os._exit(0)
#sys.exit(1)
#exit(0)
app = YourApp()
app.title('example')
app.geometry('400x300+200+200')
b = Button(app, text = "quit", command = app.quit_and_close)
b.pack()
app.mainloop()
And the third one:
import Tkinter as tk
import tkMessageBox
def ask_quit():
if tkMessageBox.askokcancel("Quit", "You want to quit now? *sniff*"):
root.destroy()
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", ask_quit)
root.mainloop()
After running those above code, always need have to force quit python launcher.
It is very weird, and annoying because after forcing quit, I will got the error:
Is it necessary to use python launcher as default window?
Is there possible to set another window to open ?
or is there proper way to close the launcher without causing programming crash?
p.s Even I try to use wxpython, it still open python launcher and got the same problem.
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