cuốn sách gpt4 ai đã làm

python - 如何在不保存的情况下在python窗口中显示图像/屏幕截图

In lại Tác giả: Walker 123 更新时间:2023-11-28 18:00:25 27 4
mua khóa gpt4 Nike

我想在新的 tkinter 窗口 (TopLevel) 中显示我的屏幕截图,但我不想将其保存在电脑上。当我保存它时它工作正常但是当我尝试从内存加载屏幕截图时出现错误:图像不存在。

我的主窗口是root = Tk()

我从按钮调用这个函数:

def screenshot():
x = 500
y = 500
im1 = pyautogui.screenshot(region=(x, y, 100, 100))
im1.save('test.png')

New = Toplevel(root)
im1 = ImageTk.PhotoImage(Image.open("test.png"))
image1 = Label(New, image = im1)
image1.image = im1
image1.place(x=0, y=0)

这很好用,但是当我尝试这个时:

def screenshot():
x = 500
y = 500
im1 = pyautogui.screenshot(region=(x, y, 100, 100))

New = Toplevel(root)
image1 = Label(New, image = im1)
image1.image = im1
image1.place(x=0, y=0)

我得到了错误:

_tkinter.TclError: image "" doesn't exist

如何在不保存屏幕截图的情况下显示它?

编辑:我使用 os.remove 绕过了我自己的问题,代码如下所示:

def screenshot():
x = 500
y = 500
im1 = pyautogui.screenshot(region=(x, y, 100, 100))
im1.save('test.png')

New = Toplevel(root)
im1 = ImageTk.PhotoImage(Image.open('test.png'))
image1 = Label(New, image = im1)
image1.image = im1
image1.place(x=0, y=0)
os.remove('test.png')

这工作得很好,但我仍然对我是否可以在没有 im1.save 的情况下以某种方式完成它感兴趣。我是编程新手,所以如果我的解决方案没问题,请给我提示。

câu trả lời hay nhất

解决您的问题非常简单。来自错误信息 "_tkinter.TclError: image "" doesn't exist"我看到图像在 PIL 中格式。基本上你只需要导入 ImageTk 来自 PIL 库并执行 im1 = ImageTk.PhotoImage(im1)捕获屏幕后在您的函数中。

这是您的函数。

def screenshot():
x = 500
y = 500
# Can use ImageGrab to capture the screen as well
im1 = pyautogui.screenshot(region=(x, y, 100, 100))

New = Toplevel(root)
im1 = ImageTk.PhotoImage(im1) # converting PIL to support Tkinter format
image1 = Label(New, image = im1)
image1.image = im1
image1.place(x=0, y=0)

Nếu bạn sử dụng pyautogui 只是为了捕获屏幕,那么我会推荐 from PIL import ImageGrab, ImageTk 通过这种方式,您甚至不需要 pyautogui 并将其替换为 ImageGrab.grab(bbox)) .

Ví dụ:

from tkinter import *
import pyautogui
from PIL import ImageTk, ImageGrab

root = Tk()

def screenshot():
x = 500
y = 500

# ----They both show the same results-----

# im1 = pyautogui.screenshot(region=(x, y, 100, 100))
im1 = ImageGrab.grab((x, y, x+100, y+100)) # bbox = (x1, y1, x2, y2)

New = Toplevel(root)
im1 = ImageTk.PhotoImage(im1)
image1 = Label(New, image = im1)
image1.image = im1
image1.place(x=0, y=0)

Button(root, text='ScreenShot', padx=10, command=screenshot).pack(padx=10, pady=10)

mainloop()

关于python - 如何在不保存的情况下在python窗口中显示图像/屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56022618/

27 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress