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

如何在点击Entry框外部时禁用Tkinter的Entry Widget

解决Tkinter Entry点击外部禁用的问题

要实现点击Entry组件外部时禁用它,你需要给主窗口绑定鼠标点击事件,在回调中判断点击位置是否在Entry区域外,再调整Entry的state参数。具体实现如下:

  • 定义回调函数处理窗口点击事件
  • 获取Entry的位置与尺寸,判断点击坐标是否在Entry范围外
  • 若点击在外部,将Entry状态设置为DISABLED

修改后的完整代码:

from tkinter import *

def disable_entry_on_click_outside(event):
    # 获取Entry的位置和尺寸
    entry_x = user_input.winfo_x()
    entry_y = user_input.winfo_y()
    entry_width = user_input.winfo_width()
    entry_height = user_input.winfo_height()
    
    # 判断点击坐标是否在Entry区域外
    if not (entry_x <= event.x <= entry_x + entry_width and entry_y <= event.y <= entry_y + entry_height):
        user_input.config(state=DISABLED)

tk = Tk()
tk.minsize(250, 300)
tk.resizable(False, False)

val = StringVar()
val.set(100)

user_input = Entry(tk, textvariable=val, width=22)
user_input.place(x=100, y=83)

# 给主窗口绑定左键点击事件
tk.bind("<Button-1>", disable_entry_on_click_outside)

tk.mainloop()

补充优化

如果需要再次点击Entry时恢复可编辑状态,可修改回调函数,增加点击Entry内部时的状态切换逻辑:

def disable_entry_on_click_outside(event):
    entry_x = user_input.winfo_x()
    entry_y = user_input.winfo_y()
    entry_width = user_input.winfo_width()
    entry_height = user_input.winfo_height()
    
    if entry_x <= event.x <= entry_x + entry_width and entry_y <= event.y <= entry_y + entry_height:
        # 点击Entry内部,恢复可编辑
        user_input.config(state=NORMAL)
    else:
        # 点击外部,禁用Entry
        user_input.config(state=DISABLED)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:54:51