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

如何实现Tkinter按钮点击后永久变色且无按压效果

实现方案

你的需求可以通过优化原生Button的参数完全实现,不需要额外自定义组件,所有要求效果均可满足:

  • 合并图片+文本为单个可点击组件,无需拆分编写Button和Label
  • 完全去掉传统按钮边框、按压动效
  • 点击后永久变更背景色
  • 解决宽按钮内容居中的问题,实现内容靠左对齐

关键修改逻辑
  • 给Button添加compound=tk.LEFT参数,实现图片在左、文本在右的混合展示
  • 新增anchor='w'+justify=tk.LEFT参数,控制按钮内内容靠左对齐,可通过padx参数调整左侧边距匹配原有布局位置
  • 配置relief=tk.FLAT、overrelief=tk.FLAT、activebackground='white'参数,完全去掉按压、悬浮时的默认动效和颜色变化
  • 编写点击事件函数,点击时直接修改按钮的bg属性实现永久着色,如需侧边栏单选效果,可在函数内同时重置其他按钮的背景色

完整修改代码
from tkinter import *
from tkinter import ttk
import tkinter as tk
from PIL import ImageTk, Image

root = Tk()
root.title("xxxx")
root.geometry("1920x1080+0+0")
root.config(bg="#f0f0f0")
root.state("normal")

topbar=Frame(root, width=2200, height=43, background="#e10a0a")
topbar.place(x=0, y=0)
leftbar=Frame(root, width=250, height=1400, background="white")
leftbar.place(x=1, y=44)

# 选中色可自行修改为你需要的颜色
SELECTED_COLOR = "#e8f4fd"
# 存储所有侧边栏按钮,用于单选效果,不需要单选可删除
sidebar_btns = []

# 按钮点击事件
def on_btn_click(clicked_btn):
    # 不需要单选效果可删除下面两行循环代码
    for btn in sidebar_btns:
        btn.config(bg="white")
    # 把当前点击的按钮设置为选中色
    clicked_btn.config(bg=SELECTED_COLOR)

# 加载按钮图片
button_img = tk.PhotoImage(file="/image.png")

# 第一个按钮
btn1 = tk.Button(
    root,
    image=button_img,
    text="aaaaa",
    font='Verdana 12',
    foreground='black',
    borderwidth=0,
    highlightthickness=0,
    bg="white",
    # 图文混合:图片在左
    compound=tk.LEFT,
    # 内容左对齐
    anchor='w',
    justify=tk.LEFT,
    # 左侧内边距,可自行调整匹配原有位置
    padx=5,
    # 宽度适配侧边栏
    width=224,
    # 去掉按压/悬浮动效
    relief=tk.FLAT,
    overrelief=tk.FLAT,
    # 点击时的背景色和默认一致,避免瞬间变色
    activebackground="white",
    # 绑定点击事件
    command=lambda: on_btn_click(btn1)
)
btn1.place(x=2, y=43)
sidebar_btns.append(btn1)

# 第二个按钮
btn2 = tk.Button(
    root,
    image=button_img,
    text="bbbbbb",
    font='Verdana 12',
    foreground='black',
    borderwidth=0,
    highlightthickness=0,
    bg="white",
    compound=tk.LEFT,
    anchor='w',
    justify=tk.LEFT,
    padx=5,
    width=224,
    relief=tk.FLAT,
    overrelief=tk.FLAT,
    activebackground="white",
    command=lambda: on_btn_click(btn2)
)
btn2.place(x=2, y=100)
sidebar_btns.append(btn2)

root.mainloop()

内容的提问来源于stack exchange,提问作者Erling Olsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:54:07