我对Tkinter和Python还很陌生,所以也许这对你们来说很容易,但是我找不到解决这个问题的方法。。。在
我想创造这样的东西:
所以,我使用网格布局管理来创建每个单元,并在每个单元中存储一个标签。在
我目前的代码是:
from tkinter import *
class RCP:
frame = None
commandsHandle = None
def __init__(self, targets):
self.n_row = len(targets)
self.n_col = len(targets[0])
self.targets = targets
self.canvasRoot = Tk()
def createGrid(self):
# Create and configure the root
Grid.rowconfigure(self.canvasRoot, 0, weight=1)
Grid.columnconfigure(self.canvasRoot, 0, weight=1)
# Create and configure the frame
frame = Frame(self.canvasRoot)
frame.grid(row=0, column=0, sticky="NESW")
# Create the grid of commands
commandsHandle = [[None for i in range(self.n_col)] for j in range(self.n_row)]
for row_index in range(self.n_row):
Grid.rowconfigure(frame, row_index, weight=1)
for col_index in range(self.n_col):
Grid.columnconfigure(frame, col_index, weight=1)
commandsHandle[row_index][col_index] = Label(text=self.targets[row_index][col_index])
commandsHandle[row_index][col_index].grid(row=row_index, column=col_index)
self.canvasRoot.mainloop()
targets = [['A','B','C','D'],['E','F','G','H'],['I','J','K','L']]
myRCP = RCP(targets)
myRCP.createGrid()
,它描绘了这个图:
但我有两个问题要解决:
我该怎么做?在
提前谢谢。在
所以,这绝不是一个完美的解决方案(而且在我的机器上性能很差),但是你可以:
回答您的问题:
将标签文本在每个网格单元格内居中
小部件默认位于网格“单元”的中心,我假设你的意思是让它们均匀地分布在窗口上。这可以使用以下命令完成:
^{pr2}$以及
在这里,我们给每个网格
column
和row
一个相等的1
的权重。这意味着每个column
将共享窗口获得的任何额外x轴空间,而每个row
将共享窗口获得的任何额外y轴空间。这意味着每个“单元”与窗口中的其他子级平均共享空间,因此它们分布均匀。在自动调整标签文本大小以填充整个单元格
为了实现这一点,我们需要计算窗口相对于其原始大小的增加量。所以我们用这个长方程:
为使其更具可读性,如下所示:
或者
这样做的结果是,考虑到窗口的原始大小,窗口的面积会增加一个百分比。在
这意味着,如果窗口的大小比原始大小增加了10%,那么我们将得到
1.1
作为方程的结果。然后,我们将原来的字体大小(为了方便起见,10)乘以等式(1.1
)的结果,得到新的字体大小11,比10大10%,这意味着我们的字体大小随着窗口的变化而变化。在不幸的是,我还没有找到一种方法让程序检测到当标签的字体增大到一定程度时,它会迫使文本超出网格“单元格”的边界。这意味着在x轴上扩展窗口时,文本的垂直高度会导致部分字母被截断。我目前没有办法解决这个问题。如果我想办法的话,我会更新我的答案。在
相关问题 更多 >
编程相关推荐