Python tkinter 8.5 - How do you change focus from main window to a pop up window? Python tkinter 8.5 - How do you change focus from main window to a pop up window? tkinter tkinter

Python tkinter 8.5 - How do you change focus from main window to a pop up window?


You're on the right track.

Firstly, you should only ever have one instance of Tk at a time. Tk is the object that controls the tkinter application, it just so happens that it also shows a window. Whenever you want a second window (third, fourth, etc.) you should use Toplevel. You can use it as you have used Tk, just pass it root:

txt = Toplevel(root)

It is just missing things like mainloop.

Secondly grid and pack do not return anything. So for example:

okButton = ttk.Button(txtFrame, text = "OK", command = lambda: close(txt)).grid(column=2, row=2)

Should be:

okButton = ttk.Button(txtFrame, text = "OK", command = lambda: close(txt))okButton.grid(column=2, row=2)

But you should have been getting an error if that was causing you problems.

So to answer your main question, as you do with the Entry at the bottom you just call focus on the appropriate widget. focus_set does exactly the same, in fact if you look in Tkinter.py you will find focus_set is the name of the method, and focus is just an alias.

This will give the widget focus when the application has focus. If the application is not in focus there are ways to force it into the focus, but it is considered impolite and you should let the window manager control that.


Instead of making a seperate Tk Window, you could use the built in tkmessagebox. This will give the window and OK button focus right out of the box.

Something like this:

tkMessageBox.showinfo("Warning","Please enter a .txt file.")

http://www.tutorialspoint.com/python/tk_messagebox.htm

Also, note I wrote this in Python 2.7, the syntax may be slightly different for Python 3, but the functionality should be the same.