Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

python - Make a Tkinter Toplevel active

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 FilesNotepad++
otepad++.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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

...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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...