Reputation: 665
Using Tkinter 8.6, Python 3.7.3:
A friendly user here instructed me on how to have an image act like a button by the way of creating an Imgbutton
class that is a subclass of Tkinter Canvas
.
I have some questions regarding this code, here is the simplified version of it:
#!/usr/local/bin/python3
import tkinter as tk
from PIL import Image, ImageTk
class Imgbutton(tk.Canvas):
def __init__(self, master=None, image=None, command=None, **kw):
super(Imgbutton, self).__init__(master=master, **kw)
self.set_img = self.create_image(0, 0, anchor='nw', image=image)
self.bind_class( self, '<Button-1>',
lambda _: self.config(relief='sunken'), add="+")
self.bind_class( self, '<ButtonRelease-1>',
lambda _: self.config(relief='groove'), add='+')
self.bind_class( self, '<Button-1>',
lambda _: command() if command else None, add="+")
Questions:
Imgbutton
object, the separated line above gets executed but I do not understand why. self.set_img
correspond to an object of Imgbutton
or tk.Canvas
class?This part might be unneccessary to mention but here I am creating an Imgbutton
object:
root = tk.Tk()
but_img = tk.PhotoImage(file='button.png')
but = Imgbutton(root, image=but_img, width=but_img.width(),
height=but_img.height(), borderwidth=2, highlightthickness=0)
but.pack()
root.mainloop()
Upvotes: 3
Views: 3166
Reputation: 386210
When I create an Imgbutton object, the separated line above gets executed but I do not understand why.
It's executed because it's part of the code. I'm not sure why you think it wouldn't be called. If you don't want it to be called, move it outside of the __init__
method.
Does the self.set_img correspond to an object of Imgbuttonor tk.Canvas class?
self
refers to the instance of the Imgbutton
class. set_img
will be the identifier returned by the canvas when it creates the object on the canvas.
Is there any point here where an actual canvas is created?
Yes. Imgbutton
is the canvas. That is how inheritance works: Imgbutton
is a Canvas
, with some enhancements. It gets created when you do but = Imgbutton(...)
. Though, perhaps a bit more accurately the actual canvas is created when you call super
, which tells tkinter to create the object.
Upvotes: 2