在用Tkinter Canvas画布时发现图片不能正常显示
原代码:
def open_file():
# 从本地选择一个文件
global file_path
file_path = filedialog.askopenfilename()
if file_path != '':
try:
lb1.config(text='成功选择一张图片,路径为:' + file_path)
# 加载图片文件
image = Image.open(str(file_path)).resize((200, 200))
global img
# 将图片转换为Tkinter可以显示的图片格式
img = ImageTk.PhotoImage(image)
canvas.create_image(30, 10,image=img,anchor=CENTER)
canvas.create_line(30, 10, 98, 113, fill='red', width=3)
canvas.update() # 更新画布
except Exception as e:
lb1.config(text='出错了:' + str(e))
else:
lb1.config(text='您没有选择任何文件')
if __name__ == '__main__':
global file_path
file_path = ''
root = Tk()
root.title('yolov7目标检测')
root.geometry("1000x500")
# 创建画布
canvas = Canvas(root, height=400, width=400, bg='white')
canvas.grid(row=1, column=0, padx=5, pady=10)
# 选择按钮
choose_button = Button(root,text='选择文件',relief=RAISED,command=open_file)
choose_button.grid(row=0,column=0,padx=5)
lb1 = Label(root,text='')
lb1.grid(row=0,column=1,padx=5)
print(str(file_path))
#显示窗口
root.mainloop()
找了好多方法没用,最后把img改成全局变量能正常显示
结果 :
参考文章:
Python之解决tkinter.PhotoImage不显示图片的问题 Python3_tk.photoimage-CSDN博客