计算器应用程序的Python网格间距

2024-09-26 21:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

What I'm trying to achieve

What I have

我想把AC按钮和“0”按钮调大一些。我怎样才能做到这一点而不弄乱我的for循环?我试过columnspan,但它对我不起作用。你知道吗

buttons = [['AC' , '%', '+' ],
           ['7' , '8' , '9' , '-' ],
           ['4' , '5' , '6' , '*' ],
           ['1' , '2' , '3' , '/' ],
           ['0' , '.' , '=' ]]

for r in range(len(buttons)):
    for c in range(len(buttons[r])):

        def cmd(x = buttons[r][c]):
            self.click(x)

        b = Button(self,
                   text = buttons[r][c],
                   width = 3,
                   relief = RAISED,
                   command = cmd)
        b.grid(row = r + 1, column = c)

Tags: toinselfcmdforlenhaverange
2条回答

你需要给AC和zero按钮一个2的列跨度。这对于您当前的体系结构来说有点尴尬,但您可以尝试以下方法:

buttons = [['AC' , None, '%', '+' ],
           ['7' , '8' , '9' , '-' ],
           ['4' , '5' , '6' , '*' ],
           ['1' , '2' , '3' , '/' ],
           ['0' , None '.' , '=' ]]

for r in range(len(buttons)):
    for c in range(len(buttons[r])):

        if buttons[r][c] is None:
            continue
        def cmd(x = buttons[r][c]):
            self.click(x)

        b = Button(self,
                   text = buttons[r][c],
                   width = 3,
                   relief = RAISED,
                   command = cmd)
        if buttons[r][c] in ['AC', '0']:
            b.grid(row = r + 1, column = c, columnspan=2, sticky='EW')
        else:
            b.grid(row = r + 1, column = c)

不过,我可能会建议更像这样:

buttons = [
    ('AC', 0, 0, 2),
    ('%', 0, 2, 1),
    ('+', 0, 3, 1),
    ('7', 1, 0, 1),
    ('8', 1, 1, 1),
    ('9', 1, 2, 1),
    ('-', 1, 3, 1),
    ('4', 2, 0, 1),
    ('5', 2, 1, 1),
    ('6', 2, 2, 1),
    ('*', 2, 3, 1),
    ('1', 3, 0, 1),
    ('2', 3, 1, 1),
    ('3', 3, 2, 1),
    ('/', 3, 3, 1),
    ('0', 4, 0, 2),
    ('.', 4, 2, 1),
    ('=', 4, 3, 1)]


for label, row, column, span in buttons:
    def cmd(x=label):
        self.click(x)

    b = tkinter.Button(root,
               text = label,
               width = 3,
               relief = tkinter.RAISED,
               command = cmd)
    b.grid(row=row, column=column, columnspan=span, sticky='EW')

root.mainloop()

这有利于更明确一点,少一点黑客。你知道吗

可能有按钮名称和大小值的字典:

bsize = {'AC':6,'0':6,'1':3,'2':3 ...}

然后在定义要放置的大小时引用它:

buttons = [['AC' , '%', '+' ],
           ['7' , '8' , '9' , '-' ],
           ['4' , '5' , '6' , '*' ],
           ['1' , '2' , '3' , '/' ],
           ['0' , '.' , '=' ]]

for r in range(len(buttons)):
    for c in range(len(buttons[r])):

        def cmd(x = buttons[r][c]):
            self.click(x)

        b = Button(self,
                   text = buttons[r][c],
                   width = bsize[buttons[r][c]],
                   relief = RAISED,
                   command = cmd)
        b.grid(row = r + 1, column = c)

您可能还需要更改b.grid()参数。你知道吗

相关问题 更多 >

    热门问题