我正在开发一个 Kivy 应用程序,可以让您编辑图像。为此,用户通过文件浏览器(来自 plyer 的文件选择器)选择图像,选择文件后,应该显示图像的路径并复制文件。文件的路径显示在应用程序中,但我的问题是复制文件不起作用。当我将文件复制到提供的目录中时,Python 崩溃并告诉我该目录不存在,当我将文件复制到其他地方进行测试时,Python 不会崩溃,但不会复制任何内容,就好像它不存在一样不阅读代码行。
代码(image_editing.py):
class LayoutSelectImagePath(BoxLayout):
path_to_image = StringProperty("")
def select_image(self):
# the file chooser return a list on selected files
path_image = filechooser.open_file(title="choose an image",
filters=[("Image", "*.jpg", "*.png", "*.ico", "*.bmp")])
if len(path_image) > 0:
self.path_to_image = path_image[0] # show the path in the UI (OK)
self.copy_image()
def copy_image(self):
file_base = open(self.path_to_image, "rb") #read the image file
image_base = file_base.read()
file_base.close()
image_name = path.basename(self.path_to_image) # get the name of the image file
file_to_work = open(f"image_work_dir/{image_name}", "wb") # write the image in a new image file in a new dir (NOT OK)
file_to_work.write(image_base)
file_to_work.close()
我已经尝试过使用shutil、os.system()复制文件的其他方法,但每次复制都不起作用。项目。
错误代码(仅当我想复制到image_work_dir目录时):
File "C:\Users\Trist\PycharmProjects\dev_image_edit\image_editing.py", line 28, in copy_image file_to_work = open(f"image_work_dir/{image_name}", "wb") # 将图像写入新图像文件中在新目录中(不行)FileNotFoundError:[Errno 2]没有这样的文件或目录:'image_work_dir/test.jpg'
我尝试复制文件和/或写入文件,但没有任何效果
我发现了这个bug,plyer的文件选择器改变了程序的工作目录,这意味着不再找到程序真实工作目录中的文件和文件夹。为了解决这个问题,我使用 os.getcwd() 检索当前工作目录,然后在使用文件选择器后,我使用 os.chdir() 和我之前检索到的值将工作目录重置为其默认值。
代码:
app_work_dir = getcwd()
path_image = filechooser.open_file(title="choose an image",
filters=[("Image", "*.jpg", "*.png", "*.ico", "*.bmp")])
chdir(app_work_dir)