Tkinter报错
Tkinter截图程序报错Exception in Tkinter callback
Traceback (most recent call last):
File "c:\Users\h_qiy\AppData\Local\Programs\Python\Python313\Lib\tkinter\__init__.py", line 2068, in __call__
return self.func(*args)
~~~~~~~~~^^^^^^^
File "D:\Users\python-user\ImageGrab\main.py", line 12, in get_keys
if event.keysym == "F1": full_scr(); print("full")
~~~~~~~~^^
File "D:\Users\python-user\ImageGrab\main.py", line 19, in full_scr
screenshot.save(f"{image_dir}ScreenShot{datetime.now().__str__()}.png")
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\h_qiy\AppData\Local\Programs\Python\Python313\Lib\site-packages\PIL\Image.py", line 2583, in save
fp = builtins.open(filename, "w+b")
OSError: Invalid argument: 'D://ImageGrab/ScreenShots/ScreenShot2025-08-24 00:31:28.245790.png' 您好!您的Tkinter截图程序报错是因为文件路径或文件名中包含无效字符。具体来说:
1. 路径中使用 "D://" 可能不正确(Windows中应使用 "D:/" 或 "D:\\")。
2. 文件名中的日期时间包含空格和冒号,这些在Windows文件名中是非法字符。
解决方案:
- 使用 os.path.join() 来处理路径,确保跨平台兼容。
- 使用 strftime() 格式化日期时间,避免非法字符(例如用下划线替换)。
- 确保保存目录存在(必要时创建它)。
修改后的代码示例:
import os
from datetime import datetime
from PIL import ImageGrab
# 定义截图保存目录(使用正斜杠或双反斜杠)
image_dir = "D:/ImageGrab/ScreenShots/"# 或 "D:\\ImageGrab\\ScreenShots\\"
def full_scr():
screenshot = ImageGrab.grab()
# 检查并创建目录
if not os.path.exists(image_dir):
os.makedirs(image_dir)
# 生成安全的文件名
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"ScreenShot{timestamp}.png"
full_path = os.path.join(image_dir, filename)
screenshot.save(full_path)
print("截图已保存:", full_path)
关键修改:
- 使用 os.makedirs() 确保目录存在。
- 文件名中的时间部分用下划线连接(如 "2025-08-24_00-31-28"),避免非法字符。
如果问题仍然存在,请检查 image_dir 的定义是否正确(例如,不要有多余的斜杠)。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 本帖最后由 1q23w31 于 2025-8-24 06:28 编辑
D://ImageGrab/ScreenShots/ScreenShot2025-08-24 00:31:28.245790.png
文件名在windows中由于非法无法创建,具体创建规则如下
https://blog.csdn.net/Dontla/article/details/135200176#:~:text=1.1%20%E9%81%BF%E5%85%8D%E4%BD%BF%E7%94%A8%E7%89%B9%E6%AE%8A%E5%AD%97%E7%AC%A61.2%20%E9%99%90%E5%88%B6%E6%96%87%E4%BB%B6%E5%90%8D%E9%95%BF%E5%BA%A6 1. 路径中使用 "D://" 可能不正确(Windows中应使用 "D:/" 或 "D:\\")。
2. 文件名中的日期时间包含空格和冒号,这些在Windows文件名中是非法字符。
解决方案:
- 使用 os.path.join() 来处理路径,确保跨平台兼容。
- 使用 strftime() 格式化日期时间,避免非法字符(例如用下划线替换)。
- 确保保存目录存在(必要时创建它)。
修改后的代码示例:
import os
from datetime import datetime
from PIL import ImageGrab
# 定义截图保存目录(使用正斜杠或双反斜杠)
image_dir = "D:/ImageGrab/ScreenShots/"# 或 "D:\\ImageGrab\\ScreenShots\"
def full_scr():
screenshot = ImageGrab.grab()
# 检查并创建目录
if not os.path.exists(image_dir):
os.makedirs(image_dir)
# 生成安全的文件名
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"ScreenShot{timestamp}.png"
full_path = os.path.join(image_dir, filename)
screenshot.save(full_path)
print("截图已保存:", full_path) 某一个“天” 发表于 2025-8-24 09:34
1. 路径中使用 "D://" 可能不正确(Windows中应使用 "D:/" 或 "D:\\")。
2. 文件名中的日期时间包含空格 ...
别抄FishC的好吗{:10_290:} 1q23w31 发表于 2025-8-24 06:25
文件名在windows中由于非法无法创建,具体创建规则如下
感谢感谢{:10_275:}{:10_275:}{:10_275:}
页:
[1]