MatthewG
MatthewG

Reputation: 815

TopLevel window disappears when using askopenfilename, from tkinter.filedialog

For my program I want the user to select a file, and I am using the tkinter.filedialog library to do this. However, when the askopenfilename dialog is opened, the TopLevelwindow disappears behind the main Tk() window.

How would I stop this from happening?

Here is the code that I have written so far:

from tkinter import *
from tkinter.filedialog import askopenfilename


class MainWin(Tk):
    def __init__(self):
        super(MainWin, self).__init__()
        self.update()
        pu = PopUp(self)
        self.configure(width=500, height=300)


class PopUp(Toplevel):
    def __init__(self, master):
        super(PopUp, self).__init__(master)

        def entry_set(entry, text):
            entry.delete(0, 'end')
            entry.insert(END, text)

        item_file = StringVar()
        item_entry = Entry(self, textvariable=item_file)
        item_entry.place(x=80, y=60, height=20, width=300)
        item_label = Label(self, text="item file: ", bg="gray74", relief="groove")
        item_label.place(x=20, y=60, height=20, width=60)
        item_button = Button(self, text="\uD83D\uDCC2", relief="groove",
                             command=lambda: entry_set(item_entry, askopenfilename()))
        item_button.place(x=380, y=60, height=20, width=20)
        self.configure(width=460, height=180)


if __name__ == '__main__':
    win = MainWin()
    win.mainloop()

Edit:

I have realised that using the .grab_set() method works, and will make the TopLevel() window appear back on top of the Tk() after the file is chosen.

However, this still means the window disappears behind the Tk() window whilst picking a file, I would still love to find a solution to this, even though this is now just a visual problem, not a functional one.

Upvotes: 3

Views: 1489

Answers (1)

acw1668
acw1668

Reputation: 46669

You can just make the Toplevel window a transient window, it will then be kept on top of its parent window:

class PopUp(Toplevel):
    def __init__(self, master):
        super(PopUp, self).__init__(master)
        self.transient(master)

Upvotes: 1

Related Questions