防止 tkinter 标签被长字符串拉伸 [英] Preventing tkinter labels being stretched by a long string

查看:28
本文介绍了防止 tkinter 标签被长字符串拉伸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

顺便提一下:避免 self.labvar.set("I dont...") 行超过 80 个字符限制的正确方法是什么?我尝试使用 """ 并将其分成两行,但随后将该字符串也用两行放入标签中.

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.

推荐答案

使用 wraplength 选项:

Use wraplength option:

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

根据 Tkinter Label Widget 文档:

标签可以显示多行文本.您可以使用换行符或使用wraplength 选项使标签自行环绕文本.什么时候换行文本,您可能希望使用锚点和对齐选项来让事情看起来完全如你所愿.

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=

确定何时应将标签文本换行成多行.这是以屏幕单位给出的.默认为 0(不换行).

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

这篇关于防止 tkinter 标签被长字符串拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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