Home > front end >  Python 3 tkinter box opened during file prompt won't go away
Python 3 tkinter box opened during file prompt won't go away

Time:08-25

This is all the tkinter I' m using

from tkinter import filedialog as fd

file1 = fd.askopenfilename()
file2 = fd.askopenfilename()

data = pd.ExcelFile(file1)
data2 = pd.ExcelFile(file2)

It will open the file prompt no problems, but it also opens a small blank tkinter window that won't go away. When I try to close it, it just hangs. Is there a way to get it to close on its own, or not exist in the 1st place?

CodePudding user response:

This problem was describe long time ago.

It automatically creates main window tkinter.Tk() which you see.

You should create it manually and hide it, and later you should destroy it.

import tkinter as tk   # PEP8: `import *` is not preferred
from tkinter import filedialog as fd

root = tk.Tk()   # create main window
root.withdraw()  # hide main window

file1 = fd.askopenfilename()
file2 = fd.askopenfilename()

root.destroy()   # destroy main window

# -----

if file1:  # check if not `Cancel` selection
    data1 = pd.ExcelFile(file1)
else:
    data1 = None
    
if file2:  # check if not `Cancel` selection
    data2 = pd.ExcelFile(file2)
else:
    data2 = None

PEP 8 -- Style Guide for Python Code

CodePudding user response:

Your code is auto-opening the Tk window. Create it by yourselves so you can modify it and destroy it.

from tkinter import Tk, filedialog as fd

tk = Tk()
tk.withdraw() # do not draw window

file1 = fd.askopenfilename()
file2 = fd.askopenfilename()

tk.destroy() # destroy window

data = pd.ExcelFile(file1)
data2 = pd.ExcelFile(file2)

NOTE: I modified the code so you can actually run it.

  • Related