我已经获取了链接问题的代码并使其工作。请参见下面的代码:
from tkinter import *
from PIL import Image, ImageTk
import win32gui
import win32con
def setClickthrough(hwnd):
print("setting window properties")
try:
styles = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
styles = win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, styles)
win32gui.SetLayeredWindowAttributes(hwnd, 0, 255, win32con.LWA_ALPHA)
except Exception as e:
print(e)
# Dimensions
width = 1920 #self.winfo_screenwidth()
height = 1080 #self.winfo_screenheight()
root = Tk()
root.geometry('%dx%d' % (width, height))
root.title("Applepie")
root.attributes('-transparentcolor', 'white', '-topmost', 1)
root.config(bg='white')
root.attributes("-alpha", 0.25)
root.wm_attributes("-topmost", 1)
bg = Canvas(root, width=width, height=height, bg='white')
setClickthrough(bg.winfo_id())
frame = ImageTk.PhotoImage(file="example.png")
bg.create_image(1920/2, 1080/2, image=frame)
bg.pack()
root.mainloop()
您的尝试和工作示例之间的重要区别似乎是使用hwnd
了画布而不是窗口。
我不能完全按照您的意愿去做,但我提供了一些代码来输出这个结果并希望能满足您的需求。额外的代码只是删除了装饰 ( overrideredirect(1)
) 并将窗口大小调整为 img 大小,并将其放在屏幕中间。:

from tkinter import *
from PIL import Image, ImageTk
import win32gui
import win32con
def setClickthrough(hwnd):
print("setting window properties")
try:
styles = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
styles = win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, styles)
win32gui.SetLayeredWindowAttributes(hwnd, 0, 255, win32con.LWA_ALPHA)
except Exception as e:
print(e)
def size_position_for_picture():
bbox = bg.bbox(img_id)
w,h = bbox[2]-bbox[0],bbox[3]-bbox[1]
x,y = sw/2-w/2,sh/2-h/2
root.geometry('%dx%d+%d+%d' % (w,h, x,y))
bg.configure(width=w,height=h)
root = Tk()
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
root.overrideredirect(1)
root.attributes("-alpha", 0.75)
root.attributes('-transparentcolor', 'white', '-topmost', 1)
bg = Canvas(root,bg='white',highlightthickness=0)
root.config(bg='white')
setClickthrough(bg.winfo_id())
frame = ImageTk.PhotoImage(file="example.png")
img_id = bg.create_image(0,0, image=frame,anchor='nw')
bg.pack()
size_position_for_picture()
setClickthrough(bg.winfo_id())
root.mainloop()