Python appscript OSAX display_dialog: how to move it to foreground - python

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()

Related

How to make my Program Display Always on top

Program Info & Problem
I have created a Python Program Using Pygame Module which displays the Ads on the monitor.
It shows The Ad on screen But as soon as I launch different applications like kodi or vlc or chrome, etc. It goes behind those applications.
The Problem is: The program runs but behind those applications if these applications are launched after my Ad Program.
Ideal Working
Program Laucnhed
Ad Displayed on screen
Launched Other Application
The Program still displayes the ad on top of screen.
System Info
OS: Linux - Ubuntu 20
Language: Python
Module: Pygame, Pymovie, GTK3+
Architecture: amd64
Desktop Enviroment: OpenBOX
Code Launch: CLI using a bash script which launches the python program of advertisment.
Sample Screenshot of Advertiesment
Please Help!
Thank you.
Looks like the best answer I can find is from this outdated website (https://www.mail-archive.com/pygtk#daa.com.au/msg01370.html)
they say to use code below, it should work on all OSs...things are never that easy
transient.set_transient_for(main_window)
Alternatively I have four other answers lol
Taken from (How to keep a python window on top of all others (python 3.1))
stackoverflow user pyfunc says for windows you can just do
import win32gui
import win32con
win32gui.SetWindowPos(hWnd, win32con.HWND_TOPMOST, 0,0,0,0,
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
Since this only works for windows I think you should try python-tinker, I believe it works on linux
root = Tk()
root.wm_attributes("-topmost", 1)
Also whatnick says you can use PyGTK
gtk.Window.set_keep_above
reference: How to make python window run as "Always On Top"?
Let me know if any of these work for you, I will keep looking for a better answer.
I think PyWinCtl can make the trick in most cases. You can invoke alwaysOnTop() once for your window, or you can call it inside your loop to assure it stays on top after other apps open. Check this:
import tkinter as tk
import pywinctl as pwc
class Window(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.overrideredirect(True)
self.geometry('300x200')
self.config(background='black')
self.attributes('-alpha', 0.5)
self.label = tk.Label(text="Hello World!")
self.label.pack(fill=tk.BOTH, expand=1)
self.wait_visibility()
self.window = pwc.Window(int(self.frame(), base=16))
# Call it once at the beginning of your program...
try:
self.window.alwaysOnTop()
except:
pass
self.counter = 0
self.display()
def display(self):
if self.state() == "normal":
try:
# ... or call it repeatedly to assure it stays on top
self.window.alwaysOnTop()
except:
# On Linux, sometimes it takes more time to recognize the new window
self.window = pwc.Window(int(self.frame(), base=16))
self.label.config(text=str(self.counter))
self.counter += 1
self.after(1000, self.display)
root = Window()
root.mainloop()

How to open a program os.system only using python 3

I am programming a gui using tkinter. I use os.system('file extension'). when I click the button on the gui it should open the next program, but it wont because of python 2. I can use terminal and have pythem3 ./mixed_drink, and this works. Can I set up the code to make the program only run in python 3??
from tkinter import *
import os
##############
root = Tk()
root.title('GET YO DRANK MAIN ')
root.geometry("800x400")
def open_mixed_drinks():
os.system("/home/pi/mixed_drinks.py")
If I understand your question properly, try os.system("python3 /home/pi/mixed_drinks.py")
This way you are passing the .py file to the default installed python3 binary on your system, rather than the global default python which may still be 2.7 on many systems

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 can I ensure that the application windows is always on top?

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.

How to embed some application window in my application using any Python GUI framework

I want some application to look like widget inside my Python application.
That's all. I dont need any interaction between them. I'm interested in solutions in any GUI toolkit for both windows and x windows.
It would be nice to have a solution with Tkinter but it's not crucial.
Using GTK on X windows (i.e. Linux, FreeBSD, Solaris), you can use the XEMBED protocol to embed widgets using gtk.Socket. Unfortunately, the application that you're launching has to explicitly support it so that you can tell it to embed itself. Some applications don't support this. Notably, I can't find a way to do it with Firefox.
Nonetheless, here's a sample program that will run either an X terminal or an Emacs session inside a GTK window:
import os
import gtk
from gtk import Socket, Button, Window, VBox, HBox
w = Window()
e = Button("Emacs")
x = Button("XTerm")
s = Socket()
v = VBox()
h = HBox()
w.add(v)
v.add(s)
h.add(e)
h.add(x)
v.pack_start(h, expand=False)
def runemacs(btn):
x.set_sensitive(False); e.set_sensitive(False)
os.spawnlp(os.P_NOWAIT, "emacs",
"emacs", "--parent-id", str(s.get_id()))
def runxterm(btn):
x.set_sensitive(False); e.set_sensitive(False)
os.spawnlp(os.P_NOWAIT, "xterm",
"xterm", "-into", str(s.get_id()))
e.connect('clicked', runemacs)
x.connect('clicked', runxterm)
w.show_all()
gtk.main()
Not enough reputation to comment on Glyphs answer. To make xterm work, in addition to the comments above one needs to also add
XTerm*allowSendEvents: True
to ~/.Xresources. (and perhaps reload those, with xrdb -load ~/.Xresources)

Categories

Resources