Incorporating a custom image in a tkinter interface using PIL

I am attempting to utilize a tkinter button in order to display an ERD diagram using sqlalchemy and PIL. I have successfully achieved this by saving the generated image to a file and then reopening that file to display it in a label.

Is there a method to directly display the image without the need to save it first?

import tkinter as tk
from sqlalchemy_schemadisplay import create_schema_graph
import urllib
from sqlalchemy import MetaData, create_engine
from PIL import Image, ImageTk 

root = tk.Tk()

def erd_gen(pr):
    global erd_img
    conn = create_engine("mssql+pyodbc:///?odbc_connect={}".format(pr))
    grph_data = MetaData(bind=conn)
    graph = create_schema_graph(metadata=grph_data, show_datatypes=False, show_indexes=False, rankdir='LR', concentrate=False)
    graph.write_png('dbschema.png') # write file to folder 
    erd_img = ImageTk.PhotoImage(Image.open("dbschema.png")) #open file from folder, would like to do this by just referring to 'graph' and not the saved file
    panel.configure(image = erd_img)
    conn.close()


params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
                                    "SERVER=(localdb)\ProjectsV13;"
                                    "DATABASE=Test;"
                                    "Trusted_Connection=yes")  

tk.Button(root, text='Generate', command=lambda: erd_gen(params)).pack()

panel = tk.Label(root)
panel.pack()

root.mainloop()

Answer №1

To generate a PNG image data buffer, use the method create_png() instead of write_png(). Then you can create a file input stream simulation using io.BytesIO:

from io import BytesIO

def generate_erd(pr):
    global erd_img
    conn = create_engine("mssql+pyodbc:///?odbc_connect={}".format(pr))
    graph_data = MetaData(bind=conn)
    graph = create_schema_graph(metadata=graph_data, show_datatypes=False, show_indexes=False, rankdir='LR', concentrate=False)
    stream = BytesIO(graph.create_png())
    erd_img = ImageTk.PhotoImage(file=stream)
    panel.configure(image=erd_img)
    conn.dispose()

Answer №2

If you need to store it in a file-like object, you can utilize the io module like in this code snippet:

from tkinter import *
from PIL import Image, ImageTk
import urllib.request
import io

root = Tk()

display = Label(root)
display.pack()

image_url = 'http://hem.bredband.net/b235373/kroppkakor/DSCF0002.JPG'

with urllib.request.urlopen(image_url) as url:
    temporary_file = io.BytesIO(url.read())

image = Image.open(temporary_file)
tk_image = ImageTk.PhotoImage(image=image)
display.config(image=tk_image)

root.mainloop()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PythonAnywhere encountered an ImportError while trying to load the module nrpccms.newsroom.templatetags.blog_extras. The specific error message was "No module named

My first attempt at deploying an app on PythonAnywhere (or anywhere else for that matter) is not going smoothly. I am encountering the following error: TemplateSyntaxError: 'blog_extras' is not a valid tag library: ImportError raised loading nrpc ...

What is the best way to change specific elements in an array to 0?

I have come across numerous instances where individuals substitute specific elements in an array with zeroes based on their values. For instance: X = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20] Setting all values < 4 to zero is not what I am looking fo ...

Encountering an issue when attempting to save two forms within a single template in

Currently, I am working on a view that contains 2 separate forms. These forms do not share any related fields. Form 1: Includes a FilteredSelectMultiple widget displaying files available for download from an FTP server. Each file in this form meets certai ...

