0

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

tomerpacific
  • 3,092
  • 8
  • 22
  • 41

1 Answers1

0

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
Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
  • I have tried your solution removing the "xxxxx", it works but not quite as the buttons ("CA" and "0") overlaps with the buttons on their right side and leaves an indentation/ blank space on their left and only half of the texts on the 2 buttons can be seen for CA , I can only see C and for 0 it looks like a "C" , is there a way of shifting it back to column zero – introvert_guy Aug 01 '19 at 10:28
  • @introvert edited code - you probably need to skip the ranges where you do not place anything. I reordered the `'xxxxx'` as well - try that. – Patrick Artner Aug 01 '19 at 11:32