首页 > 解决方案 > 如何在 Python 中使用 tkinter 制作可动态调整大小的文本框?

问题描述

我正在尝试在 tkinter 中制作可动态调整大小的文本框小部件。如果我决定删除内容,如何使它在行满时添加另一行,反之亦然删除行。我尝试添加<KeyRelease>绑定,并且部分有效,我得到了类似的东西:

import tkinter as tk
import tkinter.font as tkFont

def breakline(event):
    inp = event.widget.get(1.0, 'end-1c')
    font = tkFont.Font(size=event.widget['font'].split(' ')[-1])
    TextWidth = font.measure('0') * event.widget['width']
    InpWidth = font.measure(inp)
    if inp and not InpWidth % TextWidth:
        if event.widget['height'] != InpWidth // TextWidth:
            event.widget['height'] = InpWidth // TextWidth
    elif event.widget['height'] != InpWidth // TextWidth + 1:
        event.widget['height'] = (InpWidth // TextWidth) + 1


win = tk.Tk()

x = tk.Text(win, height=1, width=30, font='12')
x.bind('<KeyRelease>', breakline)

x.grid(row=0, column=0, padx=5, pady=5)
win.mainloop()

但它也没有按我的意愿工作,因为它只在我释放按钮时执行,所以如果我试图发送垃圾邮件,它最近会添加行。还有其他解决方案吗?

标签: pythontkinter

解决方案


推荐阅读