简体   繁体   English

如何在 tkinter python 的表中将 blob 显示为图像

[英]how to display blob as image in a table in tkinter python

I am trying to insert and retrieve image from MySQL database.I have inserted the image as BLOB (longblob).我正在尝试从 MySQL 数据库中插入和检索图像。我已将图像插入为 BLOB (longblob)。 When I am able to display it using image.show() but I want the image to be displayed in a table.当我能够使用image.show()显示它但我希望图像显示在表格中时。

I used treeview for this purpose.为此,我使用了 treeview。 But my table shows only BLOB objects.但我的表只显示 BLOB 对象。 It doesn't show any image.它不显示任何图像。

This is my code.这是我的代码。

from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
import mysql.connector
import io
from tkinter import ttk

root = Tk()

id = Entry(root, width=10, font=("Helvetica", 20), bd=3)
id.pack()

browse_button = Button(root,text ='Browse',command = lambda:open_file())
browse_button.pack()

display_button = Button(root,text ='display',command =lambda:display_file())
display_button.pack()

display_table_button = Button(root,text ='display Table',command =lambda:display_Table())
display_table_button.pack()

def display_Table():

    query = "SELECT * FROM image_db"
    person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
    cursor_variable = person.cursor()
    cursor_variable.execute(query)

    vertical_scrollbar = ttk.Scrollbar(root)
    vertical_scrollbar.pack(side=RIGHT, fill=Y)

    my_tree = ttk.Treeview(root, yscrollcommand= vertical_scrollbar.set)
    my_tree.pack()

    vertical_scrollbar.config(command= my_tree.yview)

    style = ttk.Style(root)
    style.theme_use("winnative")
    style.configure(".", font=("Helvetica", 11))
    style.configure("Treeview.Heading", font=("Helvetica", 11, "bold"))

    my_tree['columns'] = ("id", "data")
    my_tree.column("#0", width=0, stretch='NO')
    my_tree.column("id", width=50, anchor='w')
    my_tree.column("data", width=130, anchor='w')


    my_tree.heading("#0", anchor='w', text='Label')
    my_tree.heading("id", anchor='w', text="Id")
    my_tree.heading("data", anchor='w', text="Image")

    count = 0

    for record in cursor_variable:
        # print(record)
        my_tree.insert(parent='', index='end', iid=count, text='Parent',
                            values=(record[0], record[1]))
        count += 1

    person.close()


def display_file():

    id2 = id.get()
    person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
    cursor_variable = person.cursor()
    sql = "SELECT data FROM image_db WHERE id = '" + id2 + "'"
    cursor_variable.execute(sql)
    all_data = cursor_variable.fetchall()
    image = all_data[0][0]
    image = Image.open(io.BytesIO(image))
    image.show()
    person.commit()
    person.close()


def open_file():
    root.filename = filedialog.askopenfilename(initialdir="/Users/write/PycharmProjects/slider/img", title='Select a File',
                                               filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg'),
                                                          ('jpg files', '*.jpg')))
    my_label = Label(root, text=root.filename).pack()
    my_image = ImageTk.PhotoImage(Image.open(root.filename))
    path = root.filename
    id1 = id.get()


    person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
    cursor_variable = person.cursor()
    thedata = open(root.filename, 'rb').read()
    sql = "INSERT INTO image_db (id,data) VALUES ('" + id1 + "',%s)"
    cursor_variable.execute(sql, (thedata,))
    person.commit()
    person.close()


root.mainloop()

Any help is appreciated.任何帮助表示赞赏。

I have modified your display_Table() :我已经修改了您的display_Table()

  • set the rowheight of treeview to 50rowheight的行高设置为 50
  • set width of column "#0" to 100将“#0”列的width设置为 100
  • resize the retrieved image to fit the treeview cell调整检索到的图像大小以适合 treeview 单元格
def display_Table():
    ...
    style = ttk.Style(root)
    style.theme_use("winnative")
    style.configure(".", font=("Helvetica", 11))
    style.configure("Treeview.Heading", font=("Helvetica", 11, "bold"))
    style.configure("Treeview", rowheight=50) # set row height

    my_tree['columns'] = ("id",)
    my_tree.column("#0", width=100, stretch='NO') # set width
    my_tree.column("id", width=100, anchor='w')

    my_tree.heading("#0", anchor='w', text='Image')
    my_tree.heading("id", anchor='w', text="Id")

    count = 0

    my_tree.imglist = []
    for record in cursor_variable:
        img = Image.open(io.BytesIO(record[1]))
        img.thumbnail((50,50)) # resize the image to desired size
        img = ImageTk.PhotoImage(img)
        my_tree.insert(parent="", index="end", iid=count,
                       image=img, values=(record[0],)) # use "image" option for the image
        my_tree.imglist.append(img) # save the image reference
        count += 1

Note that I have used a list to hold the image references to avoid garbage collection.请注意,我使用了一个列表来保存图像引用以避免垃圾收集。

The output: output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM