【问题标题】:Text Widget: Update and keep idle after loop when no input文本小部件:在没有输入时更新并在循环后保持空闲
【发布时间】:2025-12-26 21:10:11
【问题描述】:
root = tk.Tk()

text = tk.Text(root, width = 40, height = 1, wrap = 'word')
text.pack(pady = 50)

after_id = None
# Now i want to increase the height after wraping
def update():
    line_length = text.cget('width')
    
    lines = int(len(text.get(1.0, 'end'))/line_length) + 1 # This is to get the current lines.
    
    text.config(height = lines) # this will update the height of the text widget.
    after_id = text.after(600, update)

update()    

root.mainloop()

嗨,我正在制作一个文本小部件,我想在某些输入时更新它,否则让它保持空闲状态,现在我正在使用此代码。但是我不知道在没有输入或没有按下按钮时如何让它保持空闲状态。

我知道有更好的方法来执行此操作,但还没有找到。请帮忙!!!

【问题讨论】:

    标签: python python-3.x tkinter tkinter-text


    【解决方案1】:

    您好,在阅读了一些文档和文章后,我找到了问题的解决方案。在此我们可以使用 KeyPress 事件,我们可以将更新方法与此事件绑定。

    这里是代码......

    import tkinter as tk
    root = tk.Tk()
    
    text = tk.Text(root, width = 40, height = 1, wrap = 'word')
    text.pack(pady = 50)
    # first of all we need to get the width of the Text box, width are equl to number of char.
    line_length = text.cget('width')
    Init_line = 1  # to compare the lines.
    # Now we want to increase the height after wraping of text in the text box
    # For that we will use event handlers, we will use KeyPress event
    # whenever the key is pressed then the update will be called
    
    def Update_TextHeight(event):
        # Now in this we need to get the current number of char in the text box 
        # for the we will use .get() method.
        text_length = len(text.get(1.0, tk.END))  
        
        # Now after this we need to get the total number of lines int the textbox
        bline = int(text_length/line_length) + 1 
        # bline will be current lines in the text box
        # text_length is the total number of char in the box
        # Since we have line_length number of char in one line so by doing 
        # text_length//line_length we will get the totol line of numbers.
        # 1 is added since initially it has one line in text box 
        # Now we need to update the length
        if event.char != 'Return':
            global Init_line
            if Init_line +1 == bline:
                text.config(height = bline)
                text.update()
                Init_line += 1
                
    # Nowe we will bind the KeyPress event with our update method.
    text.bind("<KeyPress>",Update_TextHeight)
    root.mainloop()
    

    【讨论】: