Tkinter Resize text to contents

后端 未结 4 791
长发绾君心
长发绾君心 2020-12-16 06:27

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

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

4条回答
  •  有刺的猬
    2020-12-16 06:41

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

提交回复
热议问题