In macOS, windows created by Tkinter do not automatically get focus. This is annoying when using PyCharm. If you do not take any actions, the created window will be hidden behind PyCharm. An alternative is to set the window to the top and then cancel it (code show as below). This will make the window visible after creation.
1 2 3 4 5 6 |
window = Tkinter.Tk() window.title('test1') window.lift() window.attributes('-topmost', True) window.after_idle(window.attributes, '-topmost', False) window.mainloop() |
The above method is only to make the window appear in the front, the color of the title bar is still gray, which means that it is not activated.
Solution A: pyobjc
1 2 3 4 5 6 7 |
import os import Cocoa window = Tkinter.Tk() window.title('test1') getattr(Cocoa, 'NSRunningApplication').runningApplicationWithProcessIdentifier_( os.getpid()).activateWithOptions_(getattr(Cocoa, 'NSApplicationActivateIgnoringOtherApps')) window.mainloop() |
To install pyobjc module, executing…
1 |
pip install pyobjc |
During the installation of pyobjc, many other modules will be installed at the same time, in order to uninstall them together. Please execute the following command when you need to remove the whole pyobjc.
1 |
pip freeze | grep pyobjc | xargs pip uninstall -y |
Solution B: applescript
This solution is recommended because of no extra module needed.
1 2 3 4 5 6 |
window.attributes('-topmost', True) if platform.system() == 'Darwin': tmpl = 'tell application "System Events" to set frontmost of every process whose unix id is {} to true' script = tmpl.format(os.getpid()) subprocess.check_call(['/usr/bin/osascript', '-e', script]) window.after_idle(window.attributes, '-topmost', False) |