Tkinter opens two windows - python

I am using python 3.6 and have the following issue.
These lines of codes apparently open two windows, but I only expect one to be opened.
from tkinter.filedialog import asksaveasfilename
file_name = asksaveasfilename()
root.withdraw()

IIRC, you're supposed to call withdraw before you call asksaveasfilename. Same as in Choosing a file in Python with simple Dialog.
import tkinter
from tkinter.filedialog import asksaveasfilename
tkinter.Tk().withdraw()
file_name = asksaveasfilename()

when you do filename = asksaveasfilename() you call the function
and that makes tkinter open the second window put that in a function and on
a button click the second window will open
from tkinter.filedialog import asksaveasfilename
import tkinter
root = tkinter.Tk()
root.withdraw()
asksaveasfilename()

Related

Python tkinter askopenfilename not responding

I am using tkinter asopenfilename to trigger a file chooser so as to read files from my local directory. My problem is that after the file is chosen, the window freezes and python is 'not responding'.
I've tried the answer from this post: Tkinter askopenfilename() won't close no luck.
Below is my code:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw()
root.update()
filename = askopenfilename()
print(filename)
Is there anything that I am missing? Let me know if you need more clarity. Thanks!
I tried all above solutions but didn't seem to solve the same issue for me. The dialog box was opening but somewhere in the background.
Found this code elsewhere and it works like a charm for me. On windows 10 too, python 3.x, and using Jupyter Notebook.
Posting it here in case it could help others.
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
file_path = filedialog.askopenfilename(
%gui tk
print(file_path)
I tried using root.update() after filename = askopenfilename() in my MacOS.
Following worked for me-
from tkinter import Tk
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw()
filename = askopenfilename()
root.update()
print(filename)
I had the same behavior on MacOS and adding the iPython magic %gui tk appears to be solving the issue:
from tkinter import Tk
from tkinter.filedialog import askopenfilename
%gui tk
root = Tk()
root.withdraw()
filename = askopenfilename(multiple=True)
print(filename)
From the docs:
%gui tk # enable Tk event loop integration
askopenfilename doesn't work in windows
from tkinter import *
#from tkFileDialog import askopenfilename
import tkinter.filedialog
def callback():
name= tkinter.filedialog.askopenfilenames()
print (name)
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()

Python 2.71.11 Tkinter window not closing "Application not Responding"

I'm trying to open a simple file dialog to ask the user to select a file. The code I have is:
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
sys.exit(0)
The program retrieves the file name successfully, however the window remains open and does not close. The only way I can exit it is through Force Quit. I am using Mac OS X 10.11 and Python 2.7.11.
Thank you
There seems to be some issues based on your development environment. See reference [2]. This worked for me:
from Tkinter import Tk
from tkFileDialog import askopenfilename
root = Tk() #To initialize Tkinter, we have to first create a Tk root widget
filename = askopenfilename() # store filename
# root.mainloop() may be necessary for your development environment (see [2])
root.destroy() #destroy the event loop - only required in some python environments (see [2])
print(filename)
[1] http://effbot.org/tkinterbook/tkinter-hello-tkinter.htm
[2] http://effbot.org/tkinterbook/tkinter-hello-again.htm

how do I get Tkinter askopenfilename() to open on top of other windows?

I am running a script that prompts the user for a file. There is no gui except for the file browser that opens up. I have 2 options: browse for file, or select entire folder using askdirectory(). The latter opens on top of all other windows, but the first one opens under everything, I have to minimize other windows to find it.
Here is the method I'm using for these operations
from Tkinter import Tk
from tkFileDialog import askdirectory, askopenfilename
root = Tk()
root.withdraw()
self.inpath = askdirectory() # To open entire folder
Path = askopenfilename() # Open single file
root.destroy() # This is the very last line in my main script.
This is everything Tk related in my code. askdirectory opens on top, askopenfilename doesn't.
Is there a way to force it to open on top?
root.wm_attributes('-topmost', 1) did it for me. I found it in another SO thread to be honest :-).
I had the same problem.
For me it works with:
file = filedialog.askopenfilename(parent=root)
So, the file dialog gets in front of toplevel window without uncomment root.attributes("-topmost", True)
I want to share that the following lines worked superbly in my case. But I had to use both window.wm_attributes('-topmost', 1) and window=parent to make this work, see below:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.wm_attributes('-topmost', 1)
window.withdraw() # this supress the tk window
filename = filedialog.askopenfilename(parent=window,
initialdir="",
title="Select A File",
filetypes = (("Text files", "*.txt"), ("All files", "*")))
# Here, window.wm_attributes('-topmost', 1) and "parent=window" argument help open the dialog box on top of other windows
I had the same issue of the file dialog window opening below my current window but I couldn't reproduce the issue with your code (in Python 2 or 3).
This is the minimal example where the issue occurs (context is Windows 10, Python 3, script is called from Idle, and note the input function:
File dialog opens below:
from tkinter import filedialog, Tk
root = Tk()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
To open file dialog on top, both root.lift() or root.attributes("-topmost", True) work (but the latter is specific for Windows)
from tkinter import filedialog, Tk
root = Tk()
#root.attributes("-topmost", True) # this also works
root.lift()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
I'm running python 3.x so there is a difference in code, but both opened on top for me. Try giving it focus, it should put in on top.
self.inpath.focus()
I'm not sure if it's gonna work, since I cant reproduce the problem.

tkFileDialog won't open gui when running script from cmd

I building a messenger with possibility to send files. Iv'e added this line to prevent the tk window to be shown:
Tk().withdraw()
and I'm opening files with this command
tkFileDialog.askopenfilename()
through IDLE python editor it all seems to be working, but when I open python script through cmd and try to send a file , the gui do not show up at all, and the dialog to choose file doesn't open.
when I remove the command Tk().withdraw() , it seems to be working again , but this stupid blank Tk window is still shown up.
How do I prevent the blank Tk from being shown up when I running the script from cmd without causing the choose file dialog to disappear?
this is the code (I'm using python 2.7 , and this is not the whole code, I pasted just the necessary parts):
from Tkinter import Tk
import tkFileDialog
messege = raw_input()
if messege == "SEND":
print "Starting to send file..."
isSendingFile = True
resDir = tkFileDialog.askopenfilename()
filetype = resDir[(resDir.rfind('.')):]
filename = resDir[(resDir.rfind('/') + 1):-(len(filetype))]
s.send("SEND|name:" + filename + "|type:" + filetype)
fileToSend = open(resDir, "rb")
messege = fileToSend.read()
s.send(messege)
fileToSend.close()
isSendingFile = False
You could try to keep a reference to the main window:
import os
try: # Python 2
from Tkinter import Tk
from tkSimpleDialog import askstring
from tkFileDialog import askopenfilename
except ImportError: # Python 3
from tkinter import Tk
from tkinter.simpledialog import askstring
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw() # hide main window
message = askstring("Message", "What is the message?")
if message == "SEND":
resdir = askopenfilename()
root.destroy() # done with gui
path, filetype = os.path.splitext(resdir)
filename = os.path.basename(path)

tkinter - how to open multiple filedialogs?

in python's default editor, IDLE, it is possible to have multiple 'Open' dialogs opened at the same time.
I'm looking at their source, but I can't find where I can have this behavior replicated. from their IOBinding.py's :
from tkinter import filedialog as TkFileDialog
...
class IOBinding:
...
def askopenfile(self):
dir, base = self.defaultfilename("open")
if not self.opendialog:
self.opendialog = tkFileDialog.Open(master=self.text,
filetypes=self.filetypes)
filename = self.opendialog.show(initialdir=dir, initialfile=base)
return filename
so they do use tkinter's built-in filedialog module, but I can't find way to have some 'modeless' dialogs. I can have dialogs opened by two codes, which are basically same:
from tkinter import filedialog as tkFileDialog
file_name = tkFileDialog.Open( ... ).show()
file_name = tkFileDialog.askopenfilename()
but they blocks whole application - users cannot switch windows or issue new command until they close the dialog. also, I can't call these dialog functions from different thread - that will kill whole my Tk app. What should I do?
filedialog have parent option. You can change it to hidden window to prevent blocking the root window:
from tkinter import filedialog as tkFileDialog
from tkinter import *
def ask_open():
p = hidden if attach_to_hidden.get() else root
tkFileDialog.Open(parent=p).show()
root = Tk()
hidden = Toplevel()
hidden.withdraw()
attach_to_hidden = IntVar()
Checkbutton(root, text='Attach to hidden window', variable=attach_to_hidden).pack()
Button(root, text='Open', command=ask_open).pack()
root.mainloop()

Categories