首页 > 解决方案 > 如何让 asksaveasfilename 将文件仅保存为图像并在文件目录中访问?

问题描述

我目前正在尝试在 python 中开发一个软件解决方案,该解决方案具有截取屏幕截图然后保存的功能。

到目前为止,我能够使asksaveasfilename对话框出现,将其命名为类似test.png并成功保存它,但是当我打开文件目录以打开文件本身时,Windows 无法识别它并说文件已“移动或被删除”。

问题是,我如何使它只能将文件保存为.pngor.jpg然后正确保存,以便将其作为文件目录中的文件进行访问?

import tkinter as tk
from tkinter.filedialog import asksaveasfilename
import pyautogui as pyg
table = tk.Tk()
def screenshot():
    x = table.winfo_rootx()
    y = table.winfo_rooty()
    w = table.winfo_width()
    h = table.winfo_height()
    data = [("All Files", "*.*")]
    tablescreenshot = pyg.screenshot(region=(x,y,w,h))
    tablescreenshot = asksaveasfilename(filetypes = data, defaultextension=data)
for i in range(0,3):
   for j in range(0,3):
      cell = tk.Entry(table,width=10,font=('Verdana',10))
      cell.grid(row=i,column=j)

snap = tk.Button(table,text="Screenshot",command=screenshot)
snap.grid(row=i+1,column=j)

table.mainloop()

标签: pythontkinter

解决方案


您的代码中存在问题:

  • 对屏幕截图图像和输出文件名使用相同的变量,因此图像将丢失
  • 从不调用任何函数将屏幕截图图像保存到输出文件名

以下是修改后的代码以解决上述问题:

import tkinter as tk
from tkinter.filedialog import asksaveasfilename
import pyautogui as pyg

table = tk.Tk()

def screenshot():
    x = table.winfo_rootx()
    y = table.winfo_rooty()
    w = table.winfo_width()
    h = table.winfo_height()
    data = [("Image Files", "*.png *.jpg")] # look up only PNG and JPG files
    tablescreenshot = pyg.screenshot(region=(x,y,w,h))
    # use another name for the output filename
    filename = asksaveasfilename(filetypes=data, defaultextension=data)
    if filename:
        # save the image to the output filename
        tablescreenshot.save(filename)

for i in range(0,3):
   for j in range(0,3):
      cell = tk.Entry(table, width=10, font=('Verdana',10))
      cell.grid(row=i, column=j)

snap = tk.Button(table, text="Screenshot", command=screenshot)
snap.grid(row=i+1, column=j)

table.mainloop()

推荐阅读