python通过手指触摸爬取改变图片大小
时间: 2023-06-28 19:13:37 浏览: 90
一个手指滑动改变图片的大小
4星 · 用户满意度95%
要通过手指触摸改变图片大小,你需要使用一个图形界面库(例如Tkinter或PyQt)来创建一个窗口,然后在窗口中显示图片,并通过鼠标事件来控制图片大小。
以下是一个使用Tkinter的示例代码:
```python
import tkinter as tk
from PIL import Image, ImageTk
class App:
def __init__(self, master):
self.master = master
self.image = Image.open("image.jpg")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas = tk.Canvas(self.master, width=self.image.width, height=self.image.height)
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
self.canvas.pack()
self.canvas.bind("<Button-1>", self.on_click)
self.canvas.bind("<B1-Motion>", self.on_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_release)
self.scale = 1.0
self.start_x = None
self.start_y = None
def on_click(self, event):
self.start_x = event.x
self.start_y = event.y
def on_drag(self, event):
if self.start_x is not None and self.start_y is not None:
delta_x = event.x - self.start_x
delta_y = event.y - self.start_y
self.scale += delta_y / 100.0
if self.scale < 0.1:
self.scale = 0.1
elif self.scale > 10.0:
self.scale = 10.0
new_width = int(self.image.width * self.scale)
new_height = int(self.image.height * self.scale)
resized_image = self.image.resize((new_width, new_height))
self.photo = ImageTk.PhotoImage(resized_image)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
self.canvas.configure(width=new_width, height=new_height)
def on_release(self, event):
self.start_x = None
self.start_y = None
root = tk.Tk()
app = App(root)
root.mainloop()
```
这个示例代码会在窗口中显示一张名为"image.jpg"的图片,并允许你通过鼠标拖动来改变图片大小。拖动过程中,会通过Pillow库来重新调整图片大小并更新界面。
阅读全文