Как оптимизировать код с помощью цикла for

Roman3yk

Новичок
Пользователь
Май 1, 2020
3
0
1
Мне нужно заменить вот этот код (кнопки в калькуляторе на tkinter):
Python:
button0 = Button(text = "0", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(0)).grid(row = 4, column = 0)
button1 = Button(text = "1", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(1)).grid(row = 3, column = 0)
button2 = Button(text = "2", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(2)).grid(row = 3, column = 1)
button3 = Button(text = "3", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(3)).grid(row = 3, column = 2)
button4 = Button(text = "4", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(4)).grid(row = 2, column = 0)
button5 = Button(text = "5", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(5)).grid(row = 2, column = 1)
button6 = Button(text = "6", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(6)).grid(row = 2, column = 2)
button7 = Button(text = "7", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(7)).grid(row = 1, column = 0)
button8 = Button(text = "8", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(8)).grid(row = 1, column = 1)
button9 = Button(text = "9", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(9)).grid(row = 1, column = 2)
button10 = Button(text = "+", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('+')).grid(row = 1, column = 3)
button11 = Button(text = "-", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('-')).grid(row = 2, column = 3)
button12 = Button(text = "*", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('*')).grid(row = 3, column = 3)
button13 = Button(text = "/", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('/')).grid(row = 4, column = 3)
button14 = Button(text = "=", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('=')).grid(row = 4, column = 2)
button15 = Button(text = "C", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('C')).grid(row = 4, column = 1)
через цикл for.
Сделал что то такое, но это не работает, хотя ошибок нет:
Python:
BUTTON = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
TEXT =  ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '=', 'C']

for i, word in enumerate(BUTTON):
    BUTTON[i] = Button(text = TEXT[i], width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(TEXT[i]))
Знаю, код ужасный, но интересует только этот вопрос
Весь код:
Python:
from tkinter import *

mainstr = ''
WIDTH = '5'
HEIGHT = '2'
BG = 'white'

def click(number):
    global mainstr
    if number == '=':
        try:
            result = str(eval(mainstr))
            label.configure(text = result)
            mainstr = ''
        except:
            label.configure(text = 'error')
    elif number == 'C':
        mainstr = ''
        label.configure(text = '0')
    else:
        mainstr = mainstr + str(number)
        label.configure(text = mainstr)

window = Tk()
window.title("Калькулятор")
window.configure(bg = "grey")
label = Label(text = "0", width = '24', bg = "grey")
label.grid(row = 0, column = 0, columnspan = 4)

BUTTON = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
TEXT =  ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '=', 'C']

for i, word in enumerate(BUTTON):  # в word попадает строка из списка, а в i - ее индекс
    BUTTON[i] = Button(text = TEXT[i], width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(TEXT[i]))

"""
button0 = Button(text = "0", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(0)).grid(row = 4, column = 0)
button1 = Button(text = "1", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(1)).grid(row = 3, column = 0)
button2 = Button(text = "2", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(2)).grid(row = 3, column = 1)
button3 = Button(text = "3", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(3)).grid(row = 3, column = 2)
button4 = Button(text = "4", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(4)).grid(row = 2, column = 0)
button5 = Button(text = "5", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(5)).grid(row = 2, column = 1)
button6 = Button(text = "6", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(6)).grid(row = 2, column = 2)
button7 = Button(text = "7", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(7)).grid(row = 1, column = 0)
button8 = Button(text = "8", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(8)).grid(row = 1, column = 1)
button9 = Button(text = "9", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click(9)).grid(row = 1, column = 2)
button10 = Button(text = "+", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('+')).grid(row = 1, column = 3)
button11 = Button(text = "-", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('-')).grid(row = 2, column = 3)
button12 = Button(text = "*", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('*')).grid(row = 3, column = 3)
button13 = Button(text = "/", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('/')).grid(row = 4, column = 3)
button14 = Button(text = "=", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('=')).grid(row = 4, column = 2)
button15 = Button(text = "C", width = WIDTH, height = HEIGHT, bg = BG, command = lambda:click('C')).grid(row = 4, column = 1)
"""
BUTTON[0].grid(row = 4, column = 0)
BUTTON[1].grid(row = 3, column = 0)
BUTTON[2].grid(row = 3, column = 1)
BUTTON[3].grid(row = 3, column = 2)
BUTTON[4].grid(row = 2, column = 0)
BUTTON[5].grid(row = 2, column = 1)
BUTTON[6].grid(row = 2, column = 2)
BUTTON[7].grid(row = 1, column = 0)
BUTTON[8].grid(row = 1, column = 1)
BUTTON[9].grid(row = 1, column = 2)
BUTTON[10].grid(row = 1, column = 3)
BUTTON[11].grid(row = 2, column = 3)
BUTTON[12].grid(row = 3, column = 3)
BUTTON[13].grid(row = 4, column = 3)
BUTTON[14].grid(row = 4, column = 2)
BUTTON[15].grid(row = 4, column = 1)


label = Label(text = "0", width = '24', bg = "grey")
label.grid(row = 0, column = 0, columnspan = 4)
window.mainloop()
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Вот пример:
Python:
from tkinter import *

mainstr = ''
WIDTH = '5'
HEIGHT = '2'
BG = 'white'

def click(number):
    global mainstr
    if number == '=':
        try:
            result = str(eval(mainstr))
            label.configure(text = result)
            mainstr = ''
        except:
            label.configure(text = 'error')
    elif number == 'C':
        mainstr = ''
        label.configure(text = '0')
    else:
        mainstr = mainstr + str(number)
        label.configure(text = mainstr)


window = Tk()
window.title("Калькулятор")
window.configure(bg="grey")
label = Label(text="0", width='24', bg="grey")
label.grid(row=0, column=0, columnspan=4)

TEXT =  ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '=', 'C']
row = [4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 2, 3, 4, 4, 4]
column = [0, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 3, 3, 3, 2, 1]

for i, item in enumerate(TEXT):
    cmd=lambda x=TEXT[i]: click(x)

    Button(text=TEXT[i], width=WIDTH, height=HEIGHT, bg=BG, command=cmd).grid(row=row[i], column=column[i])


label = Label(text="0", width='24', bg="grey")
label.grid(row=0, column=0, columnspan=4)
window.mainloop()
 
  • Мне нравится
Реакции: Roman3yk

Roman3yk

Новичок
Пользователь
Май 1, 2020
3
0
1
Вот пример:
Python:
from tkinter import *

mainstr = ''
WIDTH = '5'
HEIGHT = '2'
BG = 'white'

def click(number):
    global mainstr
    if number == '=':
        try:
            result = str(eval(mainstr))
            label.configure(text = result)
            mainstr = ''
        except:
            label.configure(text = 'error')
    elif number == 'C':
        mainstr = ''
        label.configure(text = '0')
    else:
        mainstr = mainstr + str(number)
        label.configure(text = mainstr)


window = Tk()
window.title("Калькулятор")
window.configure(bg="grey")
label = Label(text="0", width='24', bg="grey")
label.grid(row=0, column=0, columnspan=4)

TEXT =  ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '=', 'C']
row = [4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 2, 3, 4, 4, 4]
column = [0, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 3, 3, 3, 2, 1]

for i, item in enumerate(TEXT):
    cmd=lambda x=TEXT[i]: click(x)

    Button(text=TEXT[i], width=WIDTH, height=HEIGHT, bg=BG, command=cmd).grid(row=row[i], column=column[i])


label = Label(text="0", width='24', bg="grey")
label.grid(row=0, column=0, columnspan=4)
window.mainloop()
Cпасибо!
 

Форум IT Специалистов