文本小部件:在没有输入时更新并在循环后保持空闲

2024-10-03 17:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

嗨,我正在制作一个文本小部件,我想在一些输入被传递时更新它,或者让它空闲,现在我正在使用这个代码。但我不知道在没有输入或没有按下按钮的情况下如何保持它空闲

我知道有更好的方法做这个手术,但还没有找到。请帮忙


1条回答
网友
1楼 · 发布于 2024-10-03 17:19:37

您好,在阅读了一些文档和文章后,我找到了问题的解决方案。在这种情况下,我们可以使用KeyPress事件,并且可以将overupdate方法绑定到此事件

这是代码

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

相关问题 更多 >