如何使tkinter按钮小部件占用网格的整个宽度

时间:2017-04-03 15:39:30

标签: python button tkinter

我已经尝试this,但它没有帮助。

我正在制作计算器程序。到目前为止,我已经做到了这一点:

from tkinter import *
window = Tk()

disp = Entry(window, state='readonly', readonlybackground="white")
disp.grid(column=0, row=0, columnspan=4)
#row 1
seven = Button(window, text="7", command=Seven)
seven.grid(column=1,row=1)

eight = Button(window, text="8", command=Eight)
eight.grid(column=2,row=1)

nine = Button(window, text="9", command=Nine)
nine.grid(column=3,row=1)

divide = Button(window, text="÷", command=Divide)
divide.grid(column=4,row=1)

#row 2

four = Button(window, text="4", command=Four)
four.grid(column=1,row=2)

five = Button(window, text="5", command=Five)
five.grid(column=2,row=2)

six = Button(window, text="6", command=Six)
six.grid(column=3,row=2)

multiply = Button(window, text="×", command=Multiply)
multiply.grid(column=4,row=2)

#row 3

one = Button(window, text="1", command=One)
one.grid(column=1,row=3)

two = Button(window, text="2", command=Two)
two.grid(column=2,row=3)

three = Button(window, text="3", command=Three)
three.grid(column=3,row=3)

minus = Button(window, text="-", command=Minus)
minus.grid(column=4,row=3)

#row 4

zero = Button(window, text="0", command=Zero)
zero.grid(column=1,row=4)

dec = Button(window, text=".", command=Dec)
dec.grid(column=2,row=4)

equal = Button(window, text="=", command=Equal)
equal.grid(column=3,row=4)

add = Button(window, text="+", command=Add)
add.grid(column=4,row=4)

window.mainloop()

这看起来像这样(我的声望太低,无法发布图片):https://i.imgsafe.org/268d2a57c1.jpg (编辑:图片链接折旧)

我希望盒子同样宽,并填满可用空间。 结果应类似于:http://python.6.x6.nabble.com/file/n4545517/skaiciavke.png

如何使按钮占据行/列的整个宽度?

1 个答案:

答案 0 :(得分:6)

两件事:

  1. 您将输入框设置为从第0列开始应用,但随后每个后续行都从第1列开始。在这方面要保持一致 - 你的7按钮应该在第0列,第8列等等。
  2. 当您.grid按钮时,请使用sticky=N+S+E+W。这将允许按钮按其各自的行和列大小进行扩展。
  3. 更新: N + S + E + W不适用于python3.6.7,它是nesw或这4个字母的任意组合。

    例如:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    from tkinter import *
    window = Tk()
    
    disp = Entry(window, state='readonly', readonlybackground="white")
    disp.grid(column=0, row=0, columnspan=4)
    #row 1
    seven = Button(window, text="7")
    seven.grid(column=0,row=1, sticky='nesw')
    
    eight = Button(window, text="8")
    eight.grid(column=1,row=1, sticky='nesw')
    
    nine = Button(window, text="9")
    nine.grid(column=2,row=1, sticky='nesw')
    
    divide = Button(window, text="÷")
    divide.grid(column=3,row=1, sticky='nesw')
    
    window.mainloop()
    

    返回一个如下所示的窗口:

    Tkinter buttons with sticky