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

如何在CustomTkinter按钮上用坐标定位文本并解决点击失效问题

解决CustomTkinter中CTkButton文本自定义定位的点击问题

你遇到的问题是因为叠加在按钮上的CTkLabel会拦截鼠标点击事件,导致点标签区域时触发不了按钮的点击逻辑。给你两个可行的解决办法:

办法一:让标签把点击事件传给按钮

直接给标签绑定点击事件,触发按钮的点击逻辑就行,代码改起来很简单:

import customtkinter as ctk

class App(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.geometry("400x200")
        
        button = ctk.CTkButton(self, text="", width=300, height=100, command=self.on_button_click)
        button.place(x=10, y=20)

        label = ctk.CTkLabel(button, text="This is a label")
        label.place(x=15, y=25)
        
        # 点击标签时直接调用按钮的点击方法
        label.bind("<Button-1>", lambda e: button.invoke())
        # 可选:让标签不抢焦点,避免影响按钮的焦点状态
        label.configure(takefocus=False)
    
    def on_button_click(self):
        print("按钮被点击了!")

if __name__ == "__main__":
    app = App()
    app.mainloop()

办法二:重写CTkButton自定义文本位置(更干净)

不用额外加标签,直接改CTkButton的绘制逻辑,自己控制文本的坐标,从根源上避免组件遮挡的问题:

import customtkinter as ctk

class CustomTextButton(ctk.CTkButton):
    def __init__(self, master=None, text_x=0, text_y=0, **kwargs):
        super().__init__(master, **kwargs)
        self.text_x = text_x  # 文本相对于按钮左上角的x偏移量
        self.text_y = text_y  # 文本相对于按钮左上角的y偏移量
    
    def _draw(self, no_color_updates=False):
        super()._draw(no_color_updates)
        
        # 先把默认的文本标签隐藏
        if hasattr(self, "_text_label"):
            self._text_label.place_forget()
        
        # 在指定位置绘制文本
        if self.cget("text"):
            # 用按钮内部的画布绘制文本,anchor设为左上,方便按坐标定位
            self._canvas.create_text(self.text_x, self.text_y, 
                                    text=self.cget("text"),
                                    fill=self._current_text_color, 
                                    font=self.cget("font"),
                                    anchor="nw")

class App(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.geometry("400x200")
        
        # 创建自定义按钮,直接指定文本的x、y偏移
        button = CustomTextButton(self, text="This is a custom button", 
                                 width=300, height=100, 
                                 text_x=15, text_y=25,
                                 command=self.on_button_click)
        button.place(x=10, y=20)
    
    def on_button_click(self):
        print("自定义按钮被点击了!")

if __name__ == "__main__":
    app = App()
    app.mainloop()

两种办法各有优缺点:

  • 办法一上手快,适合临时改需求,只需要给现有标签加个绑定就行。
  • 办法二更整洁,没有多余组件,适合需要反复用这种自定义按钮的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:34:58