简体   繁体   English

如果大于列宽,则tkinter换行

[英]tkinter wrap text if larger than column width

I have 3 columns of dynamic content that. 我有3列动态内容。 I want to each column to take up 1/3 of the windows width and to be resizeable. 我希望每列占用窗口宽度的1/3,并且可调整大小。 That's not a problem: 这不是问题:

from tkinter import *
from tkinter import ttk

root = Tk()


root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.columnconfigure(2, weight=1)

ttk.Label(root, text='Hello World', width=1).grid(column=0, row=0, padx=2, sticky=(N,W,E))
ttk.Label(root, text='Some txt', width=1).grid(column=1, row=0, padx=2, sticky=(N,W,E))
ttk.Label(root, text='Yet some more text', width=1).grid(column=2, row=0, padx=2, sticky=(N,W,E))

root.geometry('400x600')
root.minsize(220,300)
root.mainloop()

The problem is that the content is dynamic and can therfore be any width - when the window is shrunk to minsize column 3 doesn't fit anymore. 问题在于内容是动态的,因此可以是任何宽度-当窗口缩小到最小时,第3列不再适合。 I want to wrap the text but need to do so in such a way that when the window is resized the text will be wraped/unwraped as needed. 我想换行,但是需要这样一种方式:当调整窗口大小时,将根据需要换行/不换行。 My main problem when I tried this was that wraptext is in text units and width is in pixels this means that I cannot write my own update function and call it every time the window is resized. 我尝试此操作时的主要问题是, 包装文本以文本单位为单位, 宽度以像素为单位,这意味着我无法编写自己的更新函数并在每次调整窗口大小时调用它。

Edit: I am not concerned what the vertical height of the window is when I wrap the text 编辑:我不担心换行时窗口的垂直高度是多少

Width for text in a label is in text units. 标签中文本的宽度以文本单位表示。 (found http://effbot.org/tkinterbook/label.htm ) so what you can do is (找到http://effbot.org/tkinterbook/label.htm ),那么您可以做的是

def display():
    window_width = root.winfo_width() #get current screen width
    wrapLen = screen_width/3
    tkk.Label(root, text="Some Text", width= ? ,wraplength=wrapLen).grid(column = 0, row=0)

The width can be decided using if statements depending on the screen_width for example it would look like 可以使用if语句来确定宽度,具体取决于screen_width,例如

if window_width == 100:
    width = 4.5
elif window_width == 300:
    width = 13.5

These are close to the correct values. 这些接近正确的值。 I calculated with a width of 400 you can get a label width=55 meaning it should be 我计算出宽度为400,可以得到标签width = 55,这应该是

if screen_width == 400:
    width = 18

do these calculations yourself if you please. 如果需要,请自己进行这些计算。

SIDE NOTE 边注

also as a side note your doing 也作为一个侧面说明

from tkinter import * 

which imports everything from tkinter. 从tkinter导入所有内容。 Then importing 然后导入

from tkinter import ttk

which just reimports the ttk bit. 只是重新导入ttk位。

If I was you I would just do 如果我是你,我会做

import tkinter as tk

then everything just becomes 然后一切都变成

root = tk.Tk()
tk.Label()
tk.Button()

and so on. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM