On Macos run function when global hotkey pressed - python

I have created a simple OCR with python to recognize text. I want this function to run when a global hotkey is pressed even if the focus is not on the app. How can I achive this?
Code:
#!/Library/Frameworks/Python.framework/Versions/3.9/bin/python3
import pytesseract
from PIL import Image
import os
import rumps
import pyperclip
#rumps.clicked('OCR')
def ocr(sender):
os.system('screencapture -i %s' % '/Users/jerryhu/Desktop/capture.png')
img = Image.open('/Users/jerryhu/Desktop/capture.png')
text = pytesseract.image_to_string(img)
pyperclip.copy(text)
rumps.Window(message='OCR Capture', default_text=text, title='Text Copied').run()
os.remove('/Users/jerryhu/Desktop/capture.png')
app = rumps.App('OCR', menu=[
'OCR',
None
])
app.run()
It's better to use a global hotkey instead of rumps for this project.

Related

How to open a tkinter window that is in an other file in Python?

I recently started working on a program in python using Tkinter and now I want to open it from another file.
I have a home page file named HomePage.py that will have a button to open another file, called VirusTotalAPI.py. I didn't find any answers because when I run the program, it opens the VirusTotalAPI.py file, and if I close it the Homepage.py will run, but the button won't work and if I try to close it, it will open the HomePage.py.
#Homepage.py
from tkinter import *
import VirusTotalAPI as vt
Home_Window=Tk()
Home_Window.geometry("980x530")
Home_Window.title("VirusTotal By Carotide")
Home_Window.config(background="grey")
def Window_35_mo() :
vt.Window_35mo
Window_35_mo_open = Button()
Window_35_mo_open.config(text= "Fichier < 35 mo", command= Window_35_mo)
Window_35_mo_open.pack()
Home_Window.mainloop()
The next one is a part from the VirusTotalAPI.py because the file is too long
#VirusTotalAPI.py
import requests
import hashlib
import json
from tkinter import *
from tkinter import filedialog
import HomePage
Window_35mo = Tk()
Window_35mo.geometry("980x530")
Window_35mo.title("VirusTotal By Carotide")
Window_35mo.config(background="grey")
global files
global file_path
def retrieve_API():
API_Value=GetAPIBox.get("1.0","end-1c")
print(API_Value)
GetAPIBox=Text(Window_35mo, height=2, width=10)
GetAPIBox.pack()
API_Button=Button(Window_35mo, height=1, width=10, text="YourAPI",
command=lambda: retrieve_API())
API_Button.pack()
Window_35mo.mainloop()
Thank you in advance.
I tried to import it by different ways like this:
import VirusTotalAPI
Or this:
from VirusTotalAPI import *
I tried to do this too:
from tkinter import *
from VirusTotalAPI import Window_35mo
Home_Window=Tk()
Home_Window.geometry("980x530")
Home_Window.title("VirusTotal By Carotide")
Home_Window.config(background="grey")
#homepage
def winopen35mo() :
Window_35mo
Window_35_mo_open = Button()
Window_35_mo_open.config(text= "Fichier < 35 mo", command= winopen35mo)
Window_35_mo_open.pack()
Home_Window.mainloop()
And it told me this:
ImportError: cannot import name 'Window_35mo' from partially initialized module 'VirusTotalAPI' (most likely due to a circular import)
I finally found how to do it there is the solution :
First we need to import os, subprocess and sys
from tkinter import *
import os
import subprocess
import sys
Then,we declare the file path of the file, for this one it is VirusTotalAPI.py by doing so :
GUI_VirusTotalAPI_Path = 'C:\\Users\\...\\VirusTotalAPI.py'
Now we enter the args, to execute and enter the path name :
args = '"%s" "%s" "%s"' % (sys.executable,
GUI_VirusTotalAPI_Path,
os.path.basename(VirusTotalAPI))
We are almost there, now we create a function to run this using the args we previoulsy used :
def Open_GUI_VirusTotalAPI_35mo() :
proc = subprocess.run(args)
Then another function to destroy the window :
def DestroyHomeWindow() :
Home_Window.destroy
Finally we create the button and "tell" it to execute the command Open_GUI_VirusTotalAPI_35moand at the same time close the window :
Window_35_mo_open = Button()
Window_35_mo_open.config(text= "Fichier < 35 mo", command= lambda:[Home_Window.destroy(),Open_GUI_VirusTotalAPI_35mo()])
Window_35_mo_open.pack()
And this is how I did it, sorry for the poor explanation and my bad english, hope this helped some people.

