如何将按钮彼此相邻放置?

时间:2021-01-14 11:38:48

标签: python tkinter

我有 2 个按钮 https://postimg.cc/DmSQHkbG

我想把它们放在一起

这是代码:

myButton = Button(root, text="Bitcoin ", padx=50, pady=50, command=myClick, bg="black", fg="red").pack()
#myButton.grid(row=0, column=0)
myButton2 = Button(root, text="Ethereum", padx=50, pady=50, command=myClick2, bg="gold", fg="green").pack()
#myButton2.grid(row=0, column=1)

当我像这样运行它并注释掉网格时,我的按钮位于彼此下方,当我使用网格运行它时,我收到此错误:

  File "button.py", line 30, in <module>
    myButton.grid(row=0, column=0)
AttributeError: 'NoneType' object has no attribute 'grid'

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

要使按钮大小相同,您可以将列配置为相同大小:

root.columnconfigure(0, weight = 1, minsize = 100)
root.columnconfigure(1, weight = 1, minsize = 100)

您必须在 pack() 和 grid() 之间进行选择,但是您同时使用了两者。您必须在行尾删除 .pack() 。所以你的代码应该是这样的:

myButton = Button(root, text="Bitcoinn ", padx=50, pady=50, command=myClick, bg="black", fg="red")
myButton.grid(row=0, column=0, sticky="nsew")
myButton2 = Button(root, text="Ethereum", padx=50, pady=50, command=myClick2, bg="gold", fg="green")
myButton2.grid(row=0, column=1, sticky="nsew")
root.mainloop()

我在 grid 函数中添加了 sticky 参数。此参数决定元素对齐哪一侧:n=north s=south e=east w=west。如果你像我一样把它们都放在里面:sticky="nsw" 它会填满整个网格字段。

要解决 myClick 的问题,您必须再次删除 .pack() 并在新行中写入价格:

def myClick():
    ...
    label1 = Label(root, text=str(price))
    label1.grid(row=1, column=0)
    ...

对于另一个

def myClick2():
    ...
    label2 = Label(root, text=str(price))
    label2.grid(row=1, column=1)
    ...