Tkinter 根据内容调整文本大小 [英] Tkinter Resize text to contents

查看:51
本文介绍了Tkinter 根据内容调整文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以调整 Tkinter 文本小部件的大小以适应其内容?

Is it possible to have a Tkinter text widget resize to fit its contents?

即:如果我放 1 行文本它会缩小,但如果我放 5 行它会增长

ie: if I put 1 line of text it will shrink, but if I put 5 lines it will grow

推荐答案

我能想到的唯一实现方法是每次用户在 Text 小部件中输入文本时计算宽度和高度,然后设置小部件.但这里的限制是只有等宽字体才能正常工作,但无论如何:

The only way I can think of accomplishing this is to calculate the width and height every time the user enters text into the Text widget and then set the size of the widget to that. But the limitation here is that only mono-spaced fonts will work correctly, but here it is anyway:

import Tkinter

class TkExample(Tkinter.Frame):
   def __init__(self, parent):
      Tkinter.Frame.__init__(self, parent)
      self.init_ui()

   def init_ui(self):
      self.pack()
      text_box = Tkinter.Text(self)
      text_box.pack()
      text_box.bind("<Key>", self.update_size)

   def update_size(self, event):
      widget_width = 0
      widget_height = float(event.widget.index(Tkinter.END))
      for line in event.widget.get("1.0", Tkinter.END).split("\n"):
         if len(line) > widget_width:
            widget_width = len(line)+1
      event.widget.config(width=widget_width, height=widget_height)

if __name__ == '__main__':
    root = Tkinter.Tk()
    TkExample(root)
    root.mainloop()

这篇关于Tkinter 根据内容调整文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