Reputation: 133
I am attempting to use a message box in Python 3 with Tkinter to solicit a name for a user. The following stripped down code produces such a message box and correctly passes the values on close, but the message box pops up behind the main window. If I move the message box out, type something in as a name, and click OK, the main window is updated but hidden behind every other open window.
A friend tried to replicate the issue on a Mac, but the code behaved as expected.
How do I make the message box show up on top with focus at the beginning, and how do I correctly hand focus to the main window when the message box is closed?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter
import tkinter.simpledialog
root = tkinter.Tk()
playerNameVar = tkinter.StringVar()
playerNameVar.set(tkinter.simpledialog.askstring("Name", \
"Name?",parent=root))
playerLabel = tkinter.Label(root,textvariable = playerNameVar)
playerLabel.grid()
root.mainloop()
Upvotes: 3
Views: 3219
Reputation: 15335
"How do I make the message box show up on top with focus at the beginning, and how do I correctly hand focus to the main window when the message box is closed?"
I don't think you can make the message box show up on top with focus without unwrapping tkinter to its Tcl, you can however easily make the root
to lower
itself just before the dialog is shown:
root.lower()
You can simply call focus_set
after the lines for calling the dialog line. See below code for complete example:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter
import tkinter.simpledialog
root = tkinter.Tk()
root.lower()
playerNameVar = tkinter.StringVar()
playerNameVar.set(tkinter.simpledialog.askstring("Name", \
"Name?",parent=root))
root.focus_set()
#root.tkraise() # this is optional
playerLabel = tkinter.Label(root,textvariable = playerNameVar)
playerLabel.grid()
root.mainloop()
Upvotes: 1