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

Python Tkinter中如何对已创建的Button按钮控件实现旋转操作?

Tkinter 按钮旋转实现方案

原生 Tkinter 的 Button 控件没有内置旋转属性,无法直接对实例化后的按钮做旋转操作,可通过以下两种方式实现需求:

  • 方案一:基于 Canvas 自定义旋转按钮(无第三方依赖)
    在 Canvas 控件上绘制旋转后的按钮背景、旋转文本,再手动绑定<Button-1>点击事件触发对应的open_code方法,完全使用原生Tkinter能力实现,不需要额外安装库。
    核心代码参考:
    import tkinter as tk
    import math
    
    # 旋转文本绘制函数
    def draw_rotated_text(canvas, x, y, text, angle, **kwargs):
        # 先创建临时文本获取尺寸
        temp = canvas.create_text(x, y, text=text, **kwargs)
        bbox = canvas.bbox(temp)
        canvas.delete(temp)
        width = bbox[2] - bbox[0]
        height = bbox[3] - bbox[1]
        # 计算旋转后坐标
        rad = math.radians(angle)
        cos_rad = math.cos(rad)
        sin_rad = math.sin(rad)
        # 绘制旋转后文本
        for dx in range(width):
            for dy in range(height):
                new_x = x + dx * cos_rad - dy * sin_rad - width/2 * cos_rad + height/2 * sin_rad
                new_y = y + dx * sin_rad + dy * cos_rad - width/2 * sin_rad - height/2 * cos_rad
                if 0 <= new_x < canvas.winfo_width() and 0 <= new_y < canvas.winfo_height():
                    canvas.create_text(new_x, new_y, text=text[0] if dx == 0 and dy ==0 else "", **kwargs)
    # 自定义旋转按钮
    rot_btn_canvas = tk.Canvas(window, width=120, height=60, bg='#D53A33', highlightthickness=0)
    rot_btn_canvas.place(x=替换为你需要的x坐标, y=替换为你需要的y坐标)
    draw_rotated_text(rot_btn_canvas, 60, 30, "Open VScode", 90, fill='white', font=('Valorant',6))
    # 绑定点击事件
    rot_btn_canvas.bind("<Button-1>", lambda e: open_code())
    
  • 方案二:基于PIL库生成旋转按钮贴图(实现更简单)
    先将你原有的按钮样式生成图片,用Pillow旋转后赋值给Button控件的image属性即可,需要提前执行pip install pillow安装依赖。
    核心代码参考:
    from PIL import Image, ImageTk, ImageDraw, ImageFont
    
    # 生成和原按钮同尺寸的背景图
    img = Image.new('RGB', (9*10, 6*20), color='#D53A33')
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("Valorant.ttf", 6)
    draw.text((10, 10), "Open VScode", font=font, fill='white')
    # 旋转90度,expand参数保证旋转后完整显示
    rotated_img = img.rotate(90, expand=1)
    tk_img = ImageTk.PhotoImage(rotated_img)
    # 替换原有Open_app2按钮
    Open_app2 = Button(window, image=tk_img, command=open_code, bd=0, highlightthickness=0)
    Open_app2.image = tk_img # 保持图片引用防止被GC回收
    

注意:如果需要其他旋转角度,修改上述代码中的角度参数即可,建议优先选择90度、180度、270度这类整90度的数值,避免出现锯齿模糊问题。

内容的提问来源于stack exchange,提问作者An Huy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:27:03