tkinter画布无法显示图像:
新增的窗口无法显示图像,显示图像不存在
import re
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk, ImageDraw, ImageFont
from tkinter import filedialog
import ttkbootstrap as ttk
wind_index = 1
ImageFrame_list = []
class ImageFrame(ttk.LabelFrame):
def __init__(self, parent, title):
super().__init__(parent, text=title, padding="5 5 5 5")#,height=height,)
self.parent = parent
self.img = None
self.zoom_factor = 0.5
self.canvas = tk.Canvas(self, highlightthickness=0)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.open_image_button = tk.Button(self, text="打开图片", command=self.open_image,pady=2)#canvas.delete(photo_id)
self.open_image_button.pack(side=tk.TOP, fill=tk.X,pady=2)
self.open_image_button = tk.Button(self, text="原始图片", command=self.open_original_img,
pady=2) # canvas.delete(photo_id)
self.open_image_button.pack(side=tk.TOP, fill=tk.X, pady=2)
self.original_image_button = tk.Button(self, text="原始图片",command=self.open_original_img,pady=2) # canvas.delete(photo_id)
self.open_image_button.pack(side=tk.TOP, fill=tk.X, pady=2)
self.add_new_window_button = tk.Button(self, text="增加窗口", command=self.add_new_window,pady=2) # canvas.delete(photo_id)
self.add_new_window_button.pack(side=tk.TOP, fill=tk.X, pady=2)
self.updateCanvas = True
self.filename=""
self.imgwidth = None
def title_number_plus1(self,A):
# 找到数字,使用group()方法 capture 它
m = re.search('\d+', A)
# 如果找到了数字
if m:
# 通过group()取出数字
num = int(m.group())
# 将数字加1
num += 1
# replace()方法用增加1后的数字替换原来的数
A = re.sub('\d+', str(num), A)
else:
A = A + '1'
return A
def add_new_window(self):
global wind_index,ImageFrame_list
self.add_new_window_button.pack_forget()
wind_index += 1
win_title = self.title_number_plus1(self['text'])
# image_frame_i = 'image_frame_' + str(wind_index)
new_wind_i = 'new_wind_' + str(wind_index)
print('new_wind_i:', new_wind_i)
self.new_wind_i = tk.Tk()
self.new_wind_i.geometry("500x500")
self.image_frame = ImageFrame(self.new_wind_i, win_title)
self.image_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
add_new_window_button = tk.Button(self.image_frame, text="关闭窗口", command=self.delete_win,
pady=2) # canvas.delete(photo_id)
add_new_window_button.pack(side=tk.TOP, fill=tk.X, pady=2)
# self.new_wind.protocol("WM_DELETE_WINDOW")
ImageFrame_list.append(self.image_frame)
self.new_wind_i.protocol("WM_DELETE_WINDOW", self.delete_win)
print('add_new-wind_wind_index:',wind_index)
def delete_win(self):
# self.image_frame_i.pack_forget()
global wind_index,ImageFrame_list
new_wind_i = ImageFrame_list[wind_index-2].master
new_wind_i.destroy()
wind_index -= 1
try:
self.add_new_window_button = tk.Button(self, text="增加窗口", command=self.add_new_window,pady=2) # canvas.delete(photo_id)
self.add_new_window_button.pack(side=tk.TOP, fill=tk.X, pady=2)
except:
pass
def open_original_img(self):
if self.filename_open:
self.open_image_file(self.filename_open)
else:
print("图片不存在")
def open_image(self):
self.filename_open = tk.filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg *.jpeg *.png *.bmp")])
if self.filename_open:
print(wind_index)
print('self.filename_open',self.filename_open)
self.open_image_file(self.filename_open)
# 将画布移动到窗口中间位置
def open_image_file(self, filename):
global wind_index,ImageFrame_list
print("更新canvas")
# print(self.canvas.coords(filename))
print(filename)
# self.center_canvas()
self.filename = filename
img1 = Image.open(filename)
img = img1.copy()
self.imgwidth = img1.width
self.imgheight = img1.height
#============================
win_width = self.winfo_width() #窗口宽度、高度
win_height = self.winfo_height()
canvas_width = self.canvas.winfo_width() #画布宽度、高度
canvas_height = self.canvas.winfo_height()
canvas_ratio = canvas_width / canvas_height
win_img_ratio = win_width / win_height
pic_ratio = self.imgwidth / self.imgheight # original_w,original_h
# 尺寸自适应,参考了 https://blog.csdn.net/superwulei/article/details/83534301 这篇文章
if pic_ratio > canvas_ratio:
w = canvas_width
h = canvas_height / pic_ratio
elif pic_ratio < canvas_ratio:
h = canvas_height
w = canvas_height * pic_ratio
elif pic_ratio == canvas_ratio :
w = canvas_width
h = canvas_height
resized_img = img.resize((int(w), int(h)),Image.LANCZOS)
center_x = int(win_width / 2)
center_y = int(win_height / 2)
self.img = ImageTk.PhotoImage(resized_img)
print('wind_index:',wind_index)
# try:
self.canvas.create_image(center_x, center_y, anchor=tk.CENTER,image=self.img)#anchor=tk.CENTER,
self.canvas.config(scrollregion=(0, 0, win_width , win_height))
# except:
# print("显示图像失败")
class App(tk.Tk):
def __init__(self):
super().__init__()
# self.style = Style(self)
self.style = ttk.Style()
# self.style.theme_use()
self.title("Object Detection")
self.geometry(("%dx%d+0+0" % (self.winfo_screenwidth(), self.winfo_screenheight())))
print(self.winfo_screenheight())
self.image_frame_1 = ImageFrame(self, "拿货")#,int(self.winfo_screenheight() /2))
self.image_frame_1.pack(side=tk.LEFT, fill=tk.BOTH,expand=True)#fill=tk.X,
self.image_frame_2 = ImageFrame(self, "退货")#,int(self.winfo_screenheight() /2))
self.image_frame_2.pack(side=tk.RIGHT,fill=tk.BOTH,expand=True)# fill=tk.BOTH,
if __name__ == "__main__":
app = App()
app.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\ProgramData\anaconda3\envs\pythonProject_yolo\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\Python\pythonProject_yolo\yolov5\测试.py", line 96, in open_image
self.open_image_file(self.filename_open)
File "D:\Python\pythonProject_yolo\yolov5\测试.py", line 134, in open_image_file
self.canvas.create_image(center_x, center_y, anchor=tk.CENTER,image=self.img)#anchor=tk.CENTER,
File "D:\ProgramData\anaconda3\envs\pythonProject_yolo\lib\tkinter\__init__.py", line 2790, in create_image
return self._create('image', args, kw)
File "D:\ProgramData\anaconda3\envs\pythonProject_yolo\lib\tkinter\__init__.py", line 2776, in _create
return self.tk.getint(self.tk.call(
_tkinter.TclError: image "pyimage1" doesn't exist