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

使用tkinter开发时点击entry输入框能否实现自动调整大小功能?

实现方案

核心思路

  • 为所有Entry组件绑定<FocusIn>焦点事件,用户点击输入框时自动触发弹窗逻辑
  • 采用Toplevel独立弹窗承载放大后的输入区域,内部使用Text组件支持长内容输入、换行与滚动
  • 弹窗关闭或点击确认按钮时,自动将编辑后的内容同步回原Entry组件
  • 动态新增的Entry组件自动绑定相同事件逻辑,适配新增字段的使用需求

修改后完整可运行代码

from tkinter import *
import tkinter as tk
 
class Database_Project(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        stack_frame_container = tk.Frame(self)
        stack_frame_container.grid_columnconfigure(0, weight=1)
        stack_frame_container.grid_rowconfigure(0, weight=1)
        stack_frame_container.pack(side="top", fill="both", expand=True)
        self.frameslist = {}
        for frame in (MainPage, CreatePage):
            frame_occurrence = frame.__name__
            active_frame = frame(parent=stack_frame_container, controller=self)
            self.frameslist[frame_occurrence] = active_frame
            active_frame.grid(row=0, column=0, sticky="snew")
        self.current_frame("MainPage")
            
    def current_frame(self, frame_occurrence):
        active_frame = self.frameslist[frame_occurrence]
        active_frame.tkraise()
 
class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label_create = tk.Label(self, text="Create and insert data").grid(row=0, column=0, padx=50, pady=(50,0))
        create_button = tk.Button(self, text="CREATE", command=lambda: controller.current_frame("CreatePage")).grid(row=1, column=0)
        label_read = tk.Label(self, text="Query over data").grid(row=0, column=1, padx=50, pady=(50,0))
        read_button = tk.Button(self, text="READ").grid(row=1, column=1)
        label_update = tk.Label(self, text="Modify existing data").grid(row=2, column=0, padx=50, pady=(50,0))
        update_button = tk.Button(self, text="UPDATE").grid(row=3, column=0, pady=(0,50))
        label_delete = tk.Label(self, text="Remove data").grid(row=2, column=1, padx=50, pady=(50,0))
        delete_button = tk.Button(self, text="DELETE").grid(row=3, column=1, pady=(0,50))
 
class CreatePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.inputlist = []
        self.newinputlist = []
        labels = [tk.Label(self, text="Enter unique field"), tk.Label(self, text="Enter corresponding the value/s")]
        self.inputlist.append(labels[:])
        for toplabels in range(1):
            self.inputlist[toplabels][0].grid(row=toplabels, column=0, padx=10, pady=5)
            self.inputlist[toplabels][1].grid(row=toplabels, column=1, padx=10, pady=5)
        # 初始化Entry并绑定焦点事件
        for entries in range(2):
            entry = tk.Entry(self, borderwidth=5)
            entry.bind("<FocusIn>", lambda e, en=entry: self.on_entry_focus(e, en))
            self.newinputlist.append(entry)
        for x in range(len(self.newinputlist)):
            self.newinputlist[x].grid(row=1, column=x, padx=10, pady=5)
        self.inputlist.append(self.newinputlist[:])
        button_input_1 = [tk.Button(self, text="ADD FIELD/VALUE", command=self.add_insert), tk.Button(self, text="BACK", command=lambda: controller.current_frame("MainPage"))]
        self.inputlist.append(button_input_1[:])
        button_input_2 = [tk.Button(self, text="IMPORT FILE"), tk.Button(self, text="SUBMIT DATA")]
        self.inputlist.append(button_input_2[:])
        for button in range(len(self.inputlist) - 2, len(self.inputlist)):
            self.inputlist[button][0].grid(row=button, column=0, padx=10, pady=5)
            self.inputlist[button][1].grid(row=button, column=1, padx=10, pady=5)

    def on_entry_focus(self, event, entry):
        # 避免重复创建弹窗
        if hasattr(self, 'edit_popup') and self.edit_popup.winfo_exists():
            return
        # 创建编辑弹窗
        self.edit_popup = tk.Toplevel(self)
        self.edit_popup.title("编辑内容")
        self.edit_popup.geometry("450x220")
        # 弹窗固定在主窗口上层
        self.edit_popup.transient(self)
        # 文本编辑区
        edit_text = tk.Text(self.edit_popup, wrap=tk.WORD, padx=8, pady=8)
        edit_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        # 同步原输入框内容
        original_val = entry.get()
        edit_text.insert("1.0", original_val)
        # 确认回写逻辑
        def save_and_close():
            new_val = edit_text.get("1.0", tk.END).strip()
            entry.delete(0, tk.END)
            entry.insert(0, new_val)
            self.edit_popup.destroy()
        # 确认按钮
        confirm_btn = tk.Button(self.edit_popup, text="确认保存", command=save_and_close)
        confirm_btn.pack(pady=5)
        # 点击窗口关闭按钮也执行保存
        self.edit_popup.protocol("WM_DELETE_WINDOW", save_and_close)
 
    def add_insert(self):
        # 新增Entry也绑定事件
        add_input = []
        for _ in range(2):
            entry = tk.Entry(self, borderwidth=5)
            entry.bind("<FocusIn>", lambda e, en=entry: self.on_entry_focus(e, en))
            add_input.append(entry)
        self.inputlist.insert(-2, add_input)
        self.newinputlist.append(add_input)
        for widget in self.children.values():
            widget.grid_forget()
        for index, widgets in enumerate(self.inputlist):
            widget_one = widgets[0]
            widget_two = widgets[1]
            widget_one.grid(row=index, column=0, padx=10, pady=5)
            widget_two.grid(row=index, column=1, padx=10)
        
if __name__ == "__main__":
    NoSQL_Project = Database_Project()
    NoSQL_Project.title("NoSQL Database Project")
    NoSQL_Project.mainloop()

功能说明

  • 任意输入框点击获取焦点时,自动弹出放大编辑窗口,原输入框内容会自动填充到编辑窗口中
  • 编辑完成后点击「确认保存」或直接关闭编辑窗口,内容会自动同步回原输入框
  • 新增的字段输入框也自动支持上述功能,无需额外配置
  • 编辑窗口支持长文本换行、滚动查看,完全满足大量内容输入的使用需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:45:03