Python Forum

Full Version: Why does this only work outside of a method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have even tried to use 'global' on canvas


img = np.ones((800,1400))
for i in range(800):
for j in range(1400):
if ran.random() >=.5:
img[i][j] = 255
else:
img[i][j] = 0

photo = ImageTk.PhotoImage(image = Image.fromarray(img))
canvas.create_image(0,0, image=photo)
Need to post all code and error messages. Not enough there to answer your question
(Aug-25-2020, 11:35 PM)Good_AI_User Wrote: [ -> ]I have even tried to use 'global' on canvas.
It doesn't return an error it just shows a blank canvas when inserted into a function

import tkinter
import numpy as np
import random as ran
from PIL import Image, ImageTk

win = tkinter.Tk()
win.geometry("1400x800")

canvas = tkinter.Canvas(win,height = 800, width = 1400, bg = 'black')
img = np.ones((800,1400))
for i in range(800):
for j in range(1400):
if ran.random() >=.5:
img[i][j] = 255
else:
img[i][j] = 0

photo = ImageTk.PhotoImage(image = Image.fromarray(img))
canvas.create_image(0,0, image=photo)
canvas.pack()


win.mainloop()
Something in your setup?
I copied the code, corrected the indentation (please use Python tags next time) and ran it in Spyder. Got a nice static screen.

Another possibility - Spyder remained the top window. I had to select the Tkinter window to see the display