2

Is it possible to automatically activate the main window of a tkinter app? I am using Yosemite on a Mac. When the window comes up, the title bar is grayed out, and I have to click on the window before it will respond to events. The Tk manual says that event generate, "Generates a window event and arranges for it to be processed just as if it had come from the window system." I tried generating a <Button-1> event, but it had no effect. The manual goes on to say, "Certain events, such as key events, require that the window has focus to receive the event properly." I tried focus_force, but it didn't work either.

Is it possible to do what I want? Is this a Mac peculiarity? In the code below, the text changes as the mouse cursor enters and leaves the label, but the app is unresponsive until you click on the window.

import tkinter as tk    
root = tk.Tk()

def visit(event):
    kilroy['text'] = 'Kilroy was here.'
def gone(event):
    kilroy['text'] = 'Kilroy has left the building'
def startup():
    root.focus_force()
    root.event_generate('<Button-1>')    

frame = tk.Frame(root, width=500,height=100)
kilroy = tk.Label(frame, text="Kilroy hasn't been here.", width = 50)
kilroy.grid(row=0,column=0)
frame.grid(row=0,column=0)
kilroy.grid_propagate(0)
frame.grid_propagate(0)
kilroy.bind('<Enter>', visit)
kilroy.bind('<Leave>', gone)

root.after(100,startup)
root.mainloop()
saulspatz
  • 5,011
  • 5
  • 36
  • 47
  • 1
    how are you starting the program? Are you double-clicking an icon? Are you typing a command from a command prompt? – Bryan Oakley Dec 20 '15 at 17:03
  • Typing a command in the terminal – saulspatz Dec 20 '15 at 20:37
  • I ran into a similar problem, the solution can be found [here](http://stackoverflow.com/questions/40843698/how-to-auto-activate-a-tkinter-simpledialog-pop-up-window/40876290#40876290). – Montmons Nov 29 '16 at 21:46
  • @SB87 Thanks, but this didn't work for me. I added the line `os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "python" to true' ''')` just before `root.mainloop()` and I get the message `21:62: execution error: Finder got an error: Can’t set process "python" to true. (-10006)`. I get a similar error if I write "Python" instead of "python". The execution of the python app is unchanged. Have I misunderstood you? – saulspatz Dec 04 '16 at 09:39

0 Answers0