【问题标题】:Why aren't my buttons properly aligned with python TKinter为什么我的按钮没有与 python TKinter 正确对齐
【发布时间】:2023-03-25 06:00:01
【问题描述】:

我正在创建一个包含一些按钮的密码管理器,但由于某种原因,这些按钮没有正确对齐,有人可以帮忙吗? 这是我使用 Tkinter 为这些按钮完成的代码:

  btn = Button(window, text="Exit Securely", command=exit)
btn.grid(column=2)
btn = Button(window, text="Add Entry", command=addEntry)
btn.grid(column=1)
btn = Button(window, text="Generate", command=run)
btn.grid(column=0)


lbl = Label(window, text="Website")
lbl.grid(row=3, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=3, column=1, padx=80)
lbl = Label(window, text="password")
lbl.grid(row=3, column=2, padx=80)

这使我的程序看起来像这样:

任何关于如何制作更好的 GUI 的一般提示或有用的链接也将不胜感激,因为我一直在努力解决这个问题。

【问题讨论】:

  • grid()中需要指定row,否则会占用下一个可用行。

标签: python user-interface tkinter button alignment


【解决方案1】:

正如@acw1668 所说,如果您未在grid() 中指定row,它将占用下一个可用行。

# Code to make this example work:
from tkinter import *

def addEntry():pass
def run():pass

window = Tk()

# Added `row=0` for each one of them
btn = Button(window, text="Exit Securely", command=exit)
btn.grid(row=0, column=2)
btn = Button(window, text="Add Entry", command=addEntry)
btn.grid(row=0, column=1)
btn = Button(window, text="Generate", command=run)
btn.grid(row=0, column=0)


# Changed the row to 1 for all of them
lbl = Label(window, text="Website")
lbl.grid(row=1, column=0, padx=80)
lbl = Label(window, text="Username")
lbl.grid(row=1, column=1, padx=80)
lbl = Label(window, text="password")
lbl.grid(row=1, column=2, padx=80)

顺便说一句,为不同的按钮/标签使用不同的名称是个好主意。

【讨论】:

  • 非常感谢,反正我很快就想通了,不过建议很感激,我现在​​就去做。
  • 如果你直接在答案中解释问题的根源,而不是参考别人说的话,这个答案会更好。
【解决方案2】:

我最近一直在尝试在程序窗口中对齐 tkinter 小部件的各种方法,而且我找到了更好的解决方案。

在您的程序中,您一直在使用grid 进行对齐。我会说你用place代替。

place 将允许您为小部件设置明确的 x 和 y 坐标,它会很容易使用。

如果我相应地更改您的代码,我可以向您展示代码(更改后)和输出图像。


代码(修改后)

# Code to make this example work:
from tkinter import *

def addEntry():pass
def run():pass

window = Tk()

# Adding geometry ettig.
window.geometry('500x500')

btn = Button(window, text="Exit Securely", command=exit)
btn.place(x=410, y=20)
btn = Button(window, text="Add Entry", command=addEntry)
btn.place(x=210, y=20)
btn = Button(window, text="Generate", command=run)
btn.place(x=10, y=20)


lbl = Label(window, text="Website")
lbl.place(x=10, y=50)
lbl = Label(window, text="Username")
lbl.place(x=210, y=50)
lbl = Label(window, text="password")
lbl.place(x=410, y=50)

输出屏幕

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2018-05-24
    • 2016-05-30
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多