使用 tkinter 版本8.6 来写一个bmp图片展示窗(允许滚动条上下左右滚动查看大图片),另点击展示窗中的图片时显示点击的坐标demo
时间: 2023-05-26 15:05:37 浏览: 93
python tkinter canvas 显示图片的示例
以下是使用 tkinter 版本 8.6 编写的 BMP 图片展示窗的 demo。
```
import tkinter as tk
from tkinter import filedialog
class BMPViewer(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.init_ui()
def init_ui(self):
self.master.title('BMP Viewer')
self.grid(sticky="NSEW")
# 创建菜单
menubar = tk.Menu(self.master)
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="打开", command=self.open_file)
menubar.add_cascade(label="文件", menu=file_menu)
self.master.config(menu=menubar)
# 创建滚动条
self.vbar = tk.Scrollbar(self.master, orient=tk.VERTICAL)
self.hbar = tk.Scrollbar(self.master, orient=tk.HORIZONTAL)
self.vbar.grid(row=0, column=1, sticky="NS")
self.hbar.grid(row=1, column=0, sticky="EW")
# 创建图片展示窗口
self.canvas = tk.Canvas(self.master, width=400, height=300, bd=0,
xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)
self.canvas.grid(row=0, column=0, sticky="NSEW")
self.canvas.bind("<Button-1>", self.show_click_position)
self.master.grid_rowconfigure(0, weight=1)
self.master.grid_columnconfigure(0, weight=1)
def open_file(self):
file_path = filedialog.askopenfilename(title="选择BMP文件",
filetypes=(("BMP文件", "*.bmp"), ("All Files", "*.*")))
if file_path:
self.load_image(file_path)
def load_image(self, file_path):
# 从 BMP 文件加载图像并显示
with open(file_path, 'rb') as f:
header = f.read(54)
width = int.from_bytes(header[18:22], byteorder='little')
height = int.from_bytes(header[22:26], byteorder='little')
bits_per_pixel = int.from_bytes(header[28:30], byteorder='little')
image_data = f.read()
self.image = tk.PhotoImage(data=image_data)
self.canvas.config(scrollregion=(0, 0, width, height))
self.canvas.create_image(0, 0, image=self.image, anchor=tk.NW)
# 设置滚动条的范围和步进
self.vbar.config(command=self.canvas.yview, from_=0, to=height)
self.hbar.config(command=self.canvas.xview, from_=0, to=width)
def show_click_position(self, event):
x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
print("点击位置坐标: ({}, {})".format(int(x), int(y)))
if __name__ == '__main__':
root = tk.Tk()
app = BMPViewer(root)
app.mainloop()
```
运行该程序后,可以通过“文件”菜单打开 BMP 图像文件,展示窗口支持滚动条上下左右滚动查看大图片。
展示窗口中的图像支持点击,并在控制台输出点击位置的坐标。
下面是示例截图:
![BMP Viewer Demo](https://cdn.mathpix.com/snip/images/PvC0f-w247gGEJhHEIJHjr8TRvGzxR0DVyvscHnstXQ.original.fullsize.png)
阅读全文