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

如何用Python Tkinter实现类Word文本框点击空白删除空文本框功能

解决方案

核心实现逻辑为新增全局变量记录最近创建的文本框实例,每次点击时先校验上一个文本框是否为空,为空则销毁后再在新位置创建文本框。

调整后完整代码

from tkinter import *

root = Tk()
# 存储最近一次创建的文本框实例
current_textbox = None

def do(event):
    global current_textbox
    # 校验上一个文本框是否为空
    if current_textbox is not None:
        # 获取文本框内容,排除组件默认自带的末尾换行符
        content = current_textbox.get("1.0", "end-1c").strip()
        if not content:
            current_textbox.destroy()
    # 在新点击位置创建文本框
    current_textbox = Text(root, cursor="arrow", bd=0, height=1, width=20)
    current_textbox.place(x=event.x, y=event.y)
    # 新文本框自动获取焦点,可直接输入内容
    current_textbox.focus_set()

root.config(bg = "red")
root.bind("<Button-1>", do)
root.mainloop()

如果需要保留原代码中根据点击横坐标设置文本框宽度的逻辑,可将width=20替换为width=event.x。

关键改动说明

  • 新增全局变量current_textbox,用于存储最近创建的文本框实例,方便后续校验状态
  • 每次点击事件触发时,先读取上一个文本框的内容,去除首尾空白后如果为空,调用destroy()方法销毁该空文本框
  • 新增focus_set()调用,新创建的文本框自动获取焦点,无需手动点击即可输入内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:06:04