1 回答
TA贡献1812条经验 获得超5个赞
你可以让自己的自定义按钮类继承自画布,并像使用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, '<Button-1>',
lambda _: self.config(relief='sunken'), add="+")
# Used the relief reference (style) to change back to original relief.
self.bind_class( self, '<ButtonRelease-1>',
lambda _: self.config(relief=style), add='+')
self.bind_class( self, '<Button-1>',
lambda _: command() if command else None, add="+")
这是一个如何使用它的示例
import tkinter as tk
from imgbutton import Imgbutton # Import the custom button class
root = tk.Tk()
root['bg'] = 'blue'
but_img = tk.PhotoImage(file='button.png')
but = Imgbutton(root, image=but_img, bg='blue',
command=lambda: print("Button Image"))
but.pack(pady=10)
root.mainloop()
添加回答
举报