views:

22

answers:

1

I have a script that uses Tkinter to pop up a window with a message. How do I make sure it takes focus so the user doesn't miss it and explicitly has to dismis the window. the code is :

        root = Tk()
        to_read = "Stuff" 
        w = Label(root, text=to_read)
        w.pack()
        root.mainloop()

Thanks.

+3  A: 

You can use focus_force method. See the following:

But note the the documentation:

w.focus_force()

Force the input focus to the widget. This is impolite. It's better to wait for the window manager to give you the focus. See also .grab_set_global() below.

Update: It should work on root. For example, try running the following code. It will create a window and you can switch focus. After 5 seconds, it will try to grab the focus.

from Tkinter import *

root = Tk()
root.after(5000, lambda: root.focus_force())
root.mainloop()
ars
the command is ok, but where does it go in my code? It seems my format will be root.focus_force, but it give an Attribute error.
Ali
@Ali: I updated the question to answer your comment.
ars
it seems to be working now. I left out the .after function though. thanks.
Ali
@Ali: the `after` wasn't necessary: it was only to introduce a delay before forcing focus so I could start the application and have enough time to shift focus to another application for demonstration purposes. Glad it's working for you now. :)
ars