是否有一种方法可以通过循环跨越两个柱面生成一个按钮



我一直在通过用于计算器的循环创建按钮。但是,我想制作两个按钮跨越两个列。

我知道,通过创建单个按钮,我们可以编写

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

我只是为了保留空间,但是我想跨越2列的按钮是" ca",而零

使用三元条件(或简单的if(相应地设置列态:

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

最新更新