【问题标题】:View image from mysql DB file path on Tkinter label [duplicate]从 Tkinter 标签上的 mysql DB 文件路径查看图像 [重复]
【发布时间】:2026-01-18 14:15:01
【问题描述】:

我有一个 MySQL 数据库,其中有一个 patients_tbl(id、names、gender、contact_no、address、date、result) 在结果列中,我正在存储可以通过双击记录来检索的图像文件路径,现在我想在我的 GUI 中的标签上显示图像,该标签未显示但正在发生其他事情。

def double_click(event):
        row_id = db_tree_view.identify_row(event.y)
        item = db_tree_view.item(db_tree_view.focus())
        id_var.set(item['values'][0])
        name_var.set(item['values'][1])
        sex_var.set(item['values'][2])
        phone_var.set(item['values'][3])
        add_var.set(item['values'][4])
        date_var.set(item['values'][5])
        _result_var = (item['values'][6]) # Image file path
        print(_result_var) # For checking purpose
        
        # ============================VIEWING THE IMAGE===============================
        patient_result = Image.open(_result_var)
        pat_result = patient_result.resize((700, 300), Image.ANTIALIAS)
        new_result = ImageTk.PhotoImage(pat_result)
        result_lbl = Label(view_frame, image = new_result) # Shoeing on a label on a view_frame
        result_lbl.pack(pady = 20)

上图为双击任意记录前的窗口,下图为双击记录后的窗口。

如果我从 DB 单独运行函数代码,它的行为很好,这告诉我文件路径没问题:

from tkinter import *
from PIL import Image, ImageTk

main_window = Tk()
main_window.configure(background='light blue')
main_window.iconbitmap('lardmon_icon.ico')
main_window.title("ECG-LArdmon")
main_window.geometry('700x500')
main_window.resizable(width=False, height=False)

_result_var = "C:\\Users\\Kennedy Mulenga\\Desktop\\Level 5\\18136709_BIT_280_Arduino_ECG_Project\\results\\Kennedy Mulenga1.png"
patient_result = Image.open(_result_var)
pat_result = patient_result.resize((500, 400), Image.ANTIALIAS)
new_result = ImageTk.PhotoImage(pat_result)
result_lbl = Label(main_window, image = new_result)
result_lbl.pack(pady = 20)



main_window.mainloop()

有人可以帮助或建议最好的方法吗?

【问题讨论】:

  • 你遇到什么错误
  • @CoolCloud 完全没有错误,但现在已修复。

标签: python mysql tkinter


【解决方案1】:

问题出在这里:

new_result = ImageTk.PhotoImage(pat_result)

new_result 应该是全局变量,而不是函数变量。它也可以存储在全局listdict 或在图像显示之前不返回的函数中。

【讨论】:

    最近更新 更多