I'm trying to create a tkinter button class to add a resized image with text.
The button renders ok on the mainwindow as expected, but I cannot pass a command to the button.
The additional **kwargs to the BTN_IMG_TXT create errors with the original tk.button.
Hence I used following in class definition, which I believe the problematic part of the code.
def __init__(self, master, command, *args, **kwargs):
tk.Button.__init__(self,master=master, command=command)
Following is the full code for testing:
import tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
window.geometry("300x200")
def remove_item(event = None):
print('Delete button pressed') #debug
# custom button widget
class BTN_IMG_TXT(tk.Button):
def __init__(self, master, command, *args, **kwargs):
tk.Button.__init__(self,master=master, command=command)
self.fname = kwargs.get('fname')
self.btn_txt = kwargs.get('btn_txt')
img = Image.open(self.fname)
image = img.resize((40,40), Image.ANTIALIAS) # make static size
self.photo1= ImageTk.PhotoImage(image)
b = tk.Button(self, text=self.btn_txt, image=self.photo1,
compound="top", width=70, height=70,)
b.pack(side="top")
frm_Main = tk.Frame(master=window, bg='#faeaea', borderwidth=2)
frm_Main.pack()
stp_btn = BTN_IMG_TXT(master=frm_Main,fname="stop_b.png",btn_txt='STOP',command=remove_item)
del_btn= BTN_IMG_TXT(master=frm_Main,fname="delete_b.png",btn_txt='DELETE', command=remove_item)
del_btn.pack(side="left", fill="both", expand=False)
stp_btn.pack(side="left", fill="both", expand=False)
window.mainloop()