The connection to the Django PostgreSQL server was unsuccessful as it could not establish a connection: The server is not accepting connections on the specified host "localhost" (127.0.0.1

I have recently deployed my Django app on aws-lambda using Zappa, but I encountered an error. I'm not sure if I need to install Postgres separately, as I believe it should be automatically installed from the requirements.txt file. OperationalError at ...

Working with Pandas Dataframes is proving to be quite time-consuming

I have been working on a dataset that includes a datetime column and a specific variable. My goal was to group the data into 15-minute intervals, so I wrote a code snippet that calculates lower and upper date bounds, creates a list of datetime objects with ...

With Python and WebDriver, the unittest module allows you to run tests without opening a browser

Could you assist me with the following issue? I have identified the problem but have been unable to resolve it. When I run the following code, the browser launches and the test passes: import unittest from selenium import webdriver driver = webdriver.Chro ...

Exploring LXML and Python: Strategies for identifying and manipulating parameters on the same parent-child level

I am currently grappling with how to tackle this particular issue, which is why I have not yet written much code on the subject. My current project involves working with lxml to handle XML files. The challenge at hand involves identifying a specific Settin ...

Is it incorrect to run the script multiple times in order for it to function properly?

After attempting to execute this script using both a while loop and a for loop, I noticed that it stops working after just one repetition. driver.find_element_by_class_name("submit").click() x = driver.find_element_by_class_name("submit" ...

Can multiple instances of a program be launched simultaneously?

As part of an educational project, I am developing a Python bot that creates Twitter accounts using disposable email addresses (catchalls) and Russian phone numbers. Successfully passing both the email and phone verification stages piqued my interest in sc ...

Tips for extracting text content that is not within an HTML element

Looking to extract data from this particular webpage: The information I'm interested in scraping includes Product Sku, Price, and List Price. I've successfully scraped the Price but I'm encountering issues with the other two, particularly t ...

Python implementation of FFT algorithm with the quickest recursive execution speed

Working on maps generated from drone images for a precision agriculture project that involves analyzing tree orchards with 10,000 trees using an IronPython 2.7 script in Rhino 6. I am applying the Fast Fourier Transform (FFT) to calculate the spacing of tr ...

What are the solutions to resolving issues that arise from using a numpy array in an if condition?

Seeking to iterate through each element of "z" using an "if else" condition and return the desired equation, my current implementation is yielding an error. I have experimented with the "z.all" and "z.any" functions, but both are converting "z" into a bool ...

"Challenges encountered while using the sort function in Merge Sort implementation with Python

I've been facing some challenges with my attempt to make the merge sort algorithm function properly. Despite a seemingly successful merge function, the sorting part just doesn't seem to be working as expected. I've tried researching online f ...

Utilize an iterator within a function's parameter

My goal was to develop a code that can handle sum-related problems efficiently. For instance, the ability to calculate the sum of 4*i for all values of i ranging from 3 to 109 is essential. However, I also wanted this code to be flexible enough to tackle m ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Having trouble updating Django forms.py with the latest values from the database

models.py class Test(models.Model): name = models.CharField(max_length=256) slug_name = models.CharField(max_length=256) template = models.BooleanField("Is Template",default=False) @staticmethod def template_as_tuple(): return ...

What is the best way to implement a function in a discord.py command that restricts the use of a command to only once per minute?

What is the best way to ensure a command in discord.py can only be used once every minute? @bot.command() async def busk(ctx): member = ctx.message.author.id #gets the user ID, which i use as the _id in pymongo because everyones is different. ...

Extract dropdown menu options

OBJECTIVE The aim is to explore every possible combination from this website: WHAT I'M SEEKING ADVICE ON I need some guidance on how to proceed with the task. ISSUE AT HAND I am facing a problem where I can retrieve a list of options for the first ...

Utilize a proxy gateway within Selenium WebDriver for enhanced browsing capabilities

My objective is to integrate a proxy gateway (such as geosurf.io) into the Selenium webdriver. I plan to achieve this using DesiredCapabilities, as it appears to be the preferred method for adding a proxy gateway according to this source. DesiredCapabi ...

What is the best method for extracting a JSON datetime string in Python?

When making a call from Python to a remote API, the returned data is in JSON format. To parse this data, I use the json module with json.loads(). The issue I am facing pertains to dates - the system I am calling returns the date formatted as follows: /Dat ...