I cannot use pyautogui or pydirectinput for game scripting

I'm trying to make a script for stardew valley, the mouse moves correctly and all the other stuff too, but when i use the click function it doesn't work
My code:
from PIL import ImageGrab
from PIL import ImageOps
import pydirectinput
import pyautogui
import keyboard
import time
from numpy import *
test1 = (1400, 720)
test2 = (890, 420)
store = (1150, 420)
time.sleep(1.5)
def main():
# pyautogui.write("t")
# pyautogui.write("/emote angry")
# pyautogui.press("enter")
pyautogui.moveTo(store)
time.sleep(1)
pyautogui.rightClick()
pydirectinput.rightClick()
main()
i've tried with both modules but none of them worked for me, and i have tried with other games and the click works

How to run Python script with a custom button

I want to run the Python script when I press the button. This code only opens the script when I click the button.
import sys
import os
import tkinter
top=tkinter.Tk()
def helloCallBack():
os.system('img.py')
B=tkinter.Button(top,text="Run",command= helloCallBack)
B.pack()
top.mainloop()
How to make it run the img.py
button=Button(top, text="Run",command=helloCallBack)
This will run the function that you define fine.
If you want a python script to appear
def helloCallBack():
os.system('python img.py')

How to hide console when displaying an image with Tkinter

I have a simple code block that displays an image when the user press a button. When I save the script with .py extension, there is console at the background so I decided to save it as .pyw to hide it. Here is my code;
from tkinter import *
from PIL import Image
def open_image():
im = Image.open("tobi.jpg")
im.show()
root = Tk()
root.geometry("800x600+400+300")
buton = Button(root)
buton.config(text = "Show the image", command = open_image, activebackground = "yellow", bg = "lightgreen")
buton.pack()
mainloop()
I don't see cmd at the background since I save it as .pyw. However, when I click the button, just before opening the image I see console for a short time, then it dissappears. How can I avoid this, I want to hide console completely,
I dont know how to do this through pure tk but if subprocess is an option then you can do the following. Not a very good solution, since you have to use the subprocess module just to open an image... but anyways....
import tkinter as tk
import subprocess as s
root = tk.Tk()
def open_image():
s.call(["tobi.jpg"], shell=True)
button = Button(root)
button.config(text="Show the Image", command=open_image, activebackground="yellow", bg="lightgreen")
button.pack()
root.mainloop()
alternatively you could use os and use os.system("start my_file_name.jpg")
(assuming windows here)
With os.system the console will show but only very briefly.
Really doing the same thing, opening with PIL is just slower than others, so you see the console for a longer period.
U can use the following code:`
import win32console
import win32gui
win=win32console.GetConsoleWindow() # For closing command window
win32gui.ShowWindow(win,0)
This will close the cmd window at start itself, and will not show again. The cmd window may show for a very little time at first, as a blink, then it will not show. u can save in .py extention.
here the full code:`
from Tkinter import *
from PIL import Image
import win32console
import win32gui
win=win32console.GetConsoleWindow() # For closing command window
win32gui.ShowWindow(win,0)
def open_image():
im = Image.open("tobi.jpg")
im.show()
root = Tk()
root.geometry("800x600+400+300")
buton = Button(root)
buton.config(text = "Show the image", command = open_image, activebackground = "yellow", bg = "lightgreen")
buton.pack()
mainloop()

Refocusing Tkinter image window

Script2 displays an image and and closes the image after spacebar is being pressed. Script2 works perfectly alone.
Unfortunately when I use script1 to launch script2, I have to click/refocus the image window before I'm able to close the image with spacebar.
I've tried using win32gui module to refocus generated image window with separate script (focus.py). If I run focus.py by myself when the image is being displayed, I'm able to just press the spacebar and image window closes. However I've not been able to import focus.py script to script2.py succesfully (so that I would only have script1.py and script2.py.
script1:
action = raw_input("Pick a scenario: ")
if action == "1":
execfile("script2.py")
else:
print "Try again."
return self
script2:
import os, sys
import Tkinter
from PIL import Image, ImageTk
def close_window(event):
event.widget.quit()
root = Tkinter.Tk()
root.bind("<space>", close_window)
imagefile = "image1.png"
image1 = Image.open(imagefile)
root.geometry('%dx%d' % (image1.size[0],image1.size[1]))
tkpi = ImageTk.PhotoImage(image1)
label_image = Tkinter.Label(root, image=tkpi)
label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])
root.mainloop()
focus.py
import win32gui
tk = win32gui.FindWindow(None, 'tk')
win32gui.SetForegroundWindow(tk)

Categories