您可以创建从canvas继承的自定义按钮类,并像使用Button()一样使用它。我给你做了一个希望你觉得有用。在
自定义按钮类:
将此类另存为imgbutton.py,然后将其导入主文件。还要确保它与主文件所在的目录相同。或者您可以在导入后将其保存在主文件的顶部。在import tkinter as tk
class Imgbutton(tk.Canvas):
def __init__(self, master=None, image=None, command=None, **kw):
# Declared style to keep a reference to the original relief
style = kw.get("relief", "groove")
if not kw.get('width') and image:
kw['width'] = image.width()
else: kw['width'] = 50
if not kw.get('height') and image:
kw['height'] = image.height()
else: kw['height'] = 24
kw['relief'] = style
kw['borderwidth'] = kw.get('borderwidth', 2)
kw['highlightthickness'] = kw.get('highlightthickness',0)
super(Imgbutton, self).__init__(master=master, **kw)
self.set_img = self.create_image(kw['borderwidth'], kw['borderwidth'],
anchor='nw', image=image)
self.bind_class( self, '',
lambda _: self.config(relief='sunken'), add="+")
# Used the relief reference (style) to change back to original relief.
self.bind_class( self, '',
lambda _: self.config(relief=style), add='+')
self.bind_class( self, '',
lambda _: command() if command else None, add="+")
下面是一个如何使用它的示例
^{pr2}$