网格选项中的columnpan剂量功能

时间:2016-07-03 11:32:33

标签: python-3.x tkinter

我在tkinter中定义了一个按钮。然后我注意到按钮网格的选项。更改columnspan不会进行任何Visual更改,该按钮保持原样... http://www.tutorialspoint.com/python/tk_grid.htm 基于柱子的定义......它不应该是这样的。 在最后一个按钮的网格中设置columnspan不会做任何更改。

# myCal_Expt1.py
from tkinter import *
from decimal import *

#key press function
def click(btn_text):
    display.insert(END, btn_text)


#### main :

window = Tk()
window.title("My Calculator")

#create top_row frame

top_row = Frame(window)
top_row.grid(row=0, column=0, columnspan=2, sticky=N)

# use Entry for an editable display

display = Entry(top_row, width=45, bg= "light green")
display.grid()

#create num_pad_frame

num_pad = Frame(window)
num_pad.grid(row=1, column=0, sticky= W)

# provide a list of keys for the number pad:

num_pad_list = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3',
'0', '.', '=' ]
# create operator_frame

operator = Frame(window)
operator.grid(row=1, column=1, sticky=E)
operator_list = [ '*', '/', '+', '-', '(', ')', 'C' ]

# create operator buttons with a loop

r = 0
c = 0
for btn_text in operator_list:
    def cmd(x=btn_text):
        click(x)
    Button( operator, text=btn_text, width=3, command=cmd).grid(row=r,column=c)
    c = c + 1
    if c > 1:
       c = 0
       r = r + 1

# create num_oad buttons with a for loop

r = 0 # row counter
c = 0 # column counter

for btn_text in num_pad_list:
    def cmd(x=btn_text):
            click(x)
    Button(num_pad, text = btn_text , width=3, command=cmd).grid(row=r, column=c)
    c = c+1
    if c > 2:
        c = 0
        r = r + 1

# Adding another Frame
last_row = Frame(window)
last_row.grid(row = 2, column = 0, columnspan=2, sticky = S)

#adding another button(HERE!)

Button( last_row, text = "last", width= 20, command = click).grid(row = 5,     column = 0, columnspan = 2)

#### Run mainloop
window.mainloop()

1 个答案:

答案 0 :(得分:1)

在last_row框架内,您只有 一个按钮。您在row=5上设置了此按钮。这与将其设置为row=0相同,因为所有其他行和列无论如何都是空的。出于同样的原因,您应该删除此按钮的不必要的columnspan选项(因为last_row框架内没有要跨越的列:它们全部都是空的。)

然后你在2列上跨越last_row。关于你如何定位前面的帧,这很好。但是,您得到了以下结果,因为按钮将在last_row的中间由默认绘制,只要您将其宽度选项设置为:

enter image description here

要让按钮延伸到您期望的2列,您只需将其宽度设置为与display小部件width=45相同的宽度。

简单来说,您需要更改此行:

Button( last_row, text = "last", width= 20, command = click).grid(row = 5,     column = 0, columnspan = 2)

为:

Button( last_row, text="last", width=45, command=click).grid(row=0, column=0)

你会得到你想要的结果:

enter image description here