473,394 Members | 1,951 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Updating image with each iteration of a loop and displaying in window.

I have a while loop that continues for the set amount of iterations and in each iteration a different image is generated. What I am trying to do is to create the image, display it in a window, and then repeat the loop over.

The problem I am having is I am using PIL to generate an image which you can see below:

def make_image(self, filename):
image = Image.new("RGB", (self.map_width, self.map_height))
pix = image.load()
rgb_min_factor, rgb_max_factor, = 0.875, 1.0
for x_value in range(self.map_width):
for y_value in range(self.map_height):
current_state = self.map[x_value][y_value].get_state()

pix[x_value, y_value] = \
(int(self.red_values[current_state] * random.uniform(rgb_min_factor, rgb_max_factor)), \
int(self.green_values[current_state] * random.uniform(rgb_min_factor, rgb_max_factor)), \
int(self.blue_values[current_state] * random.uniform(rgb_min_factor, rgb_max_factor)))

image.save(filename + ".png", "PNG")

print(filename + ".png has been generated and saved in the directory of the python file.")
I attempted adding a return statement and pass it through Tkinter, but numerous errors were being thrown, simply because I cannot find a write-up showing me resources for handling an issue such as this in Python 3 while using PIL at the same time.

Below is the method that I would utulize the newly generated image in: def run_iterations(self, num_loops): self.num_loops = num_loops self.loops_made = 0

while self.loops_made < self.num_loops:
if self.loops_made == 0:
self.make_image("Map_Initial_" + str(self.loops_made + 1))

self.update_map_state()

if self.loops_made == self.num_loops - 1:
self.make_image("Map_Final_" + str(self.loops_made + 1))

print("Iteration:", self.loops_made + 1, "(", "{:.2f}".format(time.time() - self.start_time), ")")

self.loops_made += 1
I am currently using the import:

from PIL import Image, ImageTk
import tkinter as tk
I just want a basic GUI just displaying the image and updating with every iteration of the loop, any help is greatly appreciated.

I have even attempted to create the below class in order to create the window and use the image that I am generating:

class Window:
def create_window(self, image):
root = tk.Tk()
canvas = tk.Canvas(root, width = 500, height = 500)
canvas.pack()

img = Image.open(image)
tk_img = ImageTk.PhotoImage(img)
canvas.create_image(250, 250, image = tk_img)
root.mainloop()
and change the line: self.make_image("Map_Initial_" + str(self.loops_made + 1))to self.window.create_window(self.make_image("Map_Ini tial_" + str(self.loops_made + 1))), but that gives me the error: prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'

I have exhausted all the options I can find, I have done all the hard stuff I think, it seems to be something simple holding me back, but I am not too sure honestly.

EDIT:

My window class has been updated to:

class Window:

def create_window(self, image_to_load):
root = tk.Tk()
root.title("Cellular Automata Map Generation")

image = ImageTk.PhotoImage(Image.open(image_to_load))

x = (root.winfo_screenwidth() / 2) - (image.width() / 2)
y = (root.winfo_screenheight() / 2) - (image.height() / 2)

root.geometry('%dx%d+%d+%d' % (image.width(), image.height(), x, y))
root.resizable(0,0)

canvas = tk.Canvas(root, width = image.width() + 10, height = image.height() + 10)
canvas.pack()

imagesprite = canvas.create_image(image.width() / 2, image.height() / 2, image = image)
root.mainloop()
and in my run_iterations() method I changed the generation of the image to:

