How can I ensure that the application windows is always on top? - python

I have a simple Python script that runs in a console windows.
How can I ensure that the console window is always on top and if possible resize it?

Using Mark's answer I arrived at this:
import win32gui
import win32con
hwnd = win32gui.GetForegroundWindow()
win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST,100,100,200,200,0)

To do this with the cmd window, you'll probably have to invoke a lot of win32 calls.
Enumerate all the windows using win32gui.EnumWindows to get the window handles
Find the "window title" that matches how you run your program. For example, doubling clicking on a .py file on my system the window title is "C:\Python26\python.exe". Running it on a command line, it is called c:\Windows\system32\cmd.exe - c:\python26\python.exe test.py
Using the appropriate title get the cmd window handle.
Using win32gui.SetWindowPos make your window a "top-most" window, etc...
import win32gui, win32process, win32con
import os
windowList = []
win32gui.EnumWindows(lambda hwnd, windowList: windowList.append((win32gui.GetWindowText(hwnd),hwnd)), windowList)
cmdWindow = [i for i in windowList if "c:\python26\python.exe" in i[0].lower()]
win32gui.SetWindowPos(cmdWindow[0][1],win32con.HWND_TOPMOST,0,0,100,100,0) #100,100 is the size of the window

If you are creating your own window, you can use Tkinter to create an "always on top" window like so:
from Tkinter import *
root = Tk()
root.wm_attributes("-topmost", 1)
root.mainloop()
And then put whatever you want to have happen within the main loop.
If you are talking about the command prompt window, then you will have to use some Windows-specific utilities to keep that window on top. You can try this script for Autohotkey.

Related

python tkinter main window

I was trying to open a code with pycharm and the following lines are the begining . but it doesn't open any window . what should I do ?
import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
it runs and instantly closes without opening any window
In order to make sure the window doesn't close you need the mainloop function.
import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
tkinter.mainloop()

Tkinter not working the first time it runs with withdraw()

I am trying to make a Tkinter script to select files through Windows File Explorer. I don't need the Tkinter window to show, just the File Explorer interface.
import tkinter
from tkinter import filedialog
import os
window = tkinter.Tk()
#window.geometry("1x1")
window.withdraw()
def open_files():
files = filedialog.askopenfiles(mode='r')
global filenames
filenames = [os.path.abspath(file.name) for file in files]
window.destroy() # analysis:ignore #says "window" is undefined becasue of "del window" below
window.after(0, open_files)
window.mainloop()
del window
The first time I run this in Spyder, if window.withdraw() is not commented out, the console just shows runfile(*my_file_name*) and the code does... something... in the background, but nothing seems to actually happen. Nothing changes on-screen, but I cannot type in the console so I know the code is running.
If I open a new console tab and run the code with window.withdraw() commented out, everything works, and the Tkinter GUI is visible. If I then run this code again in the same tab, with window.withdraw() not commented out, then the code works as intended, with only the File Explorer window opening up, and the Tkinter GUI staying hidden. This is the case even if I click the "Remove all variables" button in Spyder, so as far as I understand the code is not saving any variables that allow it to run properly after the first time.
My question is, why does this code work the 2nd, 3rd, 4th, etc. time I run it, but not the first time?
I kept playing around, and changed -alpha to alpha and got this error:
TclError: wrong # args: should be "wm attributes window ?-alpha ?double?? ?-transparentcolor ?color?? ?-disabled ?bool?? ?-fullscreen ?bool?? ?-toolwindow ?bool?? ?-topmost ?bool??"
So I ended up changing window.attributes('-alpha',0) to window.attributes('-topmost',True, '-alpha',0), and this works! It brings up File Explorer on the first run without showing the Tkinter window. Thank you #Thingamabobs for your help.
My final code is:
import tkinter
from tkinter import filedialog
import os
window = tkinter.Tk()
window.attributes('-topmost',True, '-alpha',0)
filenames = [os.path.abspath(file.name) for file in filedialog.askopenfiles(mode='r')]
window.destroy()
del window

Opening Full-Screen Processes From Tkinter Hangs First Time

I am writing a game-launching menu in Python 2.6 which uses subprocess.popen() to run your selected game. My problem is that the first time I run any game from the menu, it hangs: I get an hour glass over my Python app, and the game which I launched does nothing. I an see the game's icon on the task bar, but clicking on it does nothing. I have to kill the game's process in Task Manager. After this happens once, I can then launch any game, including the one I just had a problem with, and it works fine. I can even exit from my Python app and re-run it, and I don't have the problem. But I will get this problem again after a reboot. I've narrowed the offending code down to:
import os
import subprocess
from Tkinter import *
def reportEvent(event):
if event.keysym == "Alt_L":
os.chdir("\\path\\to\\game")
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen("game.exe", startupinfo=si).wait()
root = Tk()
root.option_readfile("optionDB")
root.bind('<KeyPress>', reportEvent)
root.mainloop()
The following code does not have this problem (initializes TK but does not use its main loop):
import os
import subprocess
from Tkinter import *
root = Tk()
root.option_readfile("optionDB")
os.chdir("\\path\\to\\game")
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen("game.exe", startupinfo=si).wait()
I can use my launcher to open non-fullscreen (windowed) applications without this problem occurring. It only happens for full-screen games. Any ideas? Thank you.
Edit: Based on a suggestion below, I tried the same code with Python 3.4, but I still get the same behavior.

How do I end a Tkinter python module on mac so I don't have to force quit python launcher after the program is done?

This is my code:
from Tkinter import *
app = Tk()
app.title('example')
app.geometry('400x300+200+200')
b = Button(app, text = "quit", command = app.quit)
b.pack()
app.mainloop()
When I run this python launcher pops up and when I close the window or press the quit button the window closes and the python idle says its done but python launcher becomes unresponsive and I have to force quit it for python launcher to quit and disappear from the dock.
Is there a command that I have to use to exit the code properly?
You are looking for sys.exit()
Here is an example that works
from tkinter import *
import sys
class YourApp(Tk):
def quit_and_close(self):
app.quit()
sys.exit()
app = YourApp()
app.title('example')
app.geometry('400x300+200+200')
b = Button(app, text = "quit", command = app.quit_and_close)
b.pack()
app.mainloop()
I've been looking all over and it seems like this might have been a known bug.
The best response I've gotten is from:
window = tk.Tk()
window.protocol("WM_DELETE_WINDOW", window.destroy)
Which allows you to close the window with the little x. This ends the process in the spyder console window, but not the process in the applications bar on the mac. That must still be force quit.
I tried making a function like this to destroy the window and exit using sys, but this just causes the freeze again.
def CloseProgram():
sys.exit()
window.destroy()
Try using Terminal instead of an IDE. I've found that IDEs are very finicky, and using Terminal properly exits and quits the Python Launcher.

Python appscript OSAX display_dialog: how to move it to foreground

I am playing around with the example from here; esp. I have this code:
from osax import *
sa = OSAX()
print sa.display_dialog("Python says hello!",
buttons=["Hi!", "Howdy!", "Duuuude!"],
default_button=3)
The dialog always opens in the background. How can I open it in (or move it to) the foreground?
Add an activate command to give your Python process the window manager application focus.
sa = OSAX()
sa.activate()
print sa.display_dialog(...)
You can also choose to not GUIfy your Python process by targeting a faceless background app as described here.
This works for now:
def go_foreground():
from AppKit import NSApp, NSApplication
NSApplication.sharedApplication()
NSApp().activateIgnoringOtherApps_(True)
go_foreground()

Categories

Resources