python - 在 tkinter 中将文本添加到自定义圆形按钮
问题描述
我在 tkinter 中有一个自定义圆形按钮
这是代码:
class RoundedButton(tk.Canvas):
def __init__(self, parent, bg, width, height = None, command=None, color = "red", padding = 0, cornerradius = None):
height = width if height == None else height
cornerradius = min(width, height) / 2 if cornerradius == None else cornerradius
tk.Canvas.__init__(self, parent, borderwidth=0,
relief="flat", highlightthickness=0, bg=bg)
self.command = command
if cornerradius > 0.5*width:
print("Error: cornerradius is greater than width.")
return None
if cornerradius > 0.5*height:
print("Error: cornerradius is greater than height.")
return None
rad = 2*cornerradius
def shape():
self.create_polygon((padding,height-cornerradius-padding,padding,cornerradius+padding,padding+cornerradius,padding,width-padding-cornerradius,padding,width-padding,cornerradius+padding,width-padding,height-cornerradius-padding,width-padding-cornerradius,height-padding,padding+cornerradius,height-padding), fill=color, outline=color)
self.create_arc((padding,padding+rad,padding+rad,padding), start=90, extent=90, fill=color, outline=color)
self.create_arc((width-padding-rad,padding,width-padding,padding+rad), start=0, extent=90, fill=color, outline=color)
self.create_arc((width-padding,height-rad-padding,width-padding-rad,height-padding), start=270, extent=90, fill=color, outline=color)
self.create_arc((padding,height-padding-rad,padding+rad,height-padding), start=180, extent=90, fill=color, outline=color)
id = shape()
(x0,y0,x1,y1) = self.bbox("all")
width = (x1-x0)
height = (y1-y0)
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):
# print(event)
self.configure(relief="sunken")
def _on_release(self, event):
# print(event)
self.configure(relief="raised")
if self.command is not None:
self.command()
此代码有效,但没有向其添加文本的功能。我认为要向这个圆形按钮添加文本,我需要在类中创建另一个函数,该函数将采用 x 和 y 坐标并将其放置在它的父级中,但是在放置时我们需要创建一些标签或一些文本根据 x 和 y 坐标放置。但是,我不知道如何计算应该放置的文本的位置。有人可以帮我吗?我确信必须进行一些计算才能找到文本的位置。
解决方案
您只需使用以下命令将文本放在画布的中心.create_text(...)
:
def __init__(self, parent, bg, width, height=None, text="", font=None, command=None, color="red", padding=0, cornerradius=None):
...
height = (x1-x0)
width = (y1-y0)
# show the text at the center of canvas
self.create_text(width/2, height/2, text=text, font=font)
...