python - 如何让 asksaveasfilename 将文件仅保存为图像并在文件目录中访问?
问题描述
我目前正在尝试在 python 中开发一个软件解决方案,该解决方案具有截取屏幕截图然后保存的功能。
到目前为止,我能够使asksaveasfilename
对话框出现,将其命名为类似test.png
并成功保存它,但是当我打开文件目录以打开文件本身时,Windows 无法识别它并说文件已“移动或被删除”。
问题是,我如何使它只能将文件保存为.png
or.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()
解决方案
您的代码中存在问题:
- 对屏幕截图图像和输出文件名使用相同的变量,因此图像将丢失
- 从不调用任何函数将屏幕截图图像保存到输出文件名
以下是修改后的代码以解决上述问题:
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()
推荐阅读
- spring-data-jpa - Mockito fails for Spring data JPA Page interface
- android - 如何制作透明玻璃彩色背景
- java - How to run Spring Boot application with Apache Flink on JDK 11?
- mysql - MySQL CTE 递归与加入另一个表
- c# - DockPanel ImageOption.Image 未显示图像
- c# - Apache Ignite .Net (2.8.1) 条目 ICacheEntryProcessor 写入失败
- certificate - Kubernetes: how to replace to the 3 Intermediate CAs when they are expired
- javascript - 如何从对象数组中找到最近的日期,然后添加新字段并在反应中返回数组
- android - Android Share cookie with Webview and Volley request
- vue.js - Load external url into a div