我该如何运行一个tkinter应用程序,该应用程序没有获得重点,但始终处于最重要的位置?
我正在使用一个库来输入字符,就好像它们是从键盘输入的一样,我想构建一个tkinter应用程序,向用户显示各种字符(虚拟键盘),但为了输入字符感兴趣的应用程序必须具有焦点,并且我希望虚拟键盘保持在顶部(而无需占据焦点)。
这就是我尝试过的方法,在这段代码中,我在编写字符之前将窗口最小化,因此在编写字符时将关注的应用程序放在焦点上,然后再次显示该窗口:
from pynput.keyboard import Key, Controller
import tkinter as tk
import time
keyboard = Controller()
########################################################################
class MyApp(object):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
self.root = parent
self.root.title("Special Characters")
self.frame = tk.Frame(parent)
self.frame.bind("<Enter>", self.onHover)
self.frame.pack()
btn01 = tk.Button(self.frame, text="á", command=lambda: self.printChar('á')).grid(row=0,column=0)
btn02 = tk.Button(self.frame, text="é", command=lambda: self.printChar('é')).grid(row=0,column=1)
btn03 = tk.Button(self.frame, text="í", command=lambda: self.printChar('í')).grid(row=0,column=2)
btn04 = tk.Button(self.frame, text="ó", command=lambda: self.printChar('ó')).grid(row=1,column=0)
btn05 = tk.Button(self.frame, text="ú", command=lambda: self.printChar('ú')).grid(row=1,column=1)
btn06 = tk.Button(self.frame, text="ñ", command=lambda: self.printChar('ñ')).grid(row=1,column=2)
btn07 = tk.Button(self.frame, text="Á", command=lambda: self.printChar('Á')).grid(row=2,column=0)
btn08 = tk.Button(self.frame, text="É", command=lambda: self.printChar('É')).grid(row=2,column=1)
btn09 = tk.Button(self.frame, text="Í", command=lambda: self.printChar('Í')).grid(row=2,column=2)
btn10 = tk.Button(self.frame, text="Ó", command=lambda: self.printChar('Ó')).grid(row=3,column=0)
btn11 = tk.Button(self.frame, text="Ú", command=lambda: self.printChar('Ú')).grid(row=3,column=1)
btn12 = tk.Button(self.frame, text="Ñ", command=lambda: self.printChar('Ñ')).grid(row=3,column=2)
btnClose = tk.Button(self.frame, text="Close", command=self.closeWindow).grid(row=4,column=0,columnspan=3,rowspan=1)
#----------------------------------------------------------------------
def onHover(self, event):
self.root.focus_force()
def printChar(self, character):
""""""
self.root.withdraw()
time.sleep(0.1)
keyboard.press(character)
keyboard.release(character)
time.sleep(0.1)
self.root.deiconify()
def closeWindow(self):
self.root.destroy()
#----------------------------------------------------------------------
if __name__ == "__main__":
root = tk.Tk()
root.geometry("300x200")
root.call('wm', 'attributes', '.', '-topmost', '1')
app = MyApp(root)
root.mainloop()