如何定义图像对象

人气:946 发布:2022-10-16 标签: image python tkinter

问题描述

下面是一段代码,它从sqlite3获取图像路径,调整其大小以匹配标签/帧大小,并将其显示在tkinter图形用户界面上。如果变量仅在启动之后创建,我不知道或不记得如何定义该变量。

我的意思是,我在ttk.treeview中有一个记录列表。每条记录都在数据库中插入了一个图像路径。当我在树视图中单击某个项目时,所选内容将激活函数PREVIEW_IMAGE(),然后调整图像大小以适应图形用户界面上的确切框架大小,然后显示它。

这里的问题是,在我单击树上的记录之前,变量&Quot;FINAL_IMAGE&QOOT;为空,因此当我启动图形用户界面时,该变量未被定义,并且图形用户界面失败。

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import sqlite3


def preview_image():
    global img_link1, final_image

    Find path for selected record.
    conn = sqlite3.connect('Equipment.db')
    c = conn.cursor()
    query = "SELECT c_ipath FROM items WHERE itemID LIKE '%" + record_value + "%'"
    c.execute(query)
    img_link = c.fetchone()


    c.close()
    conn.close()

    image = Image.open(img_link)
    img_link1 = image.copy()
    final_image = ImageTk.PhotoImage(image)


def resize_image(event):
    new_width = event.width
    new_height = event.height
    img = img_link1.resize((new_width, new_height))
    photo = ImageTk.PhotoImage(img)
    img_label.config(image=photo)
    img_label.image = photo  # avoid garbage collection


root = tk.Tk()
root.title("Title")
root.geometry('600x600')

# --------------------------------------- Tab 1 Image Preview -------------------------------
section3 = tk.Frame(root, background="black")
section3.place(x=10, y=10, height=460, width=500)

img_label = ttk.Label(section3, image=final_image)
img_label.bind('<Configure>', resize_image)
img_label.pack(fill=tk.BOTH, expand=tk.YES)

root.mainloop()

解决方案可能非常简单和明显,但我看不出来。

推荐答案

在acw1668的帮助下,我用一个函数解决了这个问题:我从树视图中选择一条记录。这将从数据库中拉出图像的文件路径。使用文件路径,我即时调整图像大小,并将其放入画布中。每次我单击TreeView上的记录时,它都会运行PREVIEW_IMAGE(事件)函数,并使用适合框架高度的调整后的图像来更改img_canvas中的图像。这对我很管用,也可能对其他人有帮助。

下面的注释中列出了acw1668中指明的更正。不要忘记将";Final_img";设置为全局。

def preview_image(event):
    global final_img
    # Find path for selected record.
    conn = sqlite3.connect(conndb.data_source)
    c = conn.cursor()
    query = "SELECT c_ipath FROM items WHERE itemID LIKE '%" + record_value + "%'"
    c.execute(query)

    img_link = c.fetchone()

    c.close()
    conn.close()

    baseheight = 460
    img = Image.open(img_link[0])
    hpercent = (baseheight / float(img.size[1]))
    wsize = int((float(img.size[0]) * float(hpercent)))
    img_resized = img.resize((wsize, baseheight), Image.ANTIALIAS)
    
    final_img = ImageTk.PhotoImage(img_resized)
    img_canvas.itemconfigure(image_item, image=final_img)


# --- GUI ----

root = tk.Tk()
root.title("Title")
root.geometry('1120x980+500+20')

section3 = tk.Frame(root, background="black")
section3.place(x=10, y=510, height=460, width=1100)

img_canvas = tk.Canvas(section3, bg="black", highlightthickness=0)
img_canvas.pack(fill=tk.BOTH, expand=tk.YES)
image_item = img_canvas.create_image(1100/2, 460/2, anchor=tk.CENTER)

root.mainloop()

387