self.window.create_window(self.make_image("Map_Ini tial_" + str(self.loops_made + 1)))
What this does now is that the image is generated correctly and the first iteration of the loop opens the window, though I cannot find a way to update the image with every iteration of the loop.
Dec 1 '16 #1
1 5020
dwblas
626 Expert 512MB
The problem is most likely the while(). It is always running and does not allow the program any time to update the canvas. You can try update or update_idletasks, but the preferred way is to use after() and allow some time for the program to update. My rule of thumb is at least 1/10 of a second. The following program uses a one second interval so your eyes can see the changes.
Expand|Select|Wrap|Line Numbers
  1. import sys
  2. if sys.version_info[0] < 3:
  3.     import Tkinter as tk     ## Python 2.x
  4. else:
  5.     import tkinter as tk     ## Python 3.x
  6.  
  7. class Window:
  8.     def __init__(self):
  9.         self.photos=[]
  10.         self.img=""
  11.         self.loops_made=0
  12.         root = tk.Tk()
  13.         self.canvas = tk.Canvas(root, width = 500, height = 500)
  14.         self.canvas.grid()
  15.         self.load_images()
  16.         self.next_image()
  17.  
  18.         tk.Button(root, text="Quit", bg="orange",
  19.                   command=root.quit).grid(row=1)
  20.  
  21.         root.mainloop()
  22.  
  23.     def next_image(self):
  24.         if self.loops_made < 3:  ## there are only 3 images
  25.             self.canvas.delete(self.img)  ## delete previous image
  26.             self.img=self.canvas.create_image(250, 250,
  27.                                      image=self.photos[self.loops_made])
  28.             self.canvas.after(1000, self.next_image)  ## 1 second
  29.         self.loops_made += 1
  30.  
  31.     def load_images(self):
  32.         """ some common images to use for testing
  33.             copy data images to a list that is an instance variable
  34.         """
  35.         ladybug_gif_b64='''\
  36. R0lGODlhIAAgALMAAP///wAAADAwMP99Hf8AAP+lAP//AMopUwAAAAAAAAAAAAAAAAAAAAAAAAAA
  37. AAAAACH5BAAAAAAALAAAAAAgACAAAwTHEMhJq714hp3lDh0GiqH2UWOVAt96pUIsBLKglWg87Dwv
  38. 4xMBj0Asxgg+XKxwLBJrxUGsI5TKnARoVHoLDp5XbNP5cwmNAqwa/aOc13ByrfKOw2UGw1SSxrb+
  39. AWIxeXsAaX92UDQ1Nh6BdneMhQIHkHGSjYaVlmt4epmacp19YAKEoJRspKWrjBapWWGqcm1uB5tj
  40. ok4HZa+3m5wEt5kuhpTAcb+FVL/NzspAfDHPysslMJjEIS0oLygnOMVd0SwcHeDk6errEQA7
  41. '''
  42.  
  43.         grape_gif='''\
  44. R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
  45. /////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
  46. 0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
  47. YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
  48. NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
  49. '''
  50.  
  51.         house='''R0lGODdhFQAVAPMAAAQ2PESapISCBASCBMTCxPxmNCQiJJya/ISChGRmzPz+/PxmzDQyZDQyZDQy
  52. ZDQyZCwAAAAAFQAVAAAElJDISau9Vh2WMD0gqHHelJwnsXVloqDd2hrMm8pYYiSHYfMMRm53ULlQ
  53. HGFFx1MZCciUiVOsPmEkKNVp3UBhJ4Ohy1UxerSgJGZMMBbcBACQlVhRiHvaUsXHgywTdycLdxyB
  54. gm1vcTyIZW4MeU6NgQEBXEGRcQcIlwQIAwEHoioCAgWmCZ0Iq5+hA6wIpqislgGhthEAOw==
  55. '''
  56.  
  57.         for photo in (ladybug_gif_b64, grape_gif, house):
  58.            self.photos.append(tk.PhotoImage(data=photo))
  59.  
  60. W=Window() 
Dec 1 '16 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Moth | last post by:
I have a PlotPanel class that extends JPanel which I have used previously to display charts in swing guis. I now want to display a graph in a jsp page so I was going to generate the graph and then...
0
by: Benny Raymond | last post by:
Does anyone know a way to dynamically update an image list - in case an image changes for a tool bar or something and you want it to build in the new images each time. Currently if an image...
2
by: Mike Mac | last post by:
Hello all, I have a loop and would like to create a new textbox on each iteration of the loop. The code below only generates one textbox no matter how many times the loop loops! Any insight...
2
by: thehuby | last post by:
I am building a CMS and as part of it a user can upload an image. Once uploaded I am displaying the image. If the user then decides they want to replace the image with another I get a caching...
0
by: Job Lot | last post by:
I have designed a user interface with controls bound to data using Data Source Window. Draging and dropped customer table from Data Source Window created various navigation controls and a...
16
by: fniles | last post by:
I am using VB.NET 2003, SQL 2000, and SqlDataAdapter. For every record in tblA where colB = 'abc', I want to update the value in colA. In VB6, using ADO I can loop thru the recordset,set the...
1
by: Constantine AI | last post by:
I was wondering if you could give me some advice on another issue. I have this code for inserting more details based on the StkID. Dim strSQL As String Dim db As Database ...
5
by: Dave Elfers | last post by:
Hello, I am using a for loop to iterate through an array and need to assign each iteration to a new variable, such as arr = for i in arr: print i but instead of printing i, I want...
0
by: jaseem0712 | last post by:
I have a data grid view like this: http://bytes.com/attachment.php?attachmentid=7458&stc=1&d=1390739933 i am loading data grid view like this: Dim cd As SqlCommandBuilder = New...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.