Tkinter不允许您直接在画布之外的其他窗口小部件上绘图,并且画布图形将始终位于嵌入式窗口小部件的下方。
简单的解决方案是仅使用画布来创建按钮的效果。这样做确实没有什么特别的:只需创建一个画布,然后为ButtonPress和ButtonRelease添加绑定以模拟被按下的按钮。
这是一个大概的想法:
class CustomButton(tk.Canvas): def __init__(self, parent, width, height, color, command=None): tk.Canvas.__init__(self, parent, borderwidth=1, relief="raised", highlightthickness=0) self.command = command padding = 4 id = self.create_oval((padding,padding, width+padding, height+padding), outline=color, fill=color) (x0,y0,x1,y1) = self.bbox("all") width = (x1-x0) + padding height = (y1-y0) + padding self.configure(width=width, height=height) self.bind("<ButtonPress-1>", self._on_press) self.bind("<ButtonRelease-1>", self._on_release) def _on_press(self, event): self.configure(relief="sunken") def _on_release(self, event): self.configure(relief="raised") if self.command is not None: self.command()要完成这种错觉,您需要在
<Enter>和上设置绑定
<Leave>(以模拟活动状态),并确保光标位于按钮释放按钮的上方-
注意,如果您使用真正的按钮,则什么也不做释放鼠标之前将其移开。



