0
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()

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

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

4

1 回答 1

0

嗨,在阅读了一些文档和文章后,我得到了问题的解决方案。在这种情况下,我们可以使用 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()
于 2021-05-27T18:06:07.067 回答