Tkinter Canvas画布不能正常显示

 在用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博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值