1 回答

TA貢獻1796條經驗 獲得超4個贊
如評論中所述,最好是使用單個 GUI 工具包,因此您需要為 Qt 重寫代碼或使用 tkinter 重寫剪切代碼。我不太了解 Qt,所以我無法幫助您選擇第一個選項。然而,屏幕截圖實際上是使用 PIL 截取的,而不是某些 Qt 特定方法,因此可以在 tkinter 中重寫截圖代碼。
您所需要的只是一個包含帶有可拖動矩形的畫布的全屏頂層,就像在Tkinter 中使用鼠標事件繪制矩形一樣。使頂層全屏:toplevel.attributes('-fullscreen', True)
頂層需要部分透明,這可以通過toplevel.attributes('-alpha', <value>)
.?我正在使用 Linux(帶有 XFCE 桌面環境),我需要添加toplevel.attributes('-type', 'dock')
以使透明度起作用。
全部放在一個類中,這給出:
import sys
import tkinter as tk
from PIL import ImageGrab
import cv2
import numpy as np
class MyWidget(tk.Toplevel):
? ? def __init__(self, master):
? ? ? ? super().__init__(master)
? ? ? ? self.configure(cursor='cross')
? ? ? ? if sys.platform == 'linux':
? ? ? ? ? ? self.attributes('-type', 'dock')? # to make transparency work in Linux
? ? ? ? self.attributes('-fullscreen', True)
? ? ? ? self.attributes('-alpha', 0.3)
? ? ? ? self.canvas = tk.Canvas(self, bg='white')
? ? ? ? self.canvas.pack(fill='both', expand=True)
? ? ? ? self.begin_x = 0
? ? ? ? self.begin_y = 0
? ? ? ? self.end_x = 0
? ? ? ? self.end_y = 0
? ? ? ? self.canvas.create_rectangle(0, 0, 0, 0, outline='gray', width=3, fill='blue', tags='snip_rect')
? ? ? ? self.canvas.bind('<ButtonPress-1>', self.mousePressEvent)
? ? ? ? self.canvas.bind('<B1-Motion>', self.mouseMoveEvent)
? ? ? ? self.canvas.bind('<ButtonRelease-1>', self.mouseReleaseEvent)
? ? ? ? print('Capture the screen...')
? ? def mousePressEvent(self, event):
? ? ? ? self.begin_x = event.x
? ? ? ? self.begin_y = event.y
? ? ? ? self.end_x = self.begin_x
? ? ? ? self.end_y = self.begin_y
? ? ? ? self.canvas.coords('snip_rect', self.begin_x, self.begin_y, self.end_x, self.end_y)
? ? def mouseMoveEvent(self, event):
? ? ? ? self.end_x = event.x
? ? ? ? self.end_y = event.y
? ? ? ? self.canvas.coords('snip_rect', self.begin_x, self.begin_y, self.end_x, self.end_y)
? ? def mouseReleaseEvent(self, event):
? ? ? ? self.destroy()
? ? ? ? self.master.update_idletasks()
? ? ? ? self.master.after(100)? # give time for screen to be refreshed so as not to see the blue box on the screenshot
? ? ? ? x1 = min(self.begin_x, self.end_x)
? ? ? ? y1 = min(self.begin_y, self.end_y)
? ? ? ? x2 = max(self.begin_x, self.end_x)
? ? ? ? y2 = max(self.begin_y, self.end_y)
? ? ? ? img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
? ? ? ? self.img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
? ? ? ? cv2.imshow('Captured Image', self.img)
? ? ? ? cv2.waitKey(0)
if __name__ == '__main__':
? ? root = tk.Tk()
? ? tk.Button(root, text='Snip', command=lambda: MyWidget(root)).pack()
? ? root.mainloop()
添加回答
舉報