【问题标题】:How to scale buttons without misaligning them or fix the alignment?如何在不对齐按钮的情况下缩放按钮或修复对齐?
【发布时间】:2020-10-22 10:14:26
【问题描述】:

我一直在尝试学习如何使用 python 和 Tkinter。 当我有多列大小不同的按钮时,它们不会像我期望的那样根据我制作的大小对齐。

它的样子:

如您所见,高度设置为 100 的按钮仅使用与高度为 10 的 6 个按钮相同的空间,而不是像预期的那样占据整个高度。

预期结果:

有什么方法可以按预期对齐按钮,而无需手动尝试确定点亮它们所需的大小?

代码:

import tkinter as tk
import tkinter.font as tkFont

root = tk.Tk()
pixelVirtual = tk.PhotoImage(width=1, height=1)

large = tk.Button(root,
    text='Height=100',
    image=pixelVirtual,
    width=100,
    height=100,
    compound='c')
for i in range(10):
    small = tk.Button(root,
        text='Height=10',
        image=pixelVirtual,
        width=100,
        height=10,
        compound='c')
    small.grid(row=i, column= 1)
large.grid(row=0, rowspan=10, column=0)

root.mainloop()

【问题讨论】:

    标签: python-3.x tkinter layout alignment


    【解决方案1】:

    这是因为small按钮的最终高度不是10。在我的系统中是18:

    • border width 是 2 x 2(上下),即 4
    • highlightthickness 是 1 x 2(上下),即 2
    • pady 是 1 x 2(上下),即 2
    • 文字/图片面积为10

    所以总数是4 + 2 + 2 + 10 = 18

    large 按钮类似:4 + 2 + 2 + 100 = 108,即6 x 18

    为了对齐large按钮,在grid(...)中添加sticky='nsew'

    large.grid(row=0, rowspan=10, column=0, sticky='nsew')
    

    【讨论】:

      猜你喜欢
      • 2019-07-06
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2021-07-16
      • 2021-05-10
      • 2012-09-29
      相关资源
      最近更新 更多