def __initHotkeys(self): # self.__globalHotKCListener = CGlobalHotKCListener() # self.__globalHotKCListener.start() # self.__globalHotKCListener.addTrigger.connect(self.__bStartDescription) # self.__globalHotKCListener.cancelTrigger.connect(self.__bCancelDescription) self.__GlobalHotkeyListener = SystemHotkey() self.__GlobalHotkeyListener.register(('control', 'd'), callback=self.__bStartDescription) self.__GlobalHotkeyListener.register(('control', 's'), callback=self.__bCancelDescription)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.window = Window self.hk = SystemHotkey(consumer=self.sys_hotkey_handler, check_queue_interval=0.001) self.hk.register(['f7'], self.req_system_get) # JFT self.queue = queue.Queue() Clock.schedule_interval(lambda e: self.check_queue(), 0.01)
def __init__(self, parent=None, flags=Qt.WindowFlags()): super().__init__(parent=parent, flags=flags) self.hk_capture, self.hk_exit = SystemHotkey(), SystemHotkey() self.hk_capture.register( ('alt', 'c'), callback=lambda x: self.send_key_event("capture")) self.hk_exit.register(('alt', 'q'), callback=lambda x: self.send_key_event("exit")) self.sig_keyhot.connect(self.hotkey_process)
class HotkeyManager(QtCore.QObject): triggered = QtCore.Signal(object) def __init__(self, parent=None): super().__init__(parent) self.keys = [] self.hk = SystemHotkey() def addKey(self, keyCombo): self.hk.register(keyCombo, callback=self.triggered.emit)
def __init__(self, window): super().__init__(window) # 2. 设置我们的自定义热键响应函数 self.sig_keyhot.connect(self.MKey_pressEvent) # 3. 初始化两个热键 self.hk_start, self.hk_stop = SystemHotkey(), SystemHotkey() # 4. 绑定快捷键和对应的信号发送函数 self.hk_start.register( ('alt', 'c'), callback=lambda x: self.send_key_event("enText")) self.hk_stop.register(('alt', 'v'), callback=lambda x: self.send_key_event("deText"))
def __init__(self, log_path): self.thread = None self.path = log_path self.collector = BaseCollector(self) self.lock = Lock() self.p = None self.running = True self.hk = SystemHotkey() self.hk.register(('control', 'alt', 'z'), callback=self.delete_last_img) self.images = []
class GlobalHotkey(QObject): pressed = Signal() def __init__(self, parent: Optional[QObject]): super().__init__(parent) self._hk = SystemHotkey() def is_registered(self, key): key = set(key) return any(set(k) == key for k in self._hk.keybinds) def register(self, key_sequence: Optional[QKeySequence]): key = self.convert_key_sequence(key_sequence) if key and self.is_registered(key): logger.debug("Already registered: %s", key) return self.unregister() if key_sequence and not key_sequence.isEmpty(): logger.info("Registering hotkey: %s", key) # If this fails, we get a system_hotkey.SystemRegisterError # exception, but in a different thread - so we can neither catch it # here nor is it logged. self._hk.register(key, callback=self._callback) @staticmethod def convert_key_sequence(key_sequence: QKeySequence): if not key_sequence or key_sequence.isEmpty(): return None # Restrict to the first key key_sequence = QKeySequence(key_sequence[0]) # Convert to format for SystemHotkey - simple approach, may not be # sufficient. key = key_sequence.toString(QKeySequence.PortableText).split("+") key = [part.lower() for part in key] if "meta" in key: key.remove("meta") key = ["super"] + key return key def unregister(self): for key in self._hk.keybinds: logger.info("Unregistering hotkey: %s", (key, )) self._hk.unregister(key) def _callback(self, *_, **__): self.pressed.emit()
def __init__(self, frame): self.g_settings = GeneralSettingsData() self.frame = frame super(TaskBarIcon, self).__init__() self.set_icon(TRAY_ICON) # self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down) self.Bind(wx.adv.EVT_TASKBAR_LEFT_DCLICK, self.configure_wallpapers) # Initialize display data # get_display_data() wpproc.refresh_display_data() # profile initialization self.job_lock = Lock() self.repeating_timer = None self.pause_item = None self.is_paused = False # if sp_logging.DEBUG: # sp_logging.G_LOGGER.info("START Listing profiles for menu.") self.list_of_profiles = list_profiles() # if sp_logging.DEBUG: # sp_logging.G_LOGGER.info("END Listing profiles for menu.") # Should now return an object if a previous profile was written or # None if no previous data was found if STARTUP_PROFILE: self.active_profile = open_profile(STARTUP_PROFILE) else: self.active_profile = read_active_profile() if self.active_profile: wpproc.G_ACTIVE_PROFILE = self.active_profile.name self.start_prev_profile(self.active_profile) # if self.active_profile is None: # sp_logging.G_LOGGER.info("Starting up the first profile found.") # self.start_profile(wx.EVT_MENU, self.list_of_profiles[0]) # self.hk = None # self.hk2 = None if self.g_settings.use_hotkeys is True: try: # import keyboard # https://github.com/boppreh/keyboard # This import is here to have the module in the class scope from system_hotkey import SystemHotkey self.hk = SystemHotkey(check_queue_interval=0.05) self.hk2 = SystemHotkey(consumer=self.profile_consumer, check_queue_interval=0.05) self.seen_binding = set() self.register_hotkeys() except ImportError as excep: sp_logging.G_LOGGER.info( "WARNING: Could not import keyboard hotkey hook library, \ hotkeys will not work. Exception: %s", excep) if self.g_settings.show_help is True: config_frame = ConfigFrame(self) help_frame = HelpFrame()
def __init__(self, ScriptPath=None): super().__init__() self.Cfg = Configuration() self.attributes('-type', 'dock') self.geometry("0x0+0+0") self.hk = SystemHotkey() self.hk.register(('control', 'shift', 'h'), callback=self.showhide) self.doingInput = False self.allDirs = None self.readAllDirsFromFile() dirFindThread = threading.Thread(target=self.updateAllDirs) dirFindThread.daemon = True dirFindThread.start()
def __init__(self): # 1. 简单的绘制一个窗口 self.version = 'V1.0' super(common_ipc, self).__init__() self.setupUi(self) self.update_tbrow.setText("版本已更新,请去 https://gitee.com/Setless7/PathOfTrade/release_version 下载") self.price_lwidget = cc.price_lwidget() self.price_lwidget.addprice_lwidget(self) self.price_lwidget.add_item(('40 chaos', '100', '1小时前')) self.keyBorder = KeyBorder() # 2. 设置我们的自定义热键响应函数 self.sig_keyhot.connect(self.key_press_event) # 3. 初始化两个热键 self.hk_start, self.hk_stop = SystemHotkey(), SystemHotkey() # 4. 绑定快捷键和对应的信号发送函数 self.hk_start.register(('control', 'd'), callback=lambda x: self.send_key_event("start")) self.hk_stop.register(('control', '2'), callback=lambda x: self.send_key_event("stop"))
def __init__(self, settings: ApplicationSettings, mappings: Dict[str, Dict[str, Tuple[str, Callable]]]): """ Creates keybindings for shortcuts stores in GSettings. The list of settings cannot be changed after created. Pass a map of (setting_id -> callback) """ super().__init__() self._mappings = mappings self._settings = settings self._active_shortcuts = dict() # see https://github.com/timeyyy/system_hotkey from system_hotkey import SystemHotkey self._keybinder = SystemHotkey() self.rebind_all()
class common_ipc(QMainWindow, Ui_main_form): # 定义一个热键信号 sig_keyhot = pyqtSignal(str) def __init__(self): # 1. 简单的绘制一个窗口 self.version = 'V1.0' super(common_ipc, self).__init__() self.setupUi(self) self.update_tbrow.setText("版本已更新,请去 https://gitee.com/Setless7/PathOfTrade/release_version 下载") self.price_lwidget = cc.price_lwidget() self.price_lwidget.addprice_lwidget(self) self.price_lwidget.add_item(('40 chaos', '100', '1小时前')) self.keyBorder = KeyBorder() # 2. 设置我们的自定义热键响应函数 self.sig_keyhot.connect(self.key_press_event) # 3. 初始化两个热键 self.hk_start, self.hk_stop = SystemHotkey(), SystemHotkey() # 4. 绑定快捷键和对应的信号发送函数 self.hk_start.register(('control', 'd'), callback=lambda x: self.send_key_event("start")) self.hk_stop.register(('control', '2'), callback=lambda x: self.send_key_event("stop")) # 热键处理函数 def key_press_event(self, i_str): time.sleep(0.05) self.keyBorder.key_up('d') time.sleep(0.05) self.keyBorder.key_up('ctrl') time.sleep(0.05) self.keyBorder.key_down_up_team('ctrl', 'c') self.showMinimized() self.showNormal() # 热键信号发送函数(将外部信号,转化成qt信号) def send_key_event(self, i_str): self.sig_keyhot.emit(i_str) def get_clipboard_text(self): clipboard.OpenClipboard() text = clipboard.GetClipboardData(win32con.CF_TEXT) clipboard.CloseClipboard() return text.decode('GBK')
def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) #去掉边框|任务栏|窗口置顶 self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint) self.setupUi(self) self.screenWidget = QtWidgets.QWidget() self.screenWidget.setObjectName("screenWidget") self.screenWidget.setWindowFlags(Qt.FramelessWindowHint) self.centralWidget = self.findChild(QtWidgets.QWidget, 'centralwidget') self.centralWidget.setWindowFlags(Qt.FramelessWindowHint) self.toolWidget = self.findChild(QtWidgets.QWidget, 'toolWidget') self.toolWidget.setWindowFlags(Qt.FramelessWindowHint) #设置按钮的槽函数 self.btn_i2u.clicked.connect(lambda: self.i2u()) btn_bdfy = self.findChild(QtWidgets.QToolButton, 'baidu') btn_i2t = self.findChild(QtWidgets.QToolButton, 'img2txt') btn_copy = self.findChild(QtWidgets.QToolButton, 'copy') #背景透明 self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # 2. 设置我们的自定义热键响应函数 self.sig_keyhot.connect(self.MKey_pressEvent) # 3. 初始化两个热键 self.hk_start, self.hk_stop = SystemHotkey(), SystemHotkey() # 4. 绑定快捷键和对应的信号发送函数 self.hk_start.register(('control', '1'), callback=lambda x: self.send_key_event("0")) self.hk_stop.register(('control', '2'), callback=lambda x: self.send_key_event("1")) esc = QAction('', triggered=self.esc) esc.setShortcut('esc') self.addAction(esc) self.screenWidget.addAction(esc) # 系统托盘 self.systemtray = SystemTray(self)
class Translater(QMainWindow, Ui_MainWindow): # 定义一个热键信号 sig_keyhot = pyqtSignal(str) def __init__(self, parent=None): # 继承主窗口类 super(Translater, self).__init__(parent) # 设置应用图标 # self.setWindowIcon(QIcon('source/book.png')) # 获取屏幕对象 self.screen = QDesktopWidget().screenGeometry() self.setupUi(self) # 仅支持最小化以及关闭按钮 self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) # 去掉 toolbar 右键菜单 self.setContextMenuPolicy(Qt.NoContextMenu) # self.textEdit.text() self.textEdit.setText("test value") self.translate.clicked.connect(self.translate_click) self.sig_keyhot.connect(self.translate_click) self.hk = SystemHotkey() self.hk.register(('control', 'shift', 'c'), callback=lambda x: self.send_key_event("start")) def translate_click(self): if self.checkBox.checkState() == Qt.Checked: rawtext = format_str(getCopyText()) else: rawtext = self.textEdit.toPlainText() content = bfs.translate1(rawtext, 'en', 'zh') content = content['trans_result'][0]['dst'] self.textEdit_2.setText(content) # 热键信号发送函数(将外部信号,转化成qt信号) def send_key_event(self, i_str): self.sig_keyhot.emit(i_str)
def main(): global stay_looped hk = SystemHotkey() hk.register(('control', 'f8'), callback=lambda x: _capture_and_detect()) hk.register(('control', 'f12'), callback=lambda y: _stop_loop()) while stay_looped: time.sleep(1) sys.exit('exiting...')
class UncrumpledWindow(KeyBinder, Screen, Style, Responses, Requests): supported_bind_handlers = ('on_key_down',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.window = Window self.hk = SystemHotkey(consumer=self.sys_hotkey_handler, check_queue_interval=0.001) self.hk.register(['f7'], self.req_system_get) # JFT self.queue = queue.Queue() Clock.schedule_interval(lambda e: self.check_queue(), 0.01) def check_queue(self): try: func = self.queue.get(block=False) except queue.Empty: pass else: try: func() except Exception as err: # An error happend over on the backend :( import pdb;pdb.set_trace() def run_in_main(self, func): self.queue.put(func) # This is run in another thread, errors here do not get propogated due to async.. def sys_hotkey_handler(self, event, hotkey, args): self.active_profile = 'default' program, pid, = peasoup.process_exists() # TODO rename this func profile = self.active_profile # Mainly for testing, a hotkey has bound it's own callback if args[0]: self.run_in_main(args[0][0]) else: self.run_in_main(lambda: self.req_hotkey_pressed( profile, program, hotkey))
def main(): print("=================================================") print("|| QUIC SEARCH ||") print("|| Author: Jokin ||") print("|| Version: v1.3.1 ||") print("=================================================") # 写音效文件 if (os.path.exists('./0.mp3') == False): print('wir') with open('./0.mp3', 'wb') as f: f.write(base64.b64decode(S0)) f.close if (os.path.exists('./1.mp3') == False): with open('./1.mp3', 'wb') as f: f.write(base64.b64decode(S1)) f.close if (os.path.exists('./2.mp3') == False): with open('./2.mp3', 'wb') as f: f.write(base64.b64decode(S2)) f.close if (os.path.exists('./3.mp3') == False): with open('./3.mp3', 'wb') as f: f.write(base64.b64decode(S3)) f.close # 中心节点选择 改快捷键操作 select_node() print("-> 初始化中,请稍候...") # 注册热键 hotkey hk = SystemHotkey() hk.register(('control', 'shift', 'alt', 'z'), callback=changemode) hk.register(('control', 'shift', 'alt', 's'), callback=send_note) hk.register(('control', 'shift', 'alt', 'x'), callback=receive_note) # 获取白名单 get_whitelist() print("-> 初始化完成!") # 授权 login() # 模式选择 默认0模式 # select_mode() # 获取数据库列表 get_databaselist() # 选择数据库 database = select_database() # print(database) # 获取数据库 get_database(database) # 剪贴板监听 clipboard_listen()
def main(): global note_map print("疯物之诗琴 by luern0313") print("世界线变动率:1.0.1.7546855") print("\n如果要使用快捷键演奏:") print("ctrl + shift + 数字键 :开始演奏对应的曲目") print("ctrl + shift + s : 停止演奏") read_configure() while True: try: global file_list file_list = os.listdir("midi/") print("选择要打开的文件(热键对应前十个):") print("\n".join( [str(i) + "、" + file_list[i] for i in range(len(file_list))])) hk = SystemHotkey(consumer=play_hot) for i in range(10): hk.register(('control', 'shift', str(i)), i) hk2 = SystemHotkey() hk2.register(('control', 'shift', 's'), callback=stop_hot) midi = mido.MidiFile("midi/" + file_list[int(input("请输入文件前数字序号:"))]) print_split_line() tracks = midi.tracks base_note = get_base_note(tracks) if configure[ "lowest_pitch_name"] == -1 else configure["lowest_pitch_name"] note_map = { note[i] + base_note * 12: key[i] for i in range(len(note)) } time.sleep(1) for msg in midi.play(): if msg.type == "note_on" or msg.type == "note_off": note_list = get_note(msg.note) for n in note_list: if n in note_map: if msg.type == "note_on": if vk[note_map[n]] in pressed_key: release_key(vk[note_map[n]]) press_key(vk[note_map[n]]) elif msg.type == "note_off": release_key(vk[note_map[n]]) except Exception as e: print("ERR:" + str(e))
def __init__(self, parent=None): # 继承主窗口类 super(Translater, self).__init__(parent) # 设置应用图标 # self.setWindowIcon(QIcon('source/book.png')) # 获取屏幕对象 self.screen = QDesktopWidget().screenGeometry() self.setupUi(self) # 仅支持最小化以及关闭按钮 self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) # 去掉 toolbar 右键菜单 self.setContextMenuPolicy(Qt.NoContextMenu) # self.textEdit.text() self.textEdit.setText("test value") self.translate.clicked.connect(self.translate_click) self.sig_keyhot.connect(self.translate_click) self.hk = SystemHotkey() self.hk.register(('control', 'shift', 'c'), callback=lambda x: self.send_key_event("start"))
def setHotKey(self): """ 设置全局热键 """ self.nextSongHotKey = SystemHotkey() self.lastSongHotKey = SystemHotkey() self.playHotKey = SystemHotkey() # callback会返回一个event参数,所以需要用lambda self.nextSongHotKey.register( ('f6', ), callback=lambda x: self.hotKeySlot(self.playlist.next)) self.lastSongHotKey.register( ('f4', ), callback=lambda x: self.hotKeySlot(self.playlist.previous)) self.playHotKey.register( ('f5', ), callback=lambda x: self.hotKeySlot(self.switchPlayState))
from system_hotkey import SystemHotkey hk = SystemHotkey() hk.register(('control', 'shift', 'h'), callback=lambda: print("Easy!"))
import glob import os from PIL import ImageGrab, Image import requests import json from pynput.keyboard import Key, Controller import shutil import pytesseract from ctypes import windll import time import webbrowser from base64 import b64encode import pyperclip from system_hotkey import SystemHotkey hk = SystemHotkey() toast = ToastNotifier() root = Tk() root.withdraw() keyboard = Controller() appdata = os.getenv('APPDATA') if not os.path.exists(appdata + r"\Screeny"): os.mkdir(appdata + r"\Screeny") if not os.path.exists(appdata + r"\Screeny\icon.ico"): shutil.copyfile("icon.ico", appdata + r"\Screeny\icon.ico")
import configparser from system_hotkey import SystemHotkey hk = SystemHotkey() hk.register(('control', 'alt', 'r'), callback=lambda x:OnHotkey()) import spotipy import spotipy.util as util import requests import time import sys import os def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) parser = configparser.ConfigParser() parser.read('config.ini') parser.read(resource_path('api.ini')) os.environ["SPOTIPY_CLIENT_ID"] = parser["api"]["SPOTIPY_CLIENT_ID"] os.environ["SPOTIPY_REDIRECT_URI"] = parser["api"]["SPOTIPY_REDIRECT_URI"] os.environ["SPOTIPY_CLIENT_SECRET"] = parser["api"]["SPOTIPY_CLIENT_SECRET"]
class MyMainWindow(QMainWindow, Ui_MainWindow, QObject): # 定义一个热键信号 sig_keyhot = pyqtSignal(str) def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) #去掉边框|任务栏|窗口置顶 self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint) self.setupUi(self) self.screenWidget = QtWidgets.QWidget() self.screenWidget.setObjectName("screenWidget") self.screenWidget.setWindowFlags(Qt.FramelessWindowHint) self.centralWidget = self.findChild(QtWidgets.QWidget, 'centralwidget') self.centralWidget.setWindowFlags(Qt.FramelessWindowHint) self.toolWidget = self.findChild(QtWidgets.QWidget, 'toolWidget') self.toolWidget.setWindowFlags(Qt.FramelessWindowHint) #设置按钮的槽函数 self.btn_i2u.clicked.connect(lambda: self.i2u()) btn_bdfy = self.findChild(QtWidgets.QToolButton, 'baidu') btn_i2t = self.findChild(QtWidgets.QToolButton, 'img2txt') btn_copy = self.findChild(QtWidgets.QToolButton, 'copy') #背景透明 self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # 2. 设置我们的自定义热键响应函数 self.sig_keyhot.connect(self.MKey_pressEvent) # 3. 初始化两个热键 self.hk_start, self.hk_stop = SystemHotkey(), SystemHotkey() # 4. 绑定快捷键和对应的信号发送函数 self.hk_start.register(('control', '1'), callback=lambda x: self.send_key_event("0")) self.hk_stop.register(('control', '2'), callback=lambda x: self.send_key_event("1")) esc = QAction('', triggered=self.esc) esc.setShortcut('esc') self.addAction(esc) self.screenWidget.addAction(esc) # 系统托盘 self.systemtray = SystemTray(self) def i2u(self): print('start i2u') res_im, res_txt = trans_img.generate_trans_img(img=self.cap_im.copy(), method='local') print(res_txt) cv2.imshow('', res_im) cv2.waitKey(0) @pyqtSlot() def esc(self): self.screenWidget.hide() self.hide() import sip try: self.screenLabel.deleteLater() sip.delete(self.screenLabel) except Exception as e: print('error') pass try: self.imgLabel.deleteLater() sip.delete(self.imgLabel) except Exception as e: print('delete imgLabel error') #装饰器接受的数据类型必须和信号量的数据类型保持一致 @pyqtSlot(int, int, int, int) def capture(self, x0, y0, w, h): y1 = y0 + h x1 = x0 + w print(x0, y0, x1, y1) #必须用copy,否则在使用im.data的时候会报错 self.cap_im = self.im[y0:y1, x0:x1].copy() height, width, depth = self.cap_im.shape self.esc() self.imgLabel = QLabel(self.centralWidget) self.imgLabel.resize(width, height) qimg = QImage(self.cap_im.data, width, height, width * depth, QImage.Format_RGB888) pixmap = QtGui.QPixmap(qimg).scaled(self.imgLabel.width(), self.imgLabel.height()) self.imgLabel.setPixmap(pixmap) self.imgLabel.move(0, 0) self.toolWidget.move(0, height - 30) self.centralWidget.raise_() self.toolWidget.raise_() self.resize(width, height) self.move(x0, y0) self.show() # 热键处理函数 def MKey_pressEvent(self, i_str): if i_str == '0': im = capture.capture() height, width, depth = im.shape self.im = im self.screenLabel = MyLabel(self.screenWidget) self.screenLabel.resize(width, height) self.screenLabel.msg.connect(self.capture) print(self.screenLabel.width(), self.screenLabel.height()) qimg = QImage(im.data, width, height, width * depth, QImage.Format_RGB888) pixmap = QtGui.QPixmap(qimg).scaled(self.screenLabel.width(), self.screenLabel.height()) self.screenLabel.setPixmap(pixmap) self.screenWidget.move(0, 0) self.screenWidget.showFullScreen() # 热键信号发送函数(将外部信号,转化成qt信号) def send_key_event(self, i_str): self.sig_keyhot.emit(i_str) print(i_str) #设置无边框移动 def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.m_flag = True self.m_Position = event.globalPos() - self.pos() # 获取鼠标相对窗口的位置 event.accept() self.setCursor(QCursor(Qt.OpenHandCursor)) # 更改鼠标图标 def mouseMoveEvent(self, QMouseEvent): if Qt.LeftButton and self.m_flag: self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置 QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.m_flag = False self.setCursor(QCursor(Qt.ArrowCursor))
def gui_init(): def get_score(): global last new_game = player_names() if last: if new_game.not_empty(): update_heros(last) else: last = None else: if new_game.not_empty(): clear() g = results('DOTA') render_text(g) show() last = g window.after(1000*60*3, show_heros, g) else: pass def show_heros(g): def render(): if g.enough_heros(): render_img(g) show() key_press('f11') key_press('f11') window.after(4000, render) def raise_above(): window.attributes("-topmost", True) def clear(): for l in img_labels: l.configure(text='', image='') for l in text_labels: l.configure(text='', image='') def loop(): get_score() window.after(3000, loop) def align_right(width, height): screen_width = window.winfo_screenwidth() size = '{}x{}+{}+{}'.format(width, height, screen_width-width, 0) window.geometry(size) window.update() def show(): global is_show align_right(MAX_WIDTH, MAX_HEIGHT) raise_above() is_show = False def hide(): global is_show align_right(0, 0) is_show = True def change_status(event): if is_show: show() else: hide() def init_heros(): with open('dict.txt', 'r', encoding='utf-8') as f: table = list(map(lambda x: x[0:-1].split(' '), f.readlines())) dic = {'default': tk.PhotoImage(file='static\\placehold.png')} for names in table: file_name = names[0] game_name = names[-1] photo = tk.PhotoImage(file='static\\' + file_name + '.png') dic[game_name] = photo dic[file_name] = photo return dic def render_text(game): def render_sco(): img_labels[6].configure(text='天灾', fg=SCO_COLOR) start = 7 for i in range(0, len(game.sco)): text_labels[i + start].configure(text=str(game.sco[i]), fg=SCO_COLOR) def render_sen(): img_labels[0].configure(text='近卫', fg=SEN_COLOR) start = 1 for i in range(0, len(game.sen)): text_labels[i + start].configure(text=str(game.sen[i]), fg=SEN_COLOR) render_sen() render_sco() def render_img(game): def render_sen(): start = 1 for i in range(0, len(game.sen)): hero = game.sen[i].hero if hero: img_labels[i + start].configure(image=HEROS[hero]) else: img_labels[i + start].configure(image=HEROS['default']) def render_sco(): start = 7 for i in range(0, len(game.sco)): hero = game.sco[i].hero if hero: img_labels[i + start].configure(image=HEROS[hero]) else: img_labels[i + start].configure(image=HEROS['default']) render_sen() render_sco() window = tk.Tk() window.title('09小秘书') HEROS = init_heros() img_labels = [] text_labels = [] for i in range(12): img = tk.Label(window, bg='black') img.grid(row=i, column=0) img_labels.append(img) text = tk.Label(window, font=('Microsoft YaHei', 10), anchor=tk.W, bg='black') text.grid(row=i, column=1, sticky=tk.W) text_labels.append(text) hk = SystemHotkey() hk.register(['f3'], callback=change_status) window.config(bg='black') window.overrideredirect(True) window.bind('<Motion>', lambda e: hide()) align_right(MAX_WIDTH, MAX_HEIGHT) window.after(3000, loop) window.mainloop()
def test_errors_raised_in_main(): hk = SystemHotkey() key = ('5',) cb = lambda e: print('hi') hk.register(key, callback=cb) try: hk.register(key, callback=cb) except SystemRegisterError: pass else: raise Exception('fail') hk.unregister(key) try: hk.unregister(key) except UnregisterError: pass else: raise Exception('fail') bad_key = ('badkey ..',) try: hk.register(bad_key, callback=cb) except InvalidKeyError: pass else: raise Exception('fail') try: hk.unregister(bad_key) except: pass else: raise Exception('fail')
def __init__(self, parent: Optional[QObject]): super().__init__(parent) self._hk = SystemHotkey()
def __init__(self, parent=None): super().__init__(parent) self.keys = [] self.hk = SystemHotkey()
def __init__(self): super().__init__() self.hk = SystemHotkey(consumer=self._hotkeyPressed) self._commandInvoked.connect(self.invokeCommand)
class TaskBarIcon(wx.adv.TaskBarIcon): """Taskbar icon and menu class.""" def __init__(self, frame): self.g_settings = GeneralSettingsData() self.frame = frame super(TaskBarIcon, self).__init__() self.set_icon(TRAY_ICON) self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down) # profile initialization self.job_lock = Lock() get_display_data() self.repeating_timer = None self.pause_item = None self.is_paused = False if sp_logging.DEBUG: sp_logging.G_LOGGER.info("START Listing profiles for menu.") self.list_of_profiles = list_profiles() if sp_logging.DEBUG: sp_logging.G_LOGGER.info("END Listing profiles for menu.") # Should now return an object if a previous profile was written or # None if no previous data was found self.active_profile = read_active_profile() self.start_prev_profile(self.active_profile) # if self.active_profile is None: # sp_logging.G_LOGGER.info("Starting up the first profile found.") # self.start_profile(wx.EVT_MENU, self.list_of_profiles[0]) # self.hk = None # self.hk2 = None if self.g_settings.use_hotkeys is True: try: # import keyboard # https://github.com/boppreh/keyboard # This import is here to have the module in the class scope from system_hotkey import SystemHotkey self.hk = SystemHotkey(check_queue_interval=0.05) self.hk2 = SystemHotkey(consumer=self.profile_consumer, check_queue_interval=0.05) self.seen_binding = set() self.register_hotkeys() except ImportError as excep: sp_logging.G_LOGGER.info( "WARNING: Could not import keyboard hotkey hook library, \ hotkeys will not work. Exception: %s", excep) if self.g_settings.show_help is True: config_frame = ConfigFrame(self) help_frame = HelpFrame() def register_hotkeys(self): """Registers system-wide hotkeys for profiles and application interaction.""" if self.g_settings.use_hotkeys is True: try: # import keyboard # https://github.com/boppreh/keyboard # This import allows access to the specific errors in this method. from system_hotkey import (SystemHotkey, SystemHotkeyError, SystemRegisterError, UnregisterError, InvalidKeyError) except ImportError as import_e: sp_logging.G_LOGGER.info( "WARNING: Could not import keyboard hotkey hook library, \ hotkeys will not work. Exception: %s", import_e) if "system_hotkey" in sys.modules: try: # Keyboard bindings: https://github.com/boppreh/keyboard # # Alternative KB bindings for X11 systems and Windows: # system_hotkey https://github.com/timeyyy/system_hotkey # seen_binding = set() # self.hk = SystemHotkey(check_queue_interval=0.05) # self.hk2 = SystemHotkey( # consumer=self.profile_consumer, # check_queue_interval=0.05) # Unregister previous hotkeys if self.seen_binding: for binding in self.seen_binding: try: self.hk.unregister(binding) if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Unreg hotkey %s", binding) except (SystemHotkeyError, UnregisterError, InvalidKeyError): try: self.hk2.unregister(binding) if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Unreg hotkey %s", binding) except (SystemHotkeyError, UnregisterError, InvalidKeyError): if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Could not unreg hotkey '%s'", binding) self.seen_binding = set() # register general bindings if self.g_settings.hk_binding_next not in self.seen_binding: try: self.hk.register(self.g_settings.hk_binding_next, callback=lambda x: self. next_wallpaper(wx.EVT_MENU), overwrite=False) self.seen_binding.add( self.g_settings.hk_binding_next) except (SystemHotkeyError, SystemRegisterError, InvalidKeyError): msg = "Error: could not register hotkey {}. \ Check that it is formatted properly and valid keys.".format( self.g_settings.hk_binding_next) sp_logging.G_LOGGER.info(msg) sp_logging.G_LOGGER.info(sys.exc_info()[0]) show_message_dialog(msg, "Error") if self.g_settings.hk_binding_pause not in self.seen_binding: try: self.hk.register(self.g_settings.hk_binding_pause, callback=lambda x: self. pause_timer(wx.EVT_MENU), overwrite=False) self.seen_binding.add( self.g_settings.hk_binding_pause) except (SystemHotkeyError, SystemRegisterError, InvalidKeyError): msg = "Error: could not register hotkey {}. \ Check that it is formatted properly and valid keys.".format( self.g_settings.hk_binding_pause) sp_logging.G_LOGGER.info(msg) sp_logging.G_LOGGER.info(sys.exc_info()[0]) show_message_dialog(msg, "Error") # try: # self.hk.register(('control', 'super', 'shift', 'q'), # callback=lambda x: self.on_exit(wx.EVT_MENU)) # except (SystemHotkeyError, SystemRegisterError, InvalidKeyError): # pass # register profile specific bindings self.list_of_profiles = list_profiles() for profile in self.list_of_profiles: if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Registering binding: \ %s for profile: %s", profile.hk_binding, profile.name) if (profile.hk_binding is not None and profile.hk_binding not in self.seen_binding): try: self.hk2.register(profile.hk_binding, profile, overwrite=False) self.seen_binding.add(profile.hk_binding) except (SystemHotkeyError, SystemRegisterError, InvalidKeyError): msg = "Error: could not register hotkey {}. \ Check that it is formatted properly and valid keys.".format(profile.hk_binding) sp_logging.G_LOGGER.info(msg) sp_logging.G_LOGGER.info(sys.exc_info()[0]) show_message_dialog(msg, "Error") elif profile.hk_binding in self.seen_binding: msg = "Could not register hotkey: '{}' for profile: '{}'.\n\ It is already registered for another action.".format(profile.hk_binding, profile.name) sp_logging.G_LOGGER.info(msg) show_message_dialog(msg, "Error") except (SystemHotkeyError, SystemRegisterError, UnregisterError, InvalidKeyError): if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Coulnd't register hotkeys, exception:") sp_logging.G_LOGGER.info(sys.exc_info()[0]) def profile_consumer(self, event, hotkey, profile): """Hotkey bindable method that starts up a profile.""" if sp_logging.DEBUG: sp_logging.G_LOGGER.info("Profile object is: %s", profile) self.start_profile(wx.EVT_MENU, profile[0][0]) def read_general_settings(self): """Refreshes general settings from file and applies hotkey bindings.""" self.g_settings = GeneralSettingsData() self.register_hotkeys() msg = "New settings are applied after an application restart. \ New hotkeys are registered." show_message_dialog(msg, "Info") def CreatePopupMenu(self): """Method called by WX library when user right clicks tray icon. Opens tray menu.""" menu = wx.Menu() create_menu_item(menu, "Open Config Folder", self.open_config) create_menu_item(menu, "Profile Configuration", self.configure_profiles) create_menu_item(menu, "Settings", self.configure_settings) create_menu_item(menu, "Reload Profiles", self.reload_profiles) menu.AppendSeparator() for item in self.list_of_profiles: create_menu_item(menu, item.name, self.start_profile, item) menu.AppendSeparator() create_menu_item(menu, "Next Wallpaper", self.next_wallpaper) self.pause_item = create_menu_item(menu, "Pause Timer", self.pause_timer, kind=wx.ITEM_CHECK) self.pause_item.Check(self.is_paused) menu.AppendSeparator() create_menu_item(menu, 'About', self.on_about) create_menu_item(menu, 'Exit', self.on_exit) return menu def set_icon(self, path): """Sets tray icon.""" icon = wx.Icon(path) self.SetIcon(icon, TRAY_TOOLTIP) def on_left_down(self, *event): """Allows binding left click event.""" sp_logging.G_LOGGER.info('Tray icon was left-clicked.') def open_config(self, event): """Opens Superpaper config folder, CONFIG_PATH.""" if platform.system() == "Windows": try: os.startfile(sp_paths.CONFIG_PATH) except BaseException: show_message_dialog( "There was an error trying to open the config folder.") elif platform.system() == "Darwin": try: subprocess.check_call(["open", sp_paths.CONFIG_PATH]) except subprocess.CalledProcessError: show_message_dialog( "There was an error trying to open the config folder.") else: try: subprocess.check_call(['xdg-open', sp_paths.CONFIG_PATH]) except subprocess.CalledProcessError: show_message_dialog( "There was an error trying to open the config folder.") def configure_profiles(self, event): """Opens profile configuration panel.""" config_frame = ConfigFrame(self) def configure_settings(self, event): """Opens general settings panel.""" setting_frame = SettingsFrame(self) def reload_profiles(self, event): """Reloads profiles from disk.""" self.list_of_profiles = list_profiles() def start_prev_profile(self, profile): """Checks if a previously running profile has been recorded and starts it.""" with self.job_lock: if profile is None: sp_logging.G_LOGGER.info("No previous profile was found.") else: self.repeating_timer = run_profile_job(profile) def start_profile(self, event, profile): """ Starts a profile job, i.e. runs a slideshow or a one time wallpaper change. If the input profile is the currently active profile, initiate a wallpaper change. """ if sp_logging.DEBUG: sp_logging.G_LOGGER.info("Start profile: %s", profile.name) if profile is None: sp_logging.G_LOGGER.info("start_profile: profile is None. \ Do you have any profiles in /profiles?") elif self.active_profile is not None: if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Check if the starting profile is already running: %s", profile.name) sp_logging.G_LOGGER.info("name check: %s, %s", profile.name, self.active_profile.name) if profile.name == self.active_profile.name: self.next_wallpaper(event) return 0 else: with self.job_lock: if (self.repeating_timer is not None and self.repeating_timer.is_running): self.repeating_timer.stop() if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Running quick profile job with profile: %s", profile.name) quick_profile_job(profile) if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Starting timed profile job with profile: %s", profile.name) self.repeating_timer = run_profile_job(profile) self.active_profile = profile write_active_profile(profile.name) if sp_logging.DEBUG: sp_logging.G_LOGGER.info("Wrote active profile: %s", profile.name) return 0 else: with self.job_lock: if (self.repeating_timer is not None and self.repeating_timer.is_running): self.repeating_timer.stop() if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Running quick profile job with profile: %s", profile.name) quick_profile_job(profile) if sp_logging.DEBUG: sp_logging.G_LOGGER.info( "Starting timed profile job with profile: %s", profile.name) self.repeating_timer = run_profile_job(profile) self.active_profile = profile write_active_profile(profile.name) if sp_logging.DEBUG: sp_logging.G_LOGGER.info("Wrote active profile: %s", profile.name) return 0 def next_wallpaper(self, event): """Calls the next wallpaper changer method of the running profile.""" with self.job_lock: if (self.repeating_timer is not None and self.repeating_timer.is_running): self.repeating_timer.stop() change_wallpaper_job(self.active_profile) self.repeating_timer.start() else: change_wallpaper_job(self.active_profile) def rt_stop(self): """Stops running slideshow timer if one is active.""" if (self.repeating_timer is not None and self.repeating_timer.is_running): self.repeating_timer.stop() def pause_timer(self, event): """Check if a slideshow timer is running and if it is, then try to stop/start.""" if (self.repeating_timer is not None and self.repeating_timer.is_running): self.repeating_timer.stop() self.is_paused = True if sp_logging.DEBUG: sp_logging.G_LOGGER.info("Paused timer") elif (self.repeating_timer is not None and not self.repeating_timer.is_running): self.repeating_timer.start() self.is_paused = False if sp_logging.DEBUG: sp_logging.G_LOGGER.info("Resumed timer") else: sp_logging.G_LOGGER.info("Current profile isn't using a timer.") def on_about(self, event): """Opens About dialog.""" # Credit for AboutDiaglog example to Jan Bodnar of # http://zetcode.com/wxpython/dialogs/ description = ( "Superpaper is an advanced multi monitor wallpaper\n" + "manager for Unix and Windows operating systems.\n" + "Features include setting a single or multiple image\n" + "wallpaper, pixel per inch and bezel corrections,\n" + "manual pixel offsets for tuning, slideshow with\n" + "configurable file order, multiple path support and more.") licence = ("Superpaper is free software; you can redistribute\n" + "it and/or modify it under the terms of the MIT" + " License.\n\n" + "Superpaper is distributed in the hope that it will" + " be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied" + " warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" + "See the MIT License for more details.") artists = "Icons kindly provided by Icons8 https://icons8.com" info = wx.adv.AboutDialogInfo() info.SetIcon(wx.Icon(TRAY_ICON, wx.BITMAP_TYPE_PNG)) info.SetName('Superpaper') info.SetVersion(__version__) info.SetDescription(description) info.SetCopyright('(C) 2019 Henri Hänninen') info.SetWebSite('https://github.com/hhannine/Superpaper/') info.SetLicence(licence) info.AddDeveloper('Henri Hänninen') info.AddArtist(artists) # info.AddDocWriter('Doc Writer') # info.AddTranslator('Tran Slator') wx.adv.AboutBox(info) def on_exit(self, event): """Exits Superpaper.""" self.rt_stop() wx.CallAfter(self.Destroy) self.frame.Close()
import configparser from system_hotkey import SystemHotkey hk = SystemHotkey() hk.register(('control', 'alt', 'r'), callback=lambda x: OnHotkey()) import spotipy import spotipy.util as util import requests import time import sys import os def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) parser = configparser.ConfigParser() parser.read('config.ini') parser.read(resource_path('api.ini')) os.environ["SPOTIPY_CLIENT_ID"] = parser["api"]["SPOTIPY_CLIENT_ID"] os.environ["SPOTIPY_REDIRECT_URI"] = parser["api"]["SPOTIPY_REDIRECT_URI"] os.environ["SPOTIPY_CLIENT_SECRET"] = parser["api"]["SPOTIPY_CLIENT_SECRET"]
#!/usr/bin/env python # coding: utf-8 from system_hotkey import SystemHotkey import pyperclip as pyclip import time # 剪贴板字符串处理 def StringProcess(self): # 读取字符串(剪贴板) read_text = pyclip.paste() # 字符串处理 output_text = read_text.replace("\r\n", " ") output_text = output_text.replace("\n", " ") output_text = output_text.replace("\r", " ") # 输出字符串(剪贴板) pyclip.copy(output_text) hk = SystemHotkey() hk.register(('control', 'shift', 'm'), callback=StringProcess) while (1): time.sleep(1000)