I'm trying to build a tkinter
button with an image as background inside an object. It doesn't make any sense why the second implementation doesn't work !
Here are 3 very simple examples ; Who can explain the reason why the second implementation is not working?
(Python 3.6.4 :: Anaconda, Inc.)
1. Button created globally.
Works like a charm...
from tkinter import *
from PIL import Image, ImageTk
from numpy import random
w = Tk()
def cb():
print("Hello World")
image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))
b = Button(w, text="text", command=cb, image=image)
b.pack()
w.mainloop()
2. Button created inside the object A
with a background image
The button doesn't work when clicked and doesn't display the image :(. There's clearly a problem but I don't understand it...
from tkinter import *
from PIL import Image, ImageTk
from numpy import random
w = Tk()
class A():
def __init__(self, w):
image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))
b = Button(w, text="text", command=self.cb, image=image)
b.pack()
def cb(self):
print("Hello World")
a = A(w)
w.mainloop()
3. Button created inside the object A
without a background image
The button works properly, but I would like to display the image as well
from tkinter import *
from PIL import Image, ImageTk
from numpy import random
w = Tk()
class A():
def __init__(self, w):
image = ImageTk.PhotoImage(image=Image.fromarray(random.random((50,50))))
b = Button(w, text="text", command=self.cb)#, image=image)
b.pack()
def cb(self):
print("Hello World")
a = A(w)
w.mainloop()