【发布时间】:2023-01-04 22:24:18
【问题描述】:
我有一个名为 crop.py 的 python 脚本,当我通过 visual studio code 运行它时,它不会报告错误,但什么也没有发生,就像脚本期望其他命令起作用一样。 该代码允许您选择一个图像,根据四个点裁剪它,然后保存它。 这里的代码:
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
class App:
def __init__(self, root):
self.root = root
self.image = None
self.image_tk = None
self.points = []
# create a canvas for the image
self.canvas = tk.Canvas(root, width=600, height=600)
self.canvas.pack()
# bind the left mouse button click to the canvas
self.canvas.bind("<Button-1>", self.select_point)
# create a button to open an image file
self.open_button = tk.Button(root, text="Open Image", command=self.open_image)
self.open_button.pack()
# create a button to crop the image
self.crop_button = tk.Button(root, text="Crop Image", command=self.crop_image)
self.crop_button.pack()
def select_point(self, event):
# add the selected point to the list
self.points.append((event.x, event.y))
# draw a circle at the selected point
self.canvas.create_oval(event.x - 5, event.y - 5, event.x + 5, event.y + 5, fill="red")
# if we have selected four points, unbind the left mouse button
if len(self.points) == 4:
self.canvas.unbind("<Button-1>")
def open_image(self):
# open a file dialog to select an image file
file_path = filedialog.askopenfilename()
# open the image file
self.image = Image.open(file_path)
# resize the image to fit the canvas
self.image = self.image.resize((600, 600))
# convert the image to a PhotoImage object
self.image_tk = ImageTk.PhotoImage(self.image)
# draw the image on the canvas
self.canvas.create_image(0, 0, anchor="nw", image=self.image_tk)
def crop_image(self):
# check if we have selected four points
if len(self.points) != 4:
return
# get the top-left and bottom-right points
x1, y1 = self.points[0]
x2, y2 = self.points[1]
x3, y3 = self.points[2]
x4, y4 = self.points[3]
# find the top-left and bottom-right coordinates of the cropped image
left = min(x1, x2, x3, x4)
top = min(y1, y2, y3, y4)
right = max(x1, x2, x3, x4)
bottom = max(y1, y2, y3, y4)
# crop the image
cropped_image= image.crop((left,top,right,bottom))
#save the cropped image
cropped_image.save(filedialog.asksaveasfilename())
我没有使用 python 太久了,如果问题很简单,我很抱歉。 有人可以告诉我如何运行代码吗? (打开图像,裁剪等。)
【问题讨论】:
-
您只是定义了一个类,但您从未真正使用过它。为了创建一个类的实例,你必须像调用函数一样调用它在里面参数:
my_app = App(root)(别忘了初始化root=tk.Tk() -
您将获得的最佳建议:从小处着手。您甚至不知道类是什么(没关系,我们都从某个地方开始),但您的开场白是……制作图像编辑应用程序?那不会发生。从在终端或其他东西上打印“hello world”开始。我从事专业编程已有十多年了,我不会从一个如此复杂的应用程序开始学习一门新语言。你也不应该。
标签: python function class init