如何使按钮更紧密?

时间:2018-12-17 00:28:19

标签: python-2.7 tkinter

我正在尝试使用Tkinter制作一个简单的计算器,但是按钮相距太远。这是我的完整代码:

from Tkinter import *
root = Tk()
root.title("Calculadora")

display = Entry(root, font = ("Simplified Arabian Fixed", 30), bg = "black", fg = "white", bd = 30).grid(columnspan = 4)

Button7 = Button(root, bd = 10, text= "7", padx = 16, font = ("Simplified Arabian Fixed", 20), bg = "black", fg = "white").grid(column = 0, row = 1)

Button8 = Button(root, bd = 10, text = "8", padx = 16, font = ("Simplified Arabian Fixed", 20), bg = "black", fg = "white").grid(column = 1, row = 1)

Division = Button(root, bd = 10, text = "/", padx = 16, font = ("Simplified Arabian Fixed", 20), bg = "black", fg = "white").grid(column = 2, row = 1)

root.mainloop()

This occours

有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:1)

此效果是因为条目比三个按钮宽。您可以设置较小的宽度,然后使网格几何图形管理器将其扩展为使用sticky = 'ew'覆盖按钮的宽度。另外,您可能想在条目中设置justify = 'right',否则看起来会很有趣。

我在下面的示例中添加了一些文字:

from Tkinter import *
root = Tk()
root.title("Calculadora")

txt = StringVar()   # StringVar to hold entry text
txt.set('123456')   # Set StringVar

display = Entry(root, font = ("Simplified Arabian Fixed", 30), 
                bg = "black", fg = "white", bd = 30, textvariable = txt,
                # Set width and justify for entry + sticky to fill available space
                width = 1, justify = 'right').grid(columnspan = 4, sticky = 'ew')

Button7 = Button(root, bd = 10, text= "7", padx = 16,
                 font = ("Simplified Arabian Fixed", 20),
                 bg = "black", fg = "white").grid(column = 0, row = 1)

Button8 = Button(root, bd = 10, text = "8", padx = 16,
                 font = ("Simplified Arabian Fixed", 20),
                 bg = "black", fg = "white").grid(column = 1, row = 1)

Division = Button(root, bd = 10, text = "/", padx = 16,
                  font = ("Simplified Arabian Fixed", 20),
                  bg = "black", fg = "white").grid(column = 2, row = 1)

root.mainloop()

答案 1 :(得分:0)

使用sticky="ew"并在每个padx中调整grid(...)的按钮以展开按钮以填充网格单元。同样,您将grid(...)的结果分配给所有始终为None的按钮变量。因此,将grid(...)函数与创建函数分开,例如:

Button7 = Button(root, bd=10, text="7", padx=16, font=("Simplified Arabian Fixed", 20), bg="black", fg="white")
Button7.grid(row=1, column=0, sticky="ew", padx=2)