Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a Tkinter Toplevel active

Tags:

python

tkinter

I am trying to make a Toplevel widget that is the active window on the screen (I want it so that if you press Enter, it exits the window. I already have the key bound to the widget, but I can't seem to get the window to be the main window on my computer. I am running my program using Notepad++ (I have a shortcut for this specific program since I will be using it a lot).

Here is my code:

def main():
    root = Tk(className = ' Module Opener')
    app = GetFileName(root)
    root.rowconfigure(0, weight = 1)
    root.columnconfigure(0, weight = 1)
    root.bind('<Return>', (lambda e, b=app.goButton: b.invoke()))
    root.mainloop()
    f, pythonType = app.fileName, app.pythonType
    if f[-3:] != '.py': f += '.py'
    moduleFile = getFilePath(f, pythonType)
    if not moduleFile is None:
        subprocess.call([r"C:\Program Files\Notepad++\notepad++.exe", moduleFile])
    else:
        root.withdraw()
        finalRoot = Toplevel(root)
        finalRoot.grab_set() # I thought this would make it active
        finalApp = FileNotExist(finalRoot, f)
        finalRoot.rowconfigure(0, weight = 1)
        finalRoot.columnconfigure(0, weight = 1)
        finalRoot.bind('<Return>', (lambda e, b=finalApp.okButton: b.invoke()))
        finalRoot.mainloop()

I want it so that when it opens, if I press Enter, it does my command; however, I have to click in the window first so that it becomes active, and then it works.

I tried various things such as finalRoot.lift(), finalRoot.focus_set(), finalRoot.grab_set()/finalRoot.grab_set_global() (I saw these methods from another question), and finalRoot.focus().

The first window Tk() is active when the program starts. However, the Toplevel() is not. I also tried making two Tk()'s (destroying root and then creating finalRoot as a new Tk() instance), but this did not work as well. How can I do this? Thanks!

like image 587
Rushy Panchal Avatar asked Dec 20 '22 07:12

Rushy Panchal


2 Answers

...however, I have to click in the window first so that it becomes active, and then it works.

I just encountered this problem and while I was researching a solution, I found this thread. I'm using Windows 7 Professional. All I did was call both grab_set() and focus() and it solved the problem for me. You already have finalRoot.grab_set(), just add:

finalRoot.focus()

It worked in my case.

like image 108
sedeh Avatar answered Dec 27 '22 12:12

sedeh


I tried the above solutions and found that focus_force() alone worked on Windows Vista/Python 3.3. Also it may help to include the takefocus=True method while creating your Toplevel window.

like image 44
KAG1224 Avatar answered Dec 27 '22 10:12

KAG1224