You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的Tkinter中为Button组件添加圆角(radius)?

Tkinter按钮设置圆角的实现方法

原生Tkinter的Button组件并不支持直接传入radius参数来设置圆角,但有几种可行的实现方式,下面是具体方法:

方法一:用ttk.Style自定义样式

ttk的按钮样式支持borderradius属性,可以通过自定义样式快速实现圆角效果:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("300x200")

# 配置自定义圆角按钮样式
style = ttk.Style()
style.configure('Rounded.TButton', 
                borderradius=20,
                padding=10,
                background="#4CAF50",
                foreground="white")

# 使用自定义样式创建按钮
rounded_btn = ttk.Button(root, text="圆角按钮", style='Rounded.TButton')
rounded_btn.pack(pady=50)

root.mainloop()

方法二:用Canvas绘制圆角按钮

通过Canvas绘制圆角矩形,再绑定点击事件模拟按钮行为,适合需要更灵活样式控制的场景:

import tkinter as tk

# 给Canvas添加绘制圆角矩形的方法
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs):
    points = [x1+radius, y1,
              x1+radius, y1,
              x2-radius, y1,
              x2-radius, y1,
              x2, y1,
              x2, y1+radius,
              x2, y1+radius,
              x2, y2-radius,
              x2, y2-radius,
              x2, y2,
              x2-radius, y2,
              x2-radius, y2,
              x1+radius, y2,
              x1+radius, y2,
              x1, y2,
              x1, y2-radius,
              x1, y2-radius,
              x1, y1+radius,
              x1, y1+radius,
              x1, y1]
    return self.create_polygon(points, **kwargs, smooth=True)

tk.Canvas.create_rounded_rectangle = create_rounded_rectangle

root = tk.Tk()
root.geometry("300x200")

def on_btn_click(event):
    print("圆角按钮被点击")

# 创建Canvas并绘制圆角按钮
canvas = tk.Canvas(root, width=150, height=50, highlightthickness=0)
canvas.pack(pady=50)

rounded_rect = canvas.create_rounded_rectangle(0, 0, 150, 50, radius=20, fill="#2196F3", outline="")
canvas.create_text(75, 25, text="Canvas圆角按钮", fill="white")

# 绑定点击事件
canvas.tag_bind(rounded_rect, "<Button-1>", on_btn_click)
canvas.tag_bind("current", "<Button-1>", on_btn_click)

root.mainloop()

方法三:用PIL结合Label模拟按钮

借助Pillow库绘制圆角图片,用Label组件显示并绑定点击事件,适合需要复杂视觉效果的场景:

import tkinter as tk
from PIL import Image, ImageDraw, ImageTk

root = tk.Tk()
root.geometry("300x200")

def on_label_click(event):
    print("PIL圆角按钮被点击")

# 绘制圆角背景图
width, height = 150, 50
radius = 20
img = Image.new('RGBA', (width, height), (255,255,255,0))
draw = ImageDraw.Draw(img)
draw.rounded_rectangle((0,0,width,height), radius=radius, fill="#FF9800")

# 转换为Tkinter可用的图片格式
tk_img = ImageTk.PhotoImage(img)

# 创建Label作为按钮
rounded_label = tk.Label(root, image=tk_img, text="PIL圆角按钮", compound="center", fg="white")
rounded_label.pack(pady=50)
rounded_label.bind("<Button-1>", on_label_click)

root.mainloop()

内容的提问来源于stack exchange,提问作者طاها ایروانی

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:02:38