Skip to main content
 首页 » 编程设计

python之防止 tkinter 标签被长字符串拉伸(stretch)

2025年05月04日24jiqing9006

如何防止 Tkinter 小部件(特别是标签)自动加宽?我的代码中有一个标签,我向其传递不同长度的字符串。如果字符串比列宽宽(使用网格布局管理器),我更希望将它们移动到新行而不是拉伸(stretch)列。下面是一些说明问题的代码。

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

作为一个简短的旁注:避免 self.labvar.set("I dont...") 行超过 80 个字符限制的正确方法是什么?我尝试使用“””并将其分成两行,但随后字符串也用两行放入标签中。

请您参考如下方法:

使用wraplength option :

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

根据 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).