【发布时间】:2018-08-28 16:07:50
【问题描述】:
我的窗口上有一些小部件。标签 lb3 随着我的窗口展开。我想从长数组中放一些字符。因此,如果窗口很大,则必须有更多的字符,如果窗口变小,则字符会更少。 因此我需要知道字符中标签的当前高度和宽度。 我的问题有一个例子:
import Tkinter as tk
import tkFont
import sys
import os
last_event_H = 0
last_event_W = 0
LONG_ARRAY = ''
# when window sized
def sizing(event):
global last_event_H
global last_event_W
global LONG_ARRAY
if (event.width == last_event_W and event.height == last_event_H):
return
last_event_H = event.height
last_event_W = event.width
width_in_chars = lb3['width']
height_in_chars = lb3['height']
first_shown = int(lb1_text.get())
lb3_text.set(LONG_ARRAY[first_shown:first_shown + width_in_chars * height_in_chars])
lb2_text.set(LONG_ARRAY[first_shown + width_in_chars * height_in_chars] + ' ...')
class WrappingLabel(tk.Label):
'''a type of Label that automatically adjusts the wrap to the size'''
def __init__(self, master=None, **kwargs):
tk.Label.__init__(self, master, **kwargs)
self.bind('<Configure>', lambda e: self.config(wraplength=self.winfo_width()))
if __name__ == '__main__':
root = tk.Tk()
root.geometry("1280x640")
dFont=tkFont.Font(family="Arial", size=30) # fixed Font
LONG_ARRAY = 'a' * 100000 # of symbols
tb_date = tk.Entry(root, font=dFont)
tb_date.grid(column=0, row=0, columnspan=3, sticky=tk.NSEW)
bt_find = tk.Button(root, text="...", font=dFont)
bt_find.grid(column=9, row=0, columnspan=2, sticky=tk.NSEW)
lb1_text = tk.StringVar()
lb1_text.set("1")
lb1 = tk.Label(root, textvariable=lb1_text, width=10, font=dFont, anchor=tk.NW)
lb1.grid(column=0, row=1, sticky=tk.NSEW)
lb2_text = tk.StringVar()
lb2 = tk.Label(root, textvariable=lb2_text, width=10, font=dFont, anchor=tk.NW)
lb2.grid(column=1, row=10, columnspan=9, sticky=tk.NSEW)
lb3_text = tk.StringVar()
lb3 = WrappingLabel(root, textvariable=lb3_text, font=dFont, anchor=tk.NW, justify=tk.LEFT)
lb3.grid(column=1, row=1, columnspan=9, rowspan=9, sticky=tk.NSEW)
for x in range(11):
tk.Grid.columnconfigure(root, x, weight=1)
for y in range(11):
tk.Grid.rowconfigure(root, y, weight=1)
root.bind("<Configure>", sizing)
width_in_chars = lb3['width']
height_in_chars = lb3['height']
print width_in_chars, height_in_chars # !!!!!!!!!!!!!
print "-------"
lb3_text.set(LONG_ARRAY[:width_in_chars * height_in_chars])
lb2_text.set(LONG_ARRAY[width_in_chars * height_in_chars] + ' ...') # last shown character
root.mainloop()
lb3 的 width 和 height 成员现在设置为 0。 因为它可以扩展。还有其他方法吗?
【问题讨论】:
-
width和height选项只会反映您配置标签的值,而不是小部件的实际大小。无论如何,实际适合的字符数取决于这些字符是什么,除非你给它一个等宽字体。如果我正确理解您的要求,我相信解决方案是使用 Text 小部件,设置为disabled或readonly模式,除非您更改内容 - 这将简单地剪切任何不适合,而不是像标签那样调整自己的大小。 -
听起来您的问题实际上可能与此重复:Display three dots in the end of a Tkinter Label text