如何用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
相关产品推荐
相关产品推荐

