简体   繁体   English

TKInter-标签中的文本更改窗口的宽度

[英]TKInter - The text in the label changes window's width

I'm building a calculator in python, using the tkinter toolkit. 我正在使用tkinter工具包在python中构建一个计算器。 The problem is that when the text is typed in the calculator (and added to the label that shoes the calculation) the whole width of the window changes and becomes longer. 问题是,当在计算器中键入文本(并将其添加到计算的标签)时,窗口的整个宽度会更改并变长。 What can I do in order to solve it? 为了解决这个问题我该怎么办?

Here is some important parts of the code: (the main class inherits from tk.Frame) 这是代码的一些重要部分:(主类继承自tk.Frame)

labelStyle = {"padx":10, "pady":10, "justify":"left"}
calculationsLabel = tk.Label(self, text="", **labelStyle)
calculationsLabel.grid(row=0, column=1, **gridStyle)
self.master.resizable(0,0)
self.pack(padx=5, pady=5)
self.calculationsLabel=calculationsLabel

for number in range(9,0,-1):
        ...
        tk.Button(self, ...).grid(...)

The images that illustrates the problem: 说明问题的图像:

没有文字的计算器带文字的计算器

You need to do a couple of things to prevent the label from changing the window size: 您需要做一些事情来防止标签更改窗口大小:

  1. Give the label a width of 1 (one). 将标签的宽度设置为1(一)。 By not giving the label a width you are implicitly saying "grow bigger when the text is bigger". 通过给标签指定宽度,您就隐含地说“当文本变大时变得更大”。 By giving it an explicit width you are saying "no matter how big the text is, don't grow if the text is bigger". 通过给它一个明确的宽度,您说的是“无论文本有多大,如果文本较大,就不要增长”。
  2. use the columnspan option to grid, to get the cell that the label is in to span the width of your grid of buttons. 使用columnspan选项进行网格化,以获取标签所在的单元格以跨越按钮网格的宽度。 Use the sticky option, so that even though the label requests only one character of width, grid will force it to grow wide enough to fit the space. 使用sticky选项,这样,即使标签仅要求一个字符的宽度,grid仍将迫使其增长足够的宽度以适合空间。

You can use the columnspan argument to let the label stretch over top all of your columns, instead of stretching out the first one. 您可以使用columnspan参数使标签延伸到所有列的顶部,而不是延伸第一列。 Add to your grid method: 添加到您的网格方法:

calculationsLabel.grid(row=0, column=1, columnspan=7 **gridStyle)

(replacing 7 with however many columns you actually have) (用您实际拥有的许多列替换7)

You could use the columnspan option of grid to make the label span the complete width of the calculator. 您可以使用gridcolumnspan选项使标签跨越计算器的整个宽度。
Then, if you want the number to be on the left use anchor=W in the Label . 然后,如果您希望数字在左侧,请在Label使用anchor=W

This way the window only expands when the Label is longer than the complete window. 这样,仅当“ Label比完整窗口长时,窗口才会展开。 And you can even prevent that by using the Label 's width option. 您甚至可以使用Labelwidth选项来防止这种情况。

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

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