TKinter window won't close?

171 Views Asked by At

I have a script which opens a file selection window using the tinter module. I've run it without issue on a windows computer, but on a Mac (Ventura 13.3.1) the window doesn't close after selecting a file. It persists as a small, blank window titled tk and as an application

in my Dock titled python3.10. I also see the following notice when I run the script:2023-06-30 11:17:10.566 python[42030:4586512] +[CATransaction synchronize] called within transaction

The Python code:

from tkinter import *
from tkinter import filedialog

def get_file():
   
    root = Tk()
    root.wm_attributes('-topmost', 1)
    root.withdraw()
    selected_file = filedialog.askopenfilename(initialdir='',
                                               title="File Selection",
                                               parent=root)

    return selected_file

print('Select .csv File with Relevant Absorption Spectra')
data_path = get_file()
2

There are 2 best solutions below

1
JRiggles On

You create a root window when you instantiate tk with root = Tk(), but because of the way Mac OS handles quitting apps, closing the window isn't enough to exit. You need to call root.quit().

Also, setting '-topmost' here is unnecessary since you're immediately minimizing the window.

Lastly, star imports are usually regarded as a bad idea. To avoid namespace pollution you'd typically use import tkinter as tk and then prefix your tkinter objects with tk. like I've done with root = tk.Tk()

import tkinter as tk
from tkinter import filedialog


root = tk.Tk()
root.withdraw()


def get_file():
    return filedialog.askopenfilename(
        initialdir='',
        title="File Selection",
        parent=root
    )

print('Select .csv File with Relevant Absorption Spectra')
data_path = get_file()
...  # do whatever with the file here
root.quit()  # exit the app

All that said, you'll obviously want to do whatever you need to to with data_path before the call to root.quit()

Hope that helps, and happy coding!

0
AudioBubble On

Looks like you forgot root.destroy()
Heres a fixed code:

from tkinter import *
from tkinter import filedialog

def get_file():
   
    root = Tk()
    root.wm_attributes('-topmost', 1)
    root.withdraw()
    selected_file = filedialog.askopenfilename(initialdir='',
                                               title="File Selection",
                                               parent=root)
    root.destroy() # Destroy window
    return selected_file

print('Select .csv File with Relevant Absorption Spectra')
data_path = get_file()