Python Forum
Why does this only work outside of a method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does this only work outside of a method
#1
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)
Reply
#2
Need to post all code and error messages. Not enough there to answer your question
Reply
#3
(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()
Reply
#4
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020