微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

解决方法

嗨,在阅读了一些文档和文章后,我得到了问题的解决方案。在这个我们可以使用 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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。