使 tkinter 按钮大小相同

som*_*y95 5 tkinter button python-3.x

无论文本如何,我都想让所有 tkinter 按钮的大小相同。是否可以拉伸其他按钮以相互匹配或设置特定大小?因为我很难在文档中找到如何这样做。目前,按钮根据文本的大小进行拉伸。 我的意思的例子。是否可以使它们全部相同大小?

Bry*_*ley 10

你用一个几何管理器时,您通常会做到这一点(packplace,或grid)。

使用网格:

import tkinter as tk

root = tk.Tk()
for row, text in enumerate((
        "Hello", "short", "All the buttons are not the same size",
        "Options", "Test2", "ABC", "This button is so much larger")):
    button = tk.Button(root, text=text)
    button.grid(row=row, column=0, sticky="ew")

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

使用包:

import tkinter as tk

root = tk.Tk()
for text in (
        "Hello", "short", "All the buttons are not the same size",
        "Options", "Test2", "ABC", "This button is so much larger"):
    button = tk.Button(root, text=text)
    button.pack(side="top", fill="x")

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 这种方法利用了这样一个事实,即包含按钮的小部件将与最大宽度的按钮具有相同的宽度。并将每个按钮扩展到容器的宽度。 (2认同)

Luc*_*fer 6

width您还可以在定义按钮时使用选项,如下所示:

from tkinter import *
root = Tk()
button = Button(root, text = "Test", width = 5)
button.grid()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)