请给出一段完整的python代码,要求运行后打开一个主窗口,主窗口内有多个按钮,按钮1点击后打开窗口1用于选择文件,文件选择后窗口1自动关闭,并在主窗口中显示窗口1选择的图片。点击按钮2后打开窗口2,窗口2要求有一个滑动条对主窗口界面的图片进行无损的放大缩小,并用两条滑动条来调整图片在窗口2中的位置。
时间: 2023-06-16 17:03:09 浏览: 61
这里提供一份基于tkinter模块的Python代码,实现了主窗口内有两个按钮,点击第一个按钮可以选择图片并在主窗口中显示,点击第二个按钮可以打开一个新的窗口,实现对图片的放大缩小和位置调整。
```python
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.title("Main Window")
self.img_path = None
self.img_label = tk.Label(self)
self.img_label.pack()
select_button = tk.Button(self, text="Select Image", command=self.select_image)
select_button.pack()
zoom_button = tk.Button(self, text="Zoom Image", command=self.zoom_image)
zoom_button.pack()
def select_image(self):
self.img_path = filedialog.askopenfilename(title="Select Image", filetypes=(("Image files", "*.jpg;*.jpeg;*.png"),))
if self.img_path:
img = Image.open(self.img_path)
img = img.resize((400, 400), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)
self.img_label.config(image=photo)
self.img_label.image = photo
def zoom_image(self):
if self.img_path:
zoom_window = ZoomWindow(self.img_path)
zoom_window.mainloop()
class ZoomWindow(tk.Toplevel):
def __init__(self, img_path):
super().__init__()
self.title("Zoom Window")
self.img_path = img_path
self.img = Image.open(self.img_path)
self.width, self.height = self.img.size
self.scale_var = tk.DoubleVar(value=1.0)
self.x_var = tk.IntVar(value=0)
self.y_var = tk.IntVar(value=0)
self.canvas = tk.Canvas(self, width=400, height=400)
self.canvas.pack()
self.scale_slider = tk.Scale(self, from_=0.1, to=2.0, resolution=0.1, orient=tk.HORIZONTAL, label="Zoom", variable=self.scale_var, command=self.update_image)
self.scale_slider.pack()
self.x_slider = tk.Scale(self, from_=-self.width, to=self.width, orient=tk.HORIZONTAL, label="X", variable=self.x_var, command=self.update_image)
self.x_slider.pack()
self.y_slider = tk.Scale(self, from_=-self.height, to=self.height, orient=tk.HORIZONTAL, label="Y", variable=self.y_var, command=self.update_image)
self.y_slider.pack()
self.update_image()
def update_image(self, event=None):
scale = self.scale_var.get()
x_offset = self.x_var.get()
y_offset = self.y_var.get()
img = self.img.resize((int(self.width*scale), int(self.height*scale)), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(img)
self.canvas.delete("all")
self.canvas.create_image(self.width/2+x_offset, self.height/2+y_offset, image=photo)
self.canvas.image = photo
if __name__ == "__main__":
app = MainWindow()
app.mainloop()
```
运行该代码后,会打开一个主窗口,包含"Select Image"和"Zoom Image"两个按钮。点击"Select Image"按钮会弹出文件选择框,选择一个图片后,图片会在主窗口中显示。点击"Zoom Image"按钮会打开一个新的窗口,包含一个滑动条用于缩放图片,两个滑动条用于调整图片位置。在调整完毕后,点击窗口右上角的关闭按钮即可返回主窗口。