没有选项或真正简单的方法来添加自定义边框,但您可以做的是创建一个继承自 Tkinter 的类Frame
类,它创建了一个Frame
持有一个Label
。你只需要给它上色Frame
用你想要的边框颜色并保持它比Label
所以它给出了边框的外观。
然后,而不是调用Label
当您需要时,您可以调用自定义的实例Frame
类并指定您在类中设置的参数。这是一个例子:
from Tkinter import *
class MyLabel(Frame):
'''inherit from Frame to make a label with customized border'''
def __init__(self, parent, myborderwidth=0, mybordercolor=None,
myborderplace='center', *args, **kwargs):
Frame.__init__(self, parent, bg=mybordercolor)
self.propagate(False) # prevent frame from auto-fitting to contents
self.label = Label(self, *args, **kwargs) # make the label
# pack label inside frame according to which side the border
# should be on. If it's not 'left' or 'right', center the label
# and multiply the border width by 2 to compensate
if myborderplace is 'left':
self.label.pack(side=RIGHT)
elif myborderplace is 'right':
self.label.pack(side=LEFT)
else:
self.label.pack()
myborderwidth = myborderwidth * 2
# set width and height of frame according to the req width
# and height of the label
self.config(width=self.label.winfo_reqwidth() + myborderwidth)
self.config(height=self.label.winfo_reqheight())
root=Tk()
MyLabel(root, text='Hello World', myborderwidth=4, mybordercolor='red',
myborderplace='left').pack()
root.mainloop()
例如,如果您每次只需要右侧 4 个像素的红色边框,则可以对其进行简化。希望有帮助。