tkinter设置button形状
时间: 2023-07-04 17:14:39 浏览: 311
可以使用tkinter中的`Canvas`组件来创建自定义形状的按钮。以下是一个示例代码:
```python
import tkinter as tk
class CustomButton(tk.Button):
def __init__(self, master=None, cnf={}, **kw):
tk.Button.__init__(self, master, cnf, **kw)
self.config(relief="flat", bd=0)
self.canvas = tk.Canvas(self, width=self.winfo_reqwidth(), height=self.winfo_reqheight(), bd=0, highlightthickness=0)
self.canvas.pack(fill="both", expand=True)
self.canvas.create_polygon([0,0,self.winfo_reqwidth(),self.winfo_reqheight()/2,0,self.winfo_reqheight()], fill=self["background"], outline=self["background"])
self.canvas.create_text(self.winfo_reqwidth()//2, self.winfo_reqheight()//2, text=self["text"], fill=self["foreground"], font=self["font"])
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, event):
self.canvas.itemconfig(1, fill=self["activebackground"])
def on_leave(self, event):
self.canvas.itemconfig(1, fill=self["background"])
root = tk.Tk()
button = CustomButton(root, text="Custom Button", font=("Arial", 16), background="#FFFFFF", foreground="#000000", activebackground="#CCCCCC")
button.pack()
root.mainloop()
```
这个例子中,我们创建了一个自定义的按钮`CustomButton`,它继承自`tk.Button`。我们使用`Canvas`组件来创建一个三角形的形状,并在其中添加文本。我们还绑定了`<Enter>`和`<Leave>`事件,用于在鼠标进入和离开按钮时改变按钮的背景色。
阅读全文
相关推荐

















