0

I have the following simplified code from my project. My error lies in the line

self.displayimg = tk.Button(self.frame, text = 'Display', width = 25, command = lambda: show)

The error message spyder gives me is that the name 'show' is not defined, even though it is a function I clearly define in the class.

from PIL import Image, ImageTk
import matplotlib.pyplot as plt
x = 100
y = 100
xtmi = 200
xtma = 205 
xs = 1024
ytmi = 500
ytma = 505
ys = 768
xarr = np.zeros(x)
yarr = np.zeros(y)
output = np.meshgrid(xarr,yarr)
output=output[0]
def mkPIL(array):
    im = Image.fromarray(np.uint8(array))
    return im
im = mkPIL(output)
plt.imshow(im, cmap='gray')


import tkinter as tk
from tkinter import Canvas, Label


root = tk.Tk()

root.mainloop()


class Manipulation:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.frame.pack()
        self.kill = tk.Button(self.frame, text = 'Kill', width = 25, command = self.close)
        self.kill.pack()
        self.displayimg = tk.Button(self.frame, text = 'Display', width = 25, command = lambda: show)
        self.displayimg.pack()
    def close(self): 
        self.master.destroy()
    def show(): 
        img = ImageTk.PhotoImage(im)
        panel = Label(root, image=im)
        panel.image = img
        panel.place(x=0,y=0)
Paul
  • 19
  • 6
  • A reference to the image is never saved. You create it in a function and not as a class attribute. This image is garbage collect after the function completes. To fix this turn that function into a method and the saved image to a class attribute. – Mike - SMT Feb 04 '20 at 16:13
  • 2
    ***"the name 'show' is not defined"***: This should read `command=self.show` and `def show(self):` Read up on [Python Classes and Objects, Section "The self"](https://www.geeksforgeeks.org/python-classes-and-objects/) – stovfl Feb 04 '20 at 16:21
  • Please share the entire error message. – AMC Feb 04 '20 at 23:29
  • `panel = Label(root, image=im)` should be `panel = Label(root, image=img)` as well. – acw1668 Feb 05 '20 at 02:38
  • Thanks for your replies, my code works now. I just have to properly position the image. – Paul Feb 06 '20 at 12:15

0 Answers0