Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing tkinter labels being stretched by a long string

How to I prevent the automatic widening of Tkinter widgets (specifically labels)? I have a label in my code to which I pass strings of varying length. In the case that the strings are wider than the column width (using the grid layout manager), I would prefer them to be moved to a new line rather than stretching the column. Below is some code that illustrates the problem.

import Tkinter

class window(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()
        self.columnconfigure(0, minsize=50)
        self.columnconfigure(0, minsize=150)
        self.rowconfigure(0,minsize=20)
        self.rowconfigure(1,minsize=20)
        self.rowconfigure(2,minsize=20)

        self.labvar = Tkinter.StringVar()
        self.lab = Tkinter.Label(self,bg='white',relief='groove',
                        textvariable=self.labvar)
        self.lab.grid(row=0,column=0,rowspan=2,sticky='NSEW')
        self.labvar.set("I don't want this to resize (Y dimension) ...")

        self.but = Tkinter.Button(self, text='Click me!',command=self.onbut)
        self.but.grid(row=2,column=0, sticky='NSEW')


    def onbut(self):
        self.labvar.set("I don't want this to resize (Y dimension) ...I'd rather this on a new line!")

if __name__ == "__main__":
    app = window(None)
    app.title('Window')
    app.mainloop()

As a quick side note: what is the correct way to avoid the self.labvar.set("I dont...") line stretching over the 80 character limit? I tried using """ and breaking it over two lines but the string was then put in to the label with two lines as well.

like image 679
John Crow Avatar asked Jan 19 '26 14:01

John Crow


1 Answers

Use wraplength option:

self.lab = Tkinter.Label(self,bg='white', relief='groove',
                         textvariable=self.labvar, wraplength=250)

According to The Tkinter Label Widget documentation:

Labels can display multiple lines of text. You can use newlines or use the wraplength option to make the label wrap text by itself. When wrapping text, you might wish to use the anchor and justify options to make things look exactly as you wish.

...

wraplength=

Determines when a label’s text should be wrapped into multiple lines. This is given in screen units. Default is 0 (no wrapping).

enter image description here

enter image description here

like image 102
falsetru Avatar answered Jan 21 '26 02:01

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!