I have been creating buttons through a for loop for a calculator. However, I'd like to make two buttons span two columns.
I know that by creating individual buttons we can write
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor = "hand2",activebackground = "#1E90FF", command = lambda: btn_eval(0))
zero.grid(row = 5, column = 0, columnspan = 2, padx = 1, pady = 1)
buttons = ['M+', 'M-', 'MR', 'MC',
'CA', 'Del', '/', 'hi',
'7', '8', '9', '*',
'4', '5', '6', '-',
'1', '2', '3', '+',
'0', '.', '=', 'bye'
]
count = 0
for row in range(2, 10):
for column in range(4):
button = Button(window, width = 10, fg = "black", height = 3, bd = 0, bg = '#fff',
cursor = 'hand2', activebackground = '#1e90ff', text = buttons[count],
command = lambda i=buttons[count]: self.functions(i)).grid(row=row, column=column)
count += 1
I am just putting "hi" and "bye" just to keep space but the buttons that I want to span 2 columns are "CA" and zero
Using a ternary condition (or a simple if) to set the columnspan accordingly should be possible:
buttons = ['M+', 'M-', 'MR', 'MC',
'CA', 'xxxxx', 'Del', '/', # the xxxxx will be skipped
'7', '8', '9', '*',
'4', '5', '6', '-',
'1', '2', '3', '+',
'0', 'xxxxx', '.', '='
]
count = 0
for row in range(2, 10):
for column in range(4):
if (row,column) in [(3,1),(9,1)]: # the xxxxx positions, no need to make a button
continue
cs = 2 if buttons[count] in ("0","CA") else 1
button = Button(window, width = 10, fg = "black", height = 3, bd = 0, bg = '#fff',
cursor = 'hand2', activebackground = '#1e90ff',
text = buttons[count],
command = lambda i=buttons[count]: self.functions(i)).grid(row=row,
column=column, columnspan = cs)
count += cs # to make indexes still work as is, increase by 2 when